Suppose I have a package that contains modules:
SWS/
__init.py__
foo.py
bar.py
time.py
and the modules need to refer to functions contained in one another. It seems like I run into problems with my time.py
module since there is a standard module that goes by the same name.
For instance, in the case that my foo.py
module requires both my SWS.time
and the standard python time
modules, I run into trouble since the interpreter will look inside the package and find my time.py
modules before it comes across the standard time
module.
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.
A package is a collection of python modules under a common namespace. In practice one is created by placing multiple python modules in a directory with a special __init__.py module (file). A module is a single file of python code that is meant to be imported.
This is not possible with the pip. All of the packages on PyPI have unique names. Packages often require and depend on each other, and assume the name will not change. Even if you manage to put the code on Python path, when importing a module, python searches the paths in sys.
A module is a file containing Python code in run time for a user-specific code. A package also modifies the user interpreted code in such a way that it gets easily functioned in the run time. A python “module” consists of a unit namespace, with the locally extracted variables.
Modules in Python can be of two types: Built-in Modules. User-defined Modules.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With