0

For example,

I want to create a function object from .

mystr = \
"""
def foo(a=1): 
    print a
    pass
"""

However, using compile(mystr) will only give me a code object. I want to have module level function object just like the string is part of the source code.

Can this be achieved?

3 Answers 3

4

exec mystr

will execute the code you have given.

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

Comments

2

Yes use exec:

>>> mystr = \
"""
def foo(a=1): 
    print a
    pass
"""
>>> exec mystr
>>> foo
<function foo at 0x0274F0F0>

Comments

0

You can also use compile here, it supports modes like exec,eval,single:

In [1]: mystr = \
"""
def foo(a=1): 
        print a
        pass
"""
   ...: 

In [2]: c=compile(mystr,"",'single')

In [3]: exec c

In [4]: foo
Out[4]: <function __main__.foo>

help on compile:

In [5]: compile?
Type:       builtin_function_or_method
String Form:<built-in function compile>
Namespace:  Python builtin
Docstring:
compile(source, filename, mode[, flags[, dont_inherit]]) -> code object

Compile the source string (a Python module, statement or expression)
into a code object that can be executed by the exec statement or eval().
The filename will be used for run-time error messages.
The mode must be 'exec' to compile a module, 'single' to compile a
single (interactive) statement, or 'eval' to compile an expression.
The flags argument, if present, controls which future statements influence
the compilation of the code.
The dont_inherit argument, if non-zero, stops the compilation inheriting
the effects of any future statements in effect in the code calling
compile; if absent or zero these statements do influence the compilation,
in addition to any features explicitly specified.

1 Comment

What's the advantage of using compile and then exec if exec alone does the job?

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.