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?


On 2020-06-14 08:20:46 -0700, zljubisic at gmail.com wrote:
> 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.

Others have already explained that.

> 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?

Take one step back. What you really want is for chk_params.execute to
return the new values and not to modify the old dict. Whether or not
params is a "local dictionary" (that doesn't really make much sense in
Python[1]) is an irrelevant implementation detail.

So lets do that:

class chk_params:
    def execute(self, params: Dict[str, List] = None):
        if params is None:
            params = {}

        result = {}
        for k, v in params.items():
            result[k] = [val + 10 for val in v]

        return result.values()

Of course at this point I notice that you are building a dict which you
don't need, so I would simplify that further:

class chk_params:
    def execute(self, params: Dict[str, List] = None):
        if params is None:
            params = {}

        result = []
        for k, v in params.items():
            result.append([val + 10 for val in v])

        return result

        hp

[1] There is a very good talk by Raymond Hettinger on how variables and
    objects in Python work. Unfortunately I can't find it at the moment.

-- 
   _  | Peter J. Holzer    | Story must make more sense than reality.
|_|_) |                    |
| |   | hjp at hjp.at         |    -- Charles Stross, "Creative writing
__/   | http://www.hjp.at/ |       challenge!"
-------------- next part --------------
A non-text attachment was scrubbed...
Name: signature.asc
Type: application/pgp-signature
Size: 833 bytes
Desc: not available
URL: <http://mail.python.org/pipermail/python-list/attachments/20200614/34aa0641/attachment.sig>