PytLab
PytLab

Reputation: 527

what is "dynamically generated function" in python

I meet a method in a class. when i tried to find the source code of the method in ipython, i get information like below:

In [9]: model.elementary_rates??
Type:        function
String form: <function elementary_rates at 0x06864170>
File:        Dynamically generated function. No source code available.
Definition:  model.elementary_rates(rate_constants, theta, p, mpf, matrix)
Docstring:   <no docstring>

What is the "dynamically generated function"? Could you provide me some information or examples of it?

Upvotes: 1

Views: 230

Answers (2)

unutbu
unutbu

Reputation: 880389

You could get a "Dynamically generated function" if the function is created by exec:

In [34]: code = compile('def f():\n    return 3', '<string>', 'exec')

In [35]: exec code

In [36]: f?
Type:       function
String Form:<function f at 0x7f6db467ac80>
File:       Dynamically generated function. No source code available.
Definition: f()
Docstring:  <no docstring>

Upvotes: 2

Simeon Visser
Simeon Visser

Reputation: 122466

The function wasn't defined in a file but it was created on the fly, for example:

>>> globals()['f'] = lambda: 3
>>>
>>> f
<function <lambda> at 0x10f337cf8>
>>> f()
3
>>> import inspect
>>> inspect.getsource(f)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/opt/local/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/inspect.py", line 701, in getsource
    lines, lnum = getsourcelines(object)
  File "/opt/local/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/inspect.py", line 690, in getsourcelines
    lines, lnum = findsource(object)
  File "/opt/local/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/inspect.py", line 538, in findsource
    raise IOError('could not get source code')
IOError: could not get source code

There are various ways of creating a function but in case the source code can't be retrieved (such as module, filename, location in the file, etc) then the function can be considered a dynamically generated function.

The following line creates a function called f which returns the value 3 when called:

globals()['f'] = lambda: 3

The globals() call means it's added to the global namespace, which is where you're at when the interpreter is running.

Upvotes: 2

Related Questions