Reputation: 2719
Is it possible to change a Python module to a package without changing the import
statements in other files?
Example: other files in the project use import x
, and x
is x.py
, but I want to move it to something like ./x/x.py
without changing the import statements in other files to from x import x
.
Even if I use __all__ = ["x"]
in __init__.py
, it needs from x import x
to work.
Is there a way or do I have to update the import
statements in the other files?
Upvotes: 2
Views: 142
Reputation: 9863
The cleanest solution to this problem would be having a proper namespace package so your imports won't be implicit ones.
Now, that said, another alternative to achieve what you're asking for would be modifying PYTHONPATH so the imports will be resolved properly, to do this there are basically few ways:
sys.path
or os.environ['PYTHONPATH']
in your python codeBut I strongly discourage these ones, only reason you want to modify PYTHONPATH could happen if you want to import non-installable pypi packages or pointing out to an external package (in this case you got full control over your package) which is not installable (setup.py) and resolved by the current PYTHONPATH.
Although my best advice, follow https://www.python.org/dev/peps/pep-0008/#imports
Upvotes: 1
Reputation: 78556
Might be one of the rare reasons to use wildcard import in your x/__init__.py
:
from .x import *
Upvotes: 1
Reputation: 9427
One way to do this is move x.py
- but then create a new x.py
(or in this case, __init__.py
that resides in the x
directory) that imports everything it used to expose.
For example, if x.py
contained def example
you could import this using from x import example
. This would basically be a proxy to the real definition.
Let me know if I haven't explained this clearly enough.
Upvotes: 1