How to do relative imports in Python?

前端 未结 15 2816
情深已故
情深已故 2020-11-21 04:47

Imagine this directory structure:

app/
   __init__.py
   sub1/
      __init__.py
      mod1.py
   sub2/
      __init__.py
      mod2.py

I\'

15条回答
  •  天涯浪人
    2020-11-21 05:40

    Everyone seems to want to tell you what you should be doing rather than just answering the question.

    The problem is that you're running the module as '__main__' by passing the mod1.py as an argument to the interpreter.

    From PEP 328:

    Relative imports use a module's __name__ attribute to determine that module's position in the package hierarchy. If the module's name does not contain any package information (e.g. it is set to '__main__') then relative imports are resolved as if the module were a top level module, regardless of where the module is actually located on the file system.

    In Python 2.6, they're adding the ability to reference modules relative to the main module. PEP 366 describes the change.

    Update: According to Nick Coghlan, the recommended alternative is to run the module inside the package using the -m switch.

提交回复
热议问题