Tuesday, 29 December 2020

Python, import string of Python code as module

In python you can do something like this to import a module using a string filename, and assign its namespace a variable on the local namespace.

x = __import__(str)

I'm wondering if there is a related function that will take take a string of Python code, instead of a path to a file with Python code, and return its namespace as a variable.

For example,

str = "a = 5";
x = importstr(str)
print x.a
#output is 5

I realize that I could write the string to a file, then use __import__ on it, but I'd like to skip the intermediate file if possible.

The reason for this is that I'm experimenting with metaprogramming in python, and it seems like a good solution to what I'm doing.



from Python, import string of Python code as module

No comments:

Post a Comment