Skip to content Skip to sidebar Skip to footer

How To Declare A Dictionary With Inline Function

Do I have to formally define a function before I can use it as an element of a dictionary? def my_func(): print 'my_func' d = { 'function': my_func } I would rather define th

Solution 1:

The answer seems to be that there is no way to declare a function inline a dictionary definition in python. Thanks to everyone who took the time to contribute.

Solution 2:

Do you really need a dictionary, or just getitem access?

If the latter, then use a class:

>>>classDispatch(object):...deffuncA(self, *args):...print('funcA%r' % (args,))...deffuncB(self, *args):...print('funcB%r' % (args,))...def__getitem__(self, name):...returngetattr(self, name)...>>>d = Dispatch()>>>>>>d['funcA'](1, 2, 3)
funcA(1, 2, 3)

Solution 3:

You could use a decorator:

func_dict = {}

defregister(func):
    func_dict[func.__name__] = func
    return func

@registerdefa_func():
    pass@registerdefb_func():
    pass

The func_dict will end up mapping using the entire name of the function:

>>> func_dict
{'a_func': <function a_func at 0x000001F6117BC950>, 'b_func': <function b_func at 0x000001F6117BC8C8>}

You can modify the key used by register as desired. The trick is that we use the __name__ attribute of the function to get the appropriate string.

Solution 4:

consider using lambdas, but note that lambdas must be functions and cannot contain statements(see http://docs.python.org/reference/expressions.html#lambda)

e.g.

d = { 'func': lambda x: x + 1 }
# call d['func'](2) will return 3

Also, note that in python2, print is not a function. So you have to do either:

from __future__ import print_function

d = {
    'function': print
}

or use sys.stdout.write instead

d = {
    'function': sys.stdout.write
}

Solution 5:

Some functions can be easily 'inlined' anonymously with lambda expressions, e.g.:

>>>d={'function': lambda x : x**2}>>>d['function'](5)
25

But for anything semi-complex (or using statements) you probably just should define them beforehand.

Post a Comment for "How To Declare A Dictionary With Inline Function"