Why python finds module instead of package if they have the same name?

后端 未结 2 1250
无人及你
无人及你 2020-12-16 21:15

Here is my directory structure:

/home/dmugtasimov/tmp/name-res
    root
        tests
            __init__.py
            test_1.py
        __init__.py
              


        
2条回答
  •  死守一世寂寞
    2020-12-16 21:39

    Do not modify sys.path it leads to the issues when the same module is available under different names. See Traps for the Unwary.

    Use absolute or explicit relative imports instead in the code and run your scripts from the project directory. Run the tests using the full name:

    $ python -munittest root.tests.test_1
    

    Some packages do modify sys.path internally e.g., see how twisted uses _preamble.py or pypy's autopath.py. You could decide whether their downsides (introduction of obscure import problems) are worth the convience (more ways to run your scripts are allowed). Avoid modifying sys.path in a code that is used as a library i.e., limit it to test modules and your command-line scripts.

提交回复
热议问题