Module Conflicts

Gabriel Genellina gagsl-py2 at yahoo.com.ar
Fri Apr 11 00:05:52 EDT 2008


En Thu, 10 Apr 2008 17:41:29 -0300, Ivan Illarionov  
<ivan.illarionov at gmail.com> escribió:
> On Apr 11, 12:31 am, Ivan Illarionov <ivan.illario... at gmail.com>
> wrote:
>> On Apr 10, 2:33 am, Jose <jfgome... at gmail.com> wrote:
>>
>> > I have a module named math.py in a package with some class
>> > definitions.  I am trying to import the standard python math module
>> > inside of math.py but It seems to be importing itself.  Is there any
>> > way around this problem without renaming my math.py file?
>>
>> Yes, if you are using Python 2.5
>>
>> from __future__ import absolute_import
>>
>> after this `import math` will always import standard math module and
>> `from . import math` will import your module.
>
> And it's relatively easy to do in earlier versions too:
> create subdirectory `stdmath` with one `__init__.py` file with one
> line `import math` and than use `from stdmath import math`.

Ah, thanks, it seems that the idea can be extended to almost all the  
standard library.
Create a directory "stdlib" somewhere on sys.path, with a single file  
__init__.py containing this single line:

__path__.append("path/to/python/standard/lib")

Now, `import stdlib.gzip` will import the standard gzip module, even if  
there is a gzip.py in the current directory or in some other place along  
sys.path.
That is, we have made a package out of the standard library.
Unfortunately it doesn't work for math as-is because math is a builtin  
module (at least on Windows), but this should work for all other "normal"  
Python-level modules.
(It's a hack, and I would never use this on production code, but it may be  
useful sometimes)

-- 
Gabriel Genellina




More information about the Python-list mailing list