Python Relative Imports and Packages

喜夏-厌秋 提交于 2019-12-08 07:29:18

问题


I'm trying to create a package and I have a tree structure that looks like this:

dionesus/
  setup.py
  dionesus/
    __init__.py
    dionesus.py

Dionesus.py has a class called Dionesus. The init.py is empty.

How do I import the class Dionesus without having to specify the top level folder?

I have to do:

import dionesus
d = dionesus.dionesus.Dionesus()

I would like import statements to look like:

import dionesus
d = dionesus.Dionesus()

回答1:


First, you can still use an absolute import, just using the from … import form:

from dionesus import dionesus
d = dionesus.Dionesus()

This will obviously be problematic if you ever need to import both dionesus and dionesus.dionesus in the same module, but that's pretty much implicit in the desire to give them both the same non-disambiguated name…

Alternatively, if you're in a parent or sibling or other relative of dionesus.dionesus, you can use a relative import. Depending on where you are, it'll be different (that's what relative means, after all); you may be importing from ., .dionesus, .., etc. But wherever it is, it's the same from … import form as above, just with a relative name instead of an absolute one. (In fact, relative imports always use the from form.)

from . import dionesus
d = dionesus.Dionesus()


来源:https://stackoverflow.com/questions/27239643/python-relative-imports-and-packages

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