Anonymous dynamic import
Maric Michaud
maric at aristote.info
Mon Aug 28 19:53:46 EDT 2006
Le lundi 28 août 2006 22:15, Christian Convey a écrit :
> I've looked at using imp.load_source() or imp.load_module(), but it looks
> to me like all of these polute the global namespace with the names of the
> modules I'm importing.
Really ? They don't. (there are some quirks in my little function)
In [1]: def importer(*mods):
...: import imp
...: from os import path as _p
...: for i in mods :
...: n, p = _p.splitext(_p.split(i)[1])[0], _p.dirname(i)
...: print imp.load_module(n,*imp.find_module(n, [p]))
...:
...:
In [2]:
importer('temp', 'temp.py', 'test', 'test/', './test', 'test/__init__.py', 'test/mod', 'test/mod.py')
<module 'temp' from 'temp.pyc'>
<module 'temp' from 'temp.pyc'>
<module 'test' from 'test/__init__.py'>
<module '' from 'test/__init__.pyc'> <--- here
<module 'test' from './test/__init__.pyc'>
<module '__init__' from 'test/__init__.pyc'> <--- and here
<module 'mod' from 'test/mod.py'>
<module 'mod' from 'test/mod.pyc'>
In [3]: temp
...
NameError: name 'temp' is not defined
Neither do a simple import in a function scope :
In [14]: def f() : import temp
....:
In [15]: f()
In [16]: temp
...
NameError: name 'temp' is not defined
But maybe you are worried by the sys.modules repository ? I don't see why it
could be a problem, but if this is the case you can't use import machinery,
You could go that way :
#temp.py
A=0
def test_execfile() : print A
In [1]: d={}
In [2]: execfile('temp.py',d, d)
In [3]: d['test_execfile']
Out[3]: <function test_execfile at 0xa7587dbc>
In [4]: d['test_execfile']()
0
In [5]: d['A'] = 1
In [6]: d['test_execfile']()
1
--
_____________
Maric Michaud
_____________
Aristote - www.aristote.info
3 place des tapis
69004 Lyon
Tel: +33 426 880 097
More information about the Python-list
mailing list