git.net

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

How to keep Dict[str, List] default method parameter as local to the method?


zljubisic at gmail.com writes:

> 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 execute method modifies the dict being passed into it.  If you don't
want that behaviour, you can pass in a copy of your params object.
dict(params) will make a shallow copy, which will work in this
particular case.

If the execute method were to do in-place modification operation on the
values (perhaps using v.append or v.extend in its loop), you'd need a
deep copy provided by the standard library's copy.deepcopy function.

-- 
regards,
kushal