Module Name Conflicts
Bengt Richter
bokr at oz.net
Thu Aug 18 22:46:39 EDT 2005
On Thu, 18 Aug 2005 16:46:42 -0700, Robert Kern <rkern at ucsd.edu> wrote:
>Dan Sommers wrote:
>
>> Assuming you can fiddle with sys.path at the right times, you can call
>> an imported module anything you want:
>>
>> fix_sys_path_to_find_java_cmd_first()
>> import cmd as java_cmd
>> fix_sys_path_to_find_python_cmd_first()
>> import cmd as python_cmd
>>
>> Obviously, then, 'cmd' does not reference either module; you'd have to
>> use java_cmd and python_cmd as appropriate.
>
>That doesn't work. The first module is recorded as 'cmd' in sys.modules
>and gets reused on the second import.
>
>[~]$ mkdir foo1
>[~]$ mkdir foo2
>[~]$ touch foo1/blah.py
>[~]$ touch foo2/blah.py
>[~]$ python
>Python 2.4.1 (#2, Mar 31 2005, 00:05:10)
>[GCC 3.3 20030304 (Apple Computer, Inc. build 1666)] on darwin
>Type "help", "copyright", "credits" or "license" for more information.
> >>> import sys
> >>> sys.path.insert(0,'foo1')
> >>> import blah as blah1
> >>> sys.path.insert(0,'foo2')
> >>> import blah as blah2
> >>> sys.modules['blah']
><module 'blah' from 'foo1/blah.py'>
> >>> blah2.__file__
>'foo1/blah.py'
> >>>
>
How about (untested)
import new
blah1 = new.module('blah')
execfile('./foo1/blah.py', blah1.__dict__)
blah2 = new.module('blah')
execfile('./foo2/blah.py', blah2.__dict__)
Of course, there is the issue of caching .pyc's and what to put in
sys.path and sys.modules, but blah1 and blah2 ought to be usable, I think.
Regards,
Bengt Richter
More information about the Python-list
mailing list