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

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 foo.py would be something like:

from __future__ import absolute_import

import time

from . import time as SWS_time

Leave a Comment