views:

61

answers:

2

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.

+2  A: 

Is this something what you're looking for ?

my_namespace = {}
exec "a = 5" in my_namespace
print my_namespace["a"]
Tarantula
i'd prefer not to need to refer to the namespace items using a string
Mike
+3  A: 

Here's an example of dynamically creating module objects using the imp module

Jeremy Brown
Yep, just the right way.
Alex Martelli
hrm... got my first ever downvote with this answer and I'm not sure why??
Jeremy Brown