简体   繁体   中英

How to change a Python 3 module to a package without changing the imports?

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?

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.

可能是在x/__init__.py使用通配符导入的罕见原因之一:

from .x import *

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:

  1. Change PYTHONPATH by hardcoding sys.path or os.environ['PYTHONPATH'] in your python code
  2. Change PYTHONPATH system-wide
  3. Use .pth files on your system-wide python distribution
  4. Use .pth files on your virtualenv

But 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM