Skip to content

Commit

Permalink
{Pylint} Fix use-dict-literal (Azure#30308)
Browse files Browse the repository at this point in the history
  • Loading branch information
atombrella authored Nov 28, 2024
1 parent d2cd62b commit a9c6b39
Show file tree
Hide file tree
Showing 45 changed files with 167 additions and 148 deletions.
1 change: 0 additions & 1 deletion pylintrc
Original file line number Diff line number Diff line change
Expand Up @@ -42,7 +42,6 @@ disable=
use-maxsplit-arg,
arguments-renamed,
consider-using-in,
use-dict-literal,
consider-using-dict-items,
consider-using-enumerate,
# These rules were added in Pylint >= 2.12, disable them to avoid making retroactive change
Expand Down
8 changes: 4 additions & 4 deletions scripts/temp_help/help_convert.py
Original file line number Diff line number Diff line change
Expand Up @@ -173,23 +173,23 @@ def get_all_mod_names():

def _get_new_yaml_dict(help_dict):

result = dict(version=1, content=[])
result = {"version": 1, "content": []}
content = result['content']

for command_or_group, yaml_text in help_dict.items():
help_dict = yaml.safe_load(yaml_text)

type = help_dict["type"]

elem = {type: dict(name=command_or_group)}
elem = {type: {"name": command_or_group}}
elem_content = elem[type]

_convert_summaries(old_dict=help_dict, new_dict=elem_content)

if "parameters" in help_dict:
parameters = []
for param in help_dict["parameters"]:
new_param = dict()
new_param = {}
if "name" in param:
options = param["name"].split()
new_param["name"] = max(options, key=lambda x: len(x))
Expand All @@ -205,7 +205,7 @@ def _get_new_yaml_dict(help_dict):
if "examples" in help_dict:
elem_examples = []
for ex in help_dict["examples"]:
new_ex = dict()
new_ex = {}
if "name" in ex:
new_ex["summary"] = ex["name"]
if "text" in ex:
Expand Down
2 changes: 1 addition & 1 deletion src/azure-cli-core/azure/cli/core/aaz/_field_value.py
Original file line number Diff line number Diff line change
Expand Up @@ -449,7 +449,7 @@ def to_serialized_data(self, processor=None, keep_undefined_in_list=False, # py

class AAZIdentityObject(AAZObject): # pylint: disable=too-few-public-methods
def to_serialized_data(self, processor=None, **kwargs):
calculate_data = dict()
calculate_data = {}
if self._data == AAZUndefined:
result = AAZUndefined

Expand Down
4 changes: 2 additions & 2 deletions src/azure-cli-core/azure/cli/core/command_recommender.py
Original file line number Diff line number Diff line change
Expand Up @@ -462,7 +462,7 @@ def get_parameter_kwargs(args):
:type: dict
"""

parameter_kwargs = dict()
parameter_kwargs = {}
for index, parameter in enumerate(args):
if parameter.startswith('-'):

Expand Down Expand Up @@ -501,7 +501,7 @@ def get_user_param_value(target_param):
:return: The replaced value for target_param
:type: str
"""
standard_source_kwargs = dict()
standard_source_kwargs = {}

for param, val in source_kwargs.items():
if param in param_mappings:
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -68,8 +68,7 @@ def get_op_handler(self, op_path):
def load_getter_op_arguments(self, getter_op_path, cmd_args=None):
""" Load arguments from function signature of getter command op """
op = self.get_op_handler(getter_op_path)
getter_args = dict(
extract_args_from_signature(op, excluded_params=EXCLUDED_PARAMS))
getter_args = dict(extract_args_from_signature(op, excluded_params=EXCLUDED_PARAMS))
cmd_args = cmd_args or {}
cmd_args.update(getter_args)
# The cmd argument is required when calling self.handler function.
Expand Down
4 changes: 2 additions & 2 deletions src/azure-cli-core/azure/cli/core/commands/parameters.py
Original file line number Diff line number Diff line change
Expand Up @@ -420,7 +420,7 @@ def expand(self, dest, model_type, group_name=None, patches=None):
return

if not patches:
patches = dict()
patches = {}

# fetch the documentation for model parameters first. for models, which are the classes
# derive from msrest.serialization.Model and used in the SDK API to carry parameters, the
Expand All @@ -440,7 +440,7 @@ def _expansion_validator_impl(namespace):
:return: The argument of specific type.
"""
ns = vars(namespace)
kwargs = dict((k, ns[k]) for k in ns if k in set(expanded_arguments))
kwargs = {k: ns[k] for k in ns if k in set(expanded_arguments)}

setattr(namespace, assigned_arg, model_type(**kwargs))

Expand Down
28 changes: 14 additions & 14 deletions src/azure-cli-core/azure/cli/core/commands/template_create.py
Original file line number Diff line number Diff line change
Expand Up @@ -59,22 +59,22 @@ def _validate_name_or_id(
resource_id_parts = parse_resource_id(property_value)
value_supplied_was_id = True
elif has_parent:
resource_id_parts = dict(
name=parent_value,
resource_group=resource_group_name,
namespace=parent_type.split('/')[0],
type=parent_type.split('/')[1],
subscription=get_subscription_id(cli_ctx),
child_name_1=property_value,
child_type_1=property_type)
resource_id_parts = {
"name": parent_value,
"resource_group": resource_group_name,
"namespace": parent_type.split('/')[0],
"type": parent_type.split('/')[1],
"subscription": get_subscription_id(cli_ctx),
"child_name_1": property_value,
"child_type_1": property_type}
value_supplied_was_id = False
else:
resource_id_parts = dict(
name=property_value,
resource_group=resource_group_name,
namespace=property_type.split('/')[0],
type=property_type.split('/')[1],
subscription=get_subscription_id(cli_ctx))
resource_id_parts = {
"name": property_value,
"resource_group": resource_group_name,
"namespace": property_type.split('/')[0],
"type": property_type.split('/')[1],
"subscription": get_subscription_id(cli_ctx)}
value_supplied_was_id = False
return (resource_id_parts, value_supplied_was_id)

Expand Down
4 changes: 2 additions & 2 deletions src/azure-cli-core/azure/cli/core/tests/test_util.py
Original file line number Diff line number Diff line change
Expand Up @@ -514,7 +514,7 @@ def test_handle_exception_httpoperationerror_typical_response_error(self, mock_l
# create test HttpOperationError Exception
err_msg = "Bad Request because of some incorrect param"
err_code = "BadRequest"
err = dict(error=dict(code=err_code, message=err_msg))
err = {"error": {"code": err_code, "message": err_msg}}
response_text = json.dumps(err)
mock_http_error = self._get_mock_HttpOperationError(response_text)

Expand All @@ -533,7 +533,7 @@ def test_handle_exception_httpoperationerror_error_key_has_string_value(self, mo

# create test HttpOperationError Exception
err_msg = "BadRequest"
err = dict(error=err_msg)
err = {"error": err_msg}
response_text = json.dumps(err)
mock_http_error = self._get_mock_HttpOperationError(response_text)

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ class CliTelemetryClient:
def __init__(self, batch=100, sender=None):
from azure.cli.telemetry.components.telemetry_logging import get_logger

self._clients = dict()
self._clients = {}
self._counter = 0
self._batch = batch
self._sender = sender or _NoRetrySender
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -107,11 +107,14 @@ def test_subscription_recording_processor_for_response(self):

for template in body_templates:
mock_sub_id = str(uuid.uuid4())
mock_response = dict({'body': {}})
mock_response['body']['string'] = template.format(mock_sub_id)
mock_response['headers'] = {'Location': [location_header_template.format(mock_sub_id)],
'azure-asyncoperation': [asyncoperation_header_template.format(mock_sub_id)],
'content-type': ['application/json']}
mock_response = {
'body': {'string': template.format(mock_sub_id)},
'headers': {
'Location': [location_header_template.format(mock_sub_id)],
'azure-asyncoperation': [asyncoperation_header_template.format(mock_sub_id)],
'content-type': ['application/json'],
}
}
rp.process_response(mock_response)
self.assertEqual(mock_response['body']['string'], template.format(replaced_subscription_id))

Expand All @@ -127,11 +130,12 @@ def test_recording_processor_skip_body_on_unrecognized_content_type(self):
rp = SubscriptionRecordingProcessor(replaced_subscription_id)

mock_sub_id = str(uuid.uuid4())
mock_response = dict({'body': {}})
mock_response['body']['string'] = mock_sub_id
mock_response['headers'] = {
'Location': [location_header_template.format(mock_sub_id)],
'content-type': ['application/foo']
mock_response = {
'body': {'string': mock_sub_id},
'headers': {
'Location': [location_header_template.format(mock_sub_id)],
'content-type': ['application/foo'],
}
}

# action
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -108,7 +108,7 @@ def acr_connected_registry_create(cmd, # pylint: disable=too-many-locals, too-m
client_token_list[i] = build_token_id(
subscription_id, resource_group_name, registry_name, client_token_name)

notifications_set = set(list(notifications)) \
notifications_set = set(notifications) \
if notifications else set()

ConnectedRegistry, LoggingProperties, SyncProperties, ParentProperties = cmd.get_models(
Expand Down Expand Up @@ -192,10 +192,10 @@ def acr_connected_registry_update(cmd, # pylint: disable=too-many-locals, too-m
client_token_list = list(client_token_set) if client_token_set != current_client_token_set else None

# Add or remove from the current notifications list
add_notifications_set = set(list(add_notifications)) \
add_notifications_set = set(add_notifications) \
if add_notifications else set()

remove_notifications_set = set(list(remove_notifications)) \
remove_notifications_set = set(remove_notifications) \
if remove_notifications else set()

duplicate_notifications = set.intersection(add_notifications_set, remove_notifications_set)
Expand Down
2 changes: 1 addition & 1 deletion src/azure-cli/azure/cli/command_modules/acr/task.py
Original file line number Diff line number Diff line change
Expand Up @@ -1130,7 +1130,7 @@ def _build_identities_info(cmd, identities, is_remove=False):
identity = IdentityProperties(type=identity_types)
if external_identities:
if is_remove:
identity.user_assigned_identities = {e: None for e in external_identities}
identity.user_assigned_identities = dict.fromkeys(external_identities)
else:
identity.user_assigned_identities = {e: UserIdentityProperties() for e in external_identities}
return identity
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -155,7 +155,7 @@ def __init__(
self.raw_param = raw_parameters
self.models = models
self.decorator_mode = decorator_mode
self.intermediates = dict()
self.intermediates = {}

def get_intermediate(self, variable_name: str, default_value: Any = None) -> Any:
"""Get the value of an intermediate by its name.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4139,10 +4139,10 @@ def _get_cluster_autoscaler_profile(self, read_only: bool = False) -> Union[Dict
if cluster_autoscaler_profile and self.mc and self.mc.auto_scaler_profile:
# shallow copy should be enough for string-to-string dictionary
copy_of_raw_dict = self.mc.auto_scaler_profile.__dict__.copy()
new_options_dict = dict(
(key.replace("-", "_"), value)
for (key, value) in cluster_autoscaler_profile.items()
)
new_options_dict = {
key.replace("-", "_"): value
for key, value in cluster_autoscaler_profile.items()
}
copy_of_raw_dict.update(new_options_dict)
cluster_autoscaler_profile = copy_of_raw_dict

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@
logger.addHandler(logging.StreamHandler())
__path__ = __import__('pkgutil').extend_path(__path__, __name__)
exceptions = []
test_map = dict()
test_map = {}
SUCCESSED = "successed"
FAILED = "failed"

Expand Down Expand Up @@ -56,7 +56,7 @@ def wrapper(*args, **kwargs):
func_to_call = get_func_to_call()
logger.info("running %s()...", func.__name__)
try:
test_map[func.__name__] = dict()
test_map[func.__name__] = {}
test_map[func.__name__]["result"] = SUCCESSED
test_map[func.__name__]["error_message"] = ""
test_map[func.__name__]["error_stack"] = ""
Expand Down
22 changes: 11 additions & 11 deletions src/azure-cli/azure/cli/command_modules/appservice/custom.py
Original file line number Diff line number Diff line change
Expand Up @@ -1001,7 +1001,7 @@ def set_webapp(cmd, resource_group_name, name, slot=None, skip_dns_registration=
instance = kwargs['parameters']
client = web_client_factory(cmd.cli_ctx)
updater = client.web_apps.begin_create_or_update_slot if slot else client.web_apps.begin_create_or_update
kwargs = dict(resource_group_name=resource_group_name, name=name, site_envelope=instance)
kwargs = {"resource_group_name": resource_group_name, "name": name, "site_envelope": instance}
if slot:
kwargs['slot'] = slot

Expand Down Expand Up @@ -1103,7 +1103,7 @@ def set_functionapp(cmd, resource_group_name, name, slot=None, **kwargs):
instance = kwargs['parameters']
client = web_client_factory(cmd.cli_ctx)
updater = client.web_apps.begin_create_or_update_slot if slot else client.web_apps.begin_create_or_update
kwargs = dict(resource_group_name=resource_group_name, name=name, site_envelope=instance)
kwargs = {"resource_group_name": resource_group_name, "name": name, "site_envelope": instance}
if slot:
kwargs['slot'] = slot

Expand Down Expand Up @@ -3870,7 +3870,7 @@ def __init__(self,
linux=False,
is_auto_update=None):
self.display_name = display_name
self.configs = configs if configs is not None else dict()
self.configs = configs if configs is not None else {}
self.github_actions_properties = github_actions_properties
self.linux = linux
self.is_auto_update = is_auto_update
Expand Down Expand Up @@ -4225,7 +4225,7 @@ def _format_version_name(cls, name):
def _format_version_names(self, runtime_to_version):
formatted_runtime_to_version = {}
for runtime, versions in runtime_to_version.items():
formatted_runtime_to_version[runtime] = formatted_runtime_to_version.get(runtime, dict())
formatted_runtime_to_version[runtime] = formatted_runtime_to_version.get(runtime, {})
for version_name, version_info in versions.items():
formatted_name = self._format_version_name(version_name)
if formatted_name in formatted_runtime_to_version[runtime]:
Expand Down Expand Up @@ -4268,7 +4268,7 @@ def _parse_raw_stacks(self, stacks):
'github_actions_properties': self.GithubActionsProperties(**github_actions_properties)
}

runtime_to_version[runtime_name] = runtime_to_version.get(runtime_name, dict())
runtime_to_version[runtime_name] = runtime_to_version.get(runtime_name, {})
runtime_to_version[runtime_name][runtime_version] = runtime_version_properties

runtime_to_version = self._format_version_names(runtime_to_version)
Expand Down Expand Up @@ -4337,8 +4337,8 @@ def __init__(self, name=None, version=None, is_preview=False, supported_func_ver
self.is_preview = is_preview
self.supported_func_versions = [] if not supported_func_versions else supported_func_versions
self.linux = linux
self.app_settings_dict = dict() if not app_settings_dict else app_settings_dict
self.site_config_dict = dict() if not site_config_dict else site_config_dict
self.app_settings_dict = {} if not app_settings_dict else app_settings_dict
self.site_config_dict = {} if not site_config_dict else site_config_dict
self.app_insights = app_insights
self.default = default
self.github_actions_properties = github_actions_properties
Expand Down Expand Up @@ -4460,7 +4460,7 @@ def _format_version_name(cls, name):
def _format_version_names(self, runtime_to_version):
formatted_runtime_to_version = {}
for runtime, versions in runtime_to_version.items():
formatted_runtime_to_version[runtime] = formatted_runtime_to_version.get(runtime, dict())
formatted_runtime_to_version[runtime] = formatted_runtime_to_version.get(runtime, {})
for version_name, version_info in versions.items():
formatted_name = self._format_version_name(version_name)
if formatted_name in formatted_runtime_to_version[runtime]:
Expand Down Expand Up @@ -4497,12 +4497,12 @@ def _parse_minor_version(self, runtime_settings, major_version_name, minor_versi
self.KEYS.GIT_HUB_ACTION_SETTINGS: runtime_settings.git_hub_action_settings
}

runtime_to_version[runtime_name] = runtime_to_version.get(runtime_name, dict())
runtime_to_version[runtime_name] = runtime_to_version.get(runtime_name, {})
runtime_to_version[runtime_name][minor_version_name] = runtime_version_properties

# obtain end of life date for all runtime versions
if runtime_settings.end_of_life_date is not None:
runtime_to_version_eol[runtime_name] = runtime_to_version_eol.get(runtime_name, dict())
runtime_to_version_eol[runtime_name] = runtime_to_version_eol.get(runtime_name, {})
runtime_to_version_eol[runtime_name][minor_version_name] = runtime_settings.end_of_life_date

def _create_runtime_from_properties(self, runtime_name, version_name, version_properties, linux):
Expand Down Expand Up @@ -5000,7 +5000,7 @@ def create_functionapp(cmd, resource_group_name, name, storage_account, plan=Non

site_config_dict = matched_runtime.site_config_dict if not flexconsumption_location \
else SiteConfigPropertiesDictionary()
app_settings_dict = matched_runtime.app_settings_dict if not flexconsumption_location else dict()
app_settings_dict = matched_runtime.app_settings_dict if not flexconsumption_location else {}

con_string = _validate_and_get_connection_string(cmd.cli_ctx, resource_group_name, storage_account)

Expand Down
4 changes: 2 additions & 2 deletions src/azure-cli/azure/cli/command_modules/backup/custom.py
Original file line number Diff line number Diff line change
Expand Up @@ -456,7 +456,7 @@ def assign_identity(client, resource_group_name, vault_name, system_assigned=Non

if user_assigned is not None:
userid = UserIdentity()
user_assigned_identity = dict()
user_assigned_identity = {}
for userMSI in user_assigned:
user_assigned_identity[userMSI] = userid
if system_assigned is not None or curr_identity_type in ["systemassigned", "systemassigned, userassigned"]:
Expand Down Expand Up @@ -499,7 +499,7 @@ def remove_identity(client, resource_group_name, vault_name, system_assigned=Non
userid = None
remove_count_of_userMSI = 0
totaluserMSI = 0
user_assigned_identity = dict()
user_assigned_identity = {}
for element in curr_identity_details.user_assigned_identities.keys():
if element in user_assigned:
remove_count_of_userMSI += 1
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@
logger.addHandler(logging.StreamHandler())
__path__ = __import__('pkgutil').extend_path(__path__, __name__)
exceptions = []
test_map = dict()
test_map = {}
SUCCESSED = "successed"
FAILED = "failed"

Expand Down Expand Up @@ -57,7 +57,7 @@ def wrapper(*args, **kwargs):
func_to_call = get_func_to_call()
logger.info("running %s()...", func.__name__)
try:
test_map[func.__name__] = dict()
test_map[func.__name__] = {}
test_map[func.__name__]["result"] = SUCCESSED
test_map[func.__name__]["error_message"] = ""
test_map[func.__name__]["error_stack"] = ""
Expand Down
Loading

0 comments on commit a9c6b39

Please sign in to comment.