How to import python class file from same directory?

女生的网名这么多〃 提交于 2020-05-09 18:41:25

问题


I have a directory in my Python 3.3 project called /models.

from my main.py I simply do a

from models import *

in my __init__.py:

__all__ = ["Engine","EngineModule","Finding","Mapping","Rule","RuleSet"]
from models.engine import Engine,EngineModule
from models.finding import Finding
from models.mapping import Mapping
from models.rule import Rule
from models.ruleset import RuleSet

This works great from my application.

I have a model that depends on another model, such that in my engine.py I need to import finding.py in engine.py. When I do: from finding import Finding

I get the error No Such Module exists.

How can I import class B from file A in the same module/directory?

Edit 1: Apparently I can do: from .finding import Finding and this works. And the answer below reflects this as well so I guess this is reasonably correct. I've fixed up my file naming and moved my tests to a different directory and I am running smoothly now. Thanks!


回答1:


Since you are using Python 3, which disallows these relative imports (it can lead to confusion between modules of the same name in different packages).

Use either:

from models import finding

or

import models.finding

or, probably best:

from . import finding  # The . means "from the same directory as this module"


来源:https://stackoverflow.com/questions/21139364/how-to-import-python-class-file-from-same-directory

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