Question: Dynamic code import

Lucio Torre lucio at movilogic.com
Thu Oct 25 18:40:50 EDT 2001


Károly Ladvánszky wrote:

>Being really new in the Pyhton world, I'm not sure what else than text files
>(.py) could come into view.
>To put it simple, I'd like to have a def  f11(a)  in a file and read it in
>and use f11 like the functions in the
>running script. Its something else than using 'import' as the file may not
>be existent at all when the script
>starts running. In Lisp, the 'load' function does this.
>

you can do import whenever you please.

 >>> if 0: import foo
...
 >>> if 1: import foo
...
Traceback (most recent call last):
  File "<stdin>", line 1, in ?
ImportError: No module named foo
 >>>

if you want to import and make sure the globals are locals are what you 
want, you can call __import__

__import__(name[, globals[, locals[, fromlist]]])
This function is invoked by the import statement.  It mainly exists so 
that you can replace it with another function that has a compatible 
interface, in order to change the  semantics of the import statement.  
For examples of why and how you would do this, see the standard library 
modules ihooks and rexec .  See also the built-in module imp , which 
defines some useful operations out of which you can build your own 
__import__() function.

For example, the statement "import spam" results in the following call: 
__import__('spam', globals(), locals(), []);  the statement "from 
spam.ham import eggs" results in "__import__('spam.ham', globals(), 
locals(), ['eggs'])". Note that even though locals() and ['eggs'] are 
passed in as arguments, the __import__() function does not set the local 
variable named eggs; this is done by subsequent code that is generated 
for the import statement.  (In fact, the standard implementation does 
not use its locals argument at all, and uses its globals only to 
determine the package context of the import statement.)







More information about the Python-list mailing list