Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 664
Mike Avatar asked Sep 01 '10 01:09

Mike


People also ask

How do I use a string module in Python?

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.


2 Answers

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

like image 106
Jeremy Brown Avatar answered Sep 21 '22 13:09

Jeremy Brown


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
like image 40
Remi Avatar answered Sep 19 '22 13:09

Remi