Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to compile a string of Python code into a module whose functions can be called?

Tags:

python

In Python, I have a string of some Python source code containing functions like:

mySrc = '''
def foo():
    print("foo")

def bar():
    print("bar")
'''

I'd like to compile this string into some kind of module-like object so I can call the functions contained in the code.

Here's pseudo-code for what I'd like to do:

myMod = myCompile(mySrc)
myMod.foo()

Is this possible in Python? I've tried this, but it does not work:

myMod = compile(mySrc, '', 'exec')
myMod.foo()

This produces an error message like this:

<code object <module> at 0x104154730, file "", line 1>Traceback (most recent call last):
  File "myfile.py", line XX, in run
    myMod.foo()
AttributeError: 'code' object has no attribute 'foo'
like image 810
Todd Ditchendorf Avatar asked Nov 08 '13 01:11

Todd Ditchendorf


People also ask

How do you compile a string in Python?

The compile() method takes in the following parameters: source - a normal string, a byte string, or an AST object. filename - file from which the code is to be read. mode - exec (can take a code block with statements, class and functions ), eval (accepts single expression) or single (has a single interactive statement)

How do you call a function from a string in Python?

Use locals() and globals() to Call a Function From a String in Python. Another way to call a function from a string is by using the built-in functions locals() and globals . These two functions return a Python dictionary that represents the current symbol table of the given source code.

Can Python code be compiled?

For the most part, Python is an interpreted language and not a compiled one, although compilation is a step. Python code, written in . py file is first compiled to what is called bytecode (discussed in detail further) which is stored with a . pyc or .

What is __ module __?

The __module__ property is intended for retrieving the module where the function was defined, either to read the source code or sometimes to re-import it in a script.

What is the Python compile () function?

The Python compile() function is a built-in Python function that compiles a source ( normal string, byte string or an AST object) into a code or AST object.

How to compile Python code to a code object?

Code: Here we will read the file content as a string and then compile it to a code object. Here eval is used when the source is a single expression. # working of compile () with eval. If the Python code is in string form or is an AST object, and you want to change it to a code object, then you can use compile () method.

What is the string module in Python?

In this lesson, you’ll learn about the string module. This module will help you quickly access some string constants. Here’s an example: You can check out the Python documentation on the string module. 00:00 In this section, you’ll learn all about Python’s standard library. Let’s start with the string module.

How to run an executable code from a Python file?

# Running the executable code. # Another Python code to demonstrate working of compile (). In this example, we will take main.py file with some string display methods, and then we read the file content and compile it to code the object and execute it. Code: Here we will read the file content as a string and then compile it to a code object.


1 Answers

You have to both compile and execute it:

myMod = compile(mySrc, '', 'exec')
exec(myMod)
foo()

You can pass dicts to exec to stop foo from “leaking” out. Combine it with a module object created using types.ModuleType:

from types import ModuleType
…
compiled = compile(mySrc, '', 'exec')
module = ModuleType("testmodule")
exec(compiled, module.__dict__)
like image 74
Ry- Avatar answered Sep 19 '22 03:09

Ry-