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.
Python string module contains a single utility function - capwords(s, sep=None). This function split the specified string into words using str. split(). Then it capitalizes each word using str.
Here's an example of dynamically creating module objects using the imp module
Here is how to import a string as a module:
import sys,imp
my_code = 'a = 5'
mymodule = imp.new_module('mymodule')
exec my_code in mymodule.__dict__
so you can now access the module attributes (and functions, classes etc) as:
mymodule.a
>>> 5
To ignore any next attempt to import, add the module to sys
:
sys.modules['mymodule'] = mymodule
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With