46

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?

4
  • 1
    What version of python are you using?
    – Wooble
    Commented Jan 15, 2014 at 14:00
  • I am using Python 3.3
    – Yablargo
    Commented Jan 15, 2014 at 14:01
  • 4
    Python 3 doesn't allow implicit relative imports.
    – Wooble
    Commented Jan 15, 2014 at 14:02
  • 1
    @Yablargo Can you move your Edit 1 section and post as self-answer (from .finding import Finding)?
    – kenorb
    Commented Jun 12, 2018 at 11:15

2 Answers 2

62

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"
3
  • 9
    I think that last one should be from . import finding (otherwise, SyntaxError is raised -- at least for me on python 3.5). Commented Mar 10, 2016 at 16:19
  • I suppose from . import finding is better because it doesn't hardcode the directory name, also any possible name class with another module is averted this way
    – anwar
    Commented Nov 18, 2016 at 8:40
  • from .models import finding also should work (at least for Python 3.5) Commented Dec 1, 2020 at 16:19
3

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
  • 3
    Doesn't work in Python 3.7
    – Wassadamo
    Commented Oct 22, 2021 at 9:15

Not the answer you're looking for? Browse other questions tagged or ask your own question.