How to keep Dict[str, List] default method parameter as local to the method?
Peter Otten
__peter__ at web.de
Sun Jun 14 13:43:34 EDT 2020
zljubisic at gmail.com wrote:
> Hi,
>
> consider this example:
>
> from typing import Dict, List
>
>
> class chk_params:
> def execute(self, params: Dict[str, List] = None):
> if params is None:
> params = {}
>
> for k, v in params.items():
> params[k] = [val + 10 for val in v]
>
> return params.values()
>
> params = {
> 'A' : [1],
> 'B': [2],
> 'C': [3],
> 'D': [4],
> 'E': [5]
> }
> print(params)
> params_obj = chk_params()
>
> print(params_obj.execute(params = params))
> print(params)
>
> Output is:
> {'A': [1], 'B': [2], 'C': [3], 'D': [4], 'E': [5]}
> dict_values([[11], [12], [13], [14], [15]])
> {'A': [11], 'B': [12], 'C': [13], 'D': [14], 'E': [15]}
>
> I expected that last print statement will show original parameters A=1,
> B=2... but this is not the case.
>
> How to construct the method parameters, with params parameter as type of
> Dict[str, List], but at the same time keep params as local dictionary to
> the chk_params.execute() method?
The type annotations are only a distraction here; let's give classical
Python a chance with
- no type annotations
- no class
- dangerous default, for the thrill of it;)
def execute(params={}):
return [[val + 10 for val in v] for v in params.values()]
Clean and simple. If you insist on getting dict_values():
def execute(params={}):
return {k: [val + 10 for val in v] for k, v in params.items()}.values()
The relevant takeaway is: if you don't want to modify a value, don't modify
it. Do not wait for a const modifier to save you.
More information about the Python-list
mailing list