0

I understood that python functions are objects too and after defining them I stored them in a dictionary but the question is how can I run these stored functions in dictionary? And can I save these functions in a pickle file and use theme later in my codes? Is it possible? An example of storing these functions but the way of running theme... I don't know!

>>> def a():
    print('hello')
>>> b={'a':a}
>>> b['a']
<function a at 0x00000000033AE620>
>>> b['a'].run()

I need some method like run for thisfunction or at least view the function code!

1 Answer 1

4

Just call it like you would a normal function:

>>> def a():
...     print('hello')
...
>>> b={'a':a}
>>> b['a']
<function a at 0x02192468>
>>> b['a']()
hello
>>>

b['a'] returns the function object, so placing (...) after it will call it just like any other function object.

Sign up to request clarification or add additional context in comments.

5 Comments

Thanks but can I store these functions in a pickle file without a problem?
Yes; they have a resource pointer, and that will always be the same instance as long as the process lives.
@HamidFzM Picking functions is a tricky topic. Pickle will store only the qualified name of the function (e.g. mylib.util.add), and unpickling will look it up by that name. Sometimes that's a good thing, but it also has downsides (most importantly, it doesn't work in several advanced use cases). The alternatives (storing the functions's code) are even worse though.
For global functions without closures, using pickle is just fine. A string that'll allow re-importing the name is stored in the pickle, not the code.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.