python - absolute import for module in the same directory

前端 未结 2 1796
旧巷少年郎
旧巷少年郎 2021-01-04 03:55

I have this package:

mypackage/
    __init__.py
    a.py
    b.py

And I want to import things from module a to module b, does it make sense

2条回答
  •  无人及你
    2021-01-04 04:37

    You can safely use number 2 because there shouldn't be any collisions - you'll be always importing a module from the same package as the current one. Please note, that if your module has the same name as one of the standard library modules, it will be imported instead of the standard one. From the documentation:

    When a module named spam is imported, the interpreter first searches for a built-in module with that name. If not found, it then searches for a file named spam.py in a list of directories given by the variable sys.path. sys.path is initialized from these locations:

    • the directory containing the input script (or the current directory).
    • PYTHONPATH (a list of directory names, with the same syntax as the
    • shell variable PATH).
    • the installation-dependent default.

    After initialization, Python programs can modify sys.path. The directory containing the script being run is placed at the beginning of the search path, ahead of the standard library path. This means that scripts in that directory will be loaded instead of modules of the same name in the library directory. This is an error unless the replacement is intended. See section Standard Modules for more information.

    The option from mypackage.a import * can be used for consistency reasons all over the project. In some modules you will have to do absolute imports anyway. Thus you won't have to think whether the module is in the same package or not and simply use a uniform style in the entire project. Additionally this approach is more reliable and predictable.

    Python style guidelines don't recommend using relative imports:

    Relative imports for intra-package imports are highly discouraged. Always use the absolute package path for all imports. Even now that PEP 328 is fully implemented in Python 2.5, its style of explicit relative imports is actively discouraged; absolute imports are more portable and usually more readable.

    Since python 2.5 a new syntax for intra-package relative imports has been introduced. Now you can . to refer to the current module and .. referring to the module being 1 level above.

    from . import echo
    from .. import formats
    from ..filters import equalizer
    

提交回复
热议问题