How can I handle a python dictionary with calls?

I would like to create a python directory whose values ​​must be evaluated separately.

So, for example, in the following non-working example, I define

a = {'key1': 'value1', 'key2': 42, 'key3': foo(20)}

for which, for example,

def foo(max):
    """Returns random float between 0 and max."""
    return max*random.random()

and after processing the dict I want to have, for example,

a_processes = {'key1': 'value1', 'key2': 42, 'key3': 12.238746374}

The example does not work, since the key value is key3immediately evaluated, and foo(20)not subject to a call. The way this might work would be to use something like

a = {'key1': 'value1', 'key2': 42, 'key3': foo}

but here they foowill miss their arguments. One way to handle this is to define a dict as follows.

a = {'key1': 'value1', 'key2': 42, 'key3': [foo, 20]}

with the following processing scheme

a_processed = dict([k,process(v)] for k,v in a.items())

in which processis a meaningful function that checks whether its argument is a list, or if the first element is callable, which is called with the rest of the arguments.

/ ?

+5
2

lambda , , :

>>> def foo(x):
...     return x*100
... 
>>> a = {'key1': 'value1', 'key2': 42, 'key3': lambda: foo(20)}
>>> a
{'key3': <function <lambda> at 0x96ae80c>, 'key2': 42, 'key1': 'value1'}
>>> {k: v() if callable(v) else v for k,v in a.iteritems()}
{'key3': 2000, 'key2': 42, 'key1': 'value1'}
+5

functools.partial(), , :

from functools import partial

a = {'key1': 'value1', 'key2': 42, 'key3': partial(foo, 20)}

key3 ; a['key3']() foo(20) .

"" ( callable() function:

{k: v() if callable(v) else v for k, v in a.iteritems()}

. Python 3, a.items() .

A functools.partial ( , foo() ):

a['key3']('additional', arguments='accepted')

, :

def CallablesDict(dict):
    def __getitem__(self, key):
        value = super(CallablesDict, self).__getitem__(key)
        return value() if callable(value) else value

a :

a = CallablesDict({'key1': 'value1', 'key2': 42, 'key3': partial(foo, 20)})

print a['key3']  # calls foo(20)
+8

All Articles