Python Packages?

北战南征 提交于 2019-12-03 03:49:34

Generally you would have a directory, the name of which is your package name, somewhere on your PYTHONPATH. For example:

eulerproject/
    euler/
        __init__.py
        euler1.py
        ...
        tests/
            ...
    setup.py

Then, you can either install this systemwide, or make sure to set PYTHONPATH=/path/to/eulerproject/:$PYTHONPATH when invoking your script.

An absolute import like this will then work:

from euler import euler1

Edit:

According to the Python docs, "modules intended for use as the main module of a Python application should always use absolute imports." (Cite)

So a test harness like nose, mentioned by the other answer, works because it imports packages rather than running them from the command line.

If you want to do things by hand, your runnable script needs to be outside the package hierarchy, like this:

eulerproject/
    runtests.py
    euler/
        __init__.py
        euler1.py
        ...
        tests/
            __init__.py
           testeulern.py

Now, runtests.py can do from euler.tests.testeulern import TestCase and testeulern.py can do from .. import euler1

Virgil Dupras

I had the same problem. I now use nose to run my tests, and relative imports are correctly handled.

Yeah, this whole relative import thing is confusing.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!