Force importing module from current directory

后端 未结 3 1299
情歌与酒
情歌与酒 2020-12-25 12:59

I have package p that has modules a and b. a relies on b:

b.py contents:



        
相关标签:
3条回答
  • 2020-12-25 13:12

    Because there is an __init__.py file in /p. This file tells Python: "All modules in this folder are in the package p".

    As long as the __init__.py file exists, you can import b as p.b, no matter where you are.

    So the correct import in b.py would be: import p.a

    0 讨论(0)
  • 2020-12-25 13:15

    After rereading the Python import documentation, the correct answer to my original problem is:

    To ensure that b imports a from its own package its just enough to write the following in the b:

    import a
    

    Here is the quote from the docs:

    The submodules often need to refer to each other. For example, the surround module might use the echo module. In fact, such references are so common that the import statement first looks in the containing package before looking in the standard module search path.

    Note: As J.F. Sebastian suggest in the comment below, use of implicit imports is not advised, and they are, in fact, gone in Python 3.

    0 讨论(0)
  • 2020-12-25 13:25

    Relative imports only work within packages.

    If you import b from where you are, there is no notion of a package, and thus there is no way for a relative import.

    If you import p.b, it is module b within package c.

    It is not the directory structure which matters, but the packages structure.

    0 讨论(0)
提交回复
热议问题