resolving module name conflicts.

Eric Snow ericsnowcurrently at gmail.com
Fri Nov 11 16:34:07 EST 2011


On Fri, Nov 11, 2011 at 1:27 PM, Gelonida N <gelonida at gmail.com> wrote:
>
>
> Hi,
>
> I got some code.
> - This code contains a package named tests
> - there are at least 100 references in different python files
>        importing from above mentioned tests package.
> - the code also imports pytz at one place
>
> I get following warning message:
>
> /usr/lib/python2.6/dist-packages/pytz/__init__.py:32: UserWarning:
> Module tests was already imported from
> /home/user/myproject/tests/__init__.pyc, but
> /usr/lib/python2.6/dist-packages is being added to sys.path
>  from pkg_resources import resource_stream
>
>
> Is there any way to tell pytz to import it's own tests package and tell
> the rest of the code to import the other?

This sounds like a problem caused by using relative imports.

Each import statement is made relative to some top-level module.  The
import mechanism looks for it in the directories in sys.path (first
match wins).  The interpreter adds the empty string to the beginning
of sys.path, by default.  The empty string represents the current
working directory.  An import referencing a module found there is
called a relative import.

Solution:

If possible, make sure each of your import statements is absolute (the
top-level module is in one of the [legit] sys.path directories).  Then
do one of the following:

 * sys.path.remove('');
 * call your script from a directory without any python modules in it;
 * call os.chdir(...) in your script to change CWD before making any imports.

This also means you shouldn't "test" your modules by just running them
as scripts.  Instead, write a separate test script that imports each
of your modules absolutely (and maybe actually test them too <wink>).

As of 2.5, Python's from...import syntax supports explicit relative
imports, with absolute imports as the default (sort of).  In 2.5 and
2.6 the feature is optional, so you must add "from __future__ import
absolute_import" to enable it.  See PEP 328[1].

The relative import syntax means that you don't have to hard-code the
name of the packages in your imports, which helps with brevity and
portability.

The problem is that the empty string is still added to the from of
sys.path.  I'm going to have to find out more about that one.

Hope that helps.

-eric

[1] http://www.python.org/dev/peps/pep-0328/


>
> Python version is 2.6.5
>
>
> Thanks in advance for any suggestion.
>
>
>
>
>
>
>
>
>
> --
> http://mail.python.org/mailman/listinfo/python-list
>



More information about the Python-list mailing list