python packaging for relative imports

前端 未结 3 1007
小蘑菇
小蘑菇 2020-11-29 19:18

First off all: I\'m sorry, I know there has been lots of question about relative imports, but I just didn\'t find a solution. If possible I would like to use the following d

3条回答
  •  执念已碎
    2020-11-29 19:44

    ValueError: Attempted relative import in non-package

    Means you attempt to use relative import in the module which is not package. Its problem with the file which has this from ... import statement, and not the file which you are trying to import.

    So if you are doing relative imports in your tests, for example, you should make your tests to be part of your package. This means

    1. Adding __init__.py to test/
    2. Running them from some outside script, like nosetests

    If you run something as python myClass/test/demo.py, relative imports will not work too since you are running demo module not as package. Relative imports require that the module which uses them is being imported itself either as package module, from myClass.test.demo import blabla, or with relative import.

提交回复
热议问题