BFTM BFTM - 1 year ago 61
Python Question

Python modules with identical names (i.e., reusing standard module names in packages)

Suppose I have a package that contains modules:


and the modules need to refer to functions contained in one another. It seems like I run into problems with my
module since there is a standard module that goes by the same name.

For instance, in the case that my
module requires both my
and the standard python
modules, I run into trouble since the interpreter will look inside the package and find my
modules before it comes across the standard

Is there any way around this? Is this a no-no situation and should modules names not be reused?

Any solutions and opinions on package philosophy would be useful here.

Answer Source

Reusing names of standard functions/classes/modules/packages is never a good idea. Try to avoid it as much as possible. However there are clean workarounds to your situation.

The behaviour you see, importing your SWS.time instead of the stdlib time, is due to the semantics of import in ancient python versions (2.x). To fix it add:

from __future__ import absolute_import

at the very top of the file. This will change the semantics of import to that of python3.x, which are much more sensible. In that case the statement:

import time

Will only refer to a top-level module. So the interpreter will not consider your SWS.time module when executing that import inside the package, but it will only use the standard library one.

If a module inside your package needs to import SWS.time you have the choice of:

  • Using an explicit relative import:

    from . import time
  • Using an absolute import:

    import SWS.time as time

So, your would be something like:

from __future__ import absolute_import

import time

from . import time as SWS_time
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download