__import__
Ryan Paul
segphault at sbcglobal.net
Sat May 8 03:58:59 EDT 2004
On Sat, 08 May 2004 00:31:58 -0700, Coder Coder wrote:
> Hi,
> Can someone help me with how to overload the __import__ function,
> so that I can call the old __import__ function and if it cannot find
> the library to be able to do something else.
>
> - Thanks.
The documentation has a small example of import
overload:
http://docs.python.org/lib/examples-imp.html but a better example
David Mertz (my personal hero!) does an excellent job of explaining it
simply:
""""
__import__(s [,globals=globals() [,locals=locals() [,fromlist]]])
Import the module named 's', using namespace dictionaries
'globals' and 'locals'. The argument 'fromlist' may be
omitted, but if specified as a nonempty list of
strings--e.g., '[""]'--the fully qualified subpackage will
be imported. For normal cases, the `import` statement is
the way you import modules, but in the special circumstance
that the value of 's' is not determined until runtime, use
`__import__()`.
>>> op = __import__('os.path',globals(),locals(),[''])
>>> op.basename('/this/that/other')
'other'
""" (I stole this from his web site: http://gnosis.cx/TPiP/appendix_a.txt)
He discusses usage of __import__ in his excellent essay on metaclass
programming:
http://gnosis.cx/publish/programming/metaclass_1.txt
You can also find an example in part of his 'Gnosis' library:
http://gnosis.cx/download/gnosis/magic/__init__.py
Have Fun!
More information about the Python-list
mailing list