0

Here is what my directory tree looks like:

one/
    config.py
    two/ 
        __init__.py
        A.py
        B.py

When I import functions or classes from A and B inside the __init__.py, it has to be like this:

from .A import func
from .B import cls

However, importing names from config.py can go straight like this:

from config import something

From what I know, since the . indicates the "current directory", why doesn't from A import func also work? On the other hand, config.py sits on the parent directory of __init__.py, how is from config import something supposed to work? Shouldn't that be from ..config import something instead? I'm a little confused.

James Wong
  • 1,107
  • 3
  • 15
  • 26

1 Answers1

0

For the first part of your question (why .A and not A): if you omit ".", the interpreter would look up your system path to find the module. For the second part: this post may help Import Script from a Parent Directory

JNo
  • 89
  • 12
  • I feel this only solved the first. As for the second, why would importing modules from parent directory by not prepending `..` work? – James Wong Jul 10 '19 at 00:09
  • It depends on how you run your code. If your main.py is located in "one", first you may need to insert the directory of "one" to python path (absolute import). By doing so, if you call "from config import something" from "A", since config is already located inside your python path, then you don't need to use relative import. Pls let me know more how you about execute your program so I can be more specific – JNo Jul 10 '19 at 07:41