简体   繁体   中英

Python Relative Imports and Packages

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()

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()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM