Scenario:
dirA/
__init__.py
file1.py
file2.py
dirB/
__init__.py
file11.py
file22.py
dirC/
__init__.py
file111.py
file222.py
I read on https://docs.python.org/2/tutorial/modules.html#tut-standardmodules that Contrarily, when using syntax like import item.subitem.subsubitem, each item except for the last must be a package; the last item can be a module or a package but can’t be a class or function or variable defined in the previous item.
Now because of above reading i have a numbers on doubt:
When i do write import dirA.dirB so whether this statement import modules inside dirC package too or only the modules inside dirB ?
what is the use of import dirA.dirB, because when i am using this statement, am still unable to use the modules inside the dirB sub package ?
and i know that to use the modules inside dirB i have to use the import dirA.dirB.file11
2 Answers 2
When you do import dirA.dirB , you only import the package dirB , which means you basically import the __init__.py under dirB.py , if that __init__.py was defining some functions or classes etc, you would be able to use them after import dirA.dirB .
Example -
My directory structure -
shared/ a.py pkg/ init.py b.py
Now in pkg/__init__.py , I have -
x = 1
import pkg.b
My pkg/b.py is -
a = 1
Now in a.py , I can do -
import pkg
print(pkg.b.a)
print(pkg.x)
And this would work, because __init__.py imported pkg.b and hence it is accessible using pkg.b.a .
6 Comments
pkg , but you would not be able to do anything with it.import pkg.b directly in a.py . But for pkg to be recognized as a package, you would need __init__.py in pkg folder.When you use from dirA import dirB, dirB will be a module which contains anything (variables, functions, etc) defined in or imported by dirB/__init__.py.
This is often used to make the "public" components of dirB easily accessible. For example, you might have:
from .file11 import Foo
from .file22 import Bar
So that users of your library could simply call:
from dirA.dirB import Foo, Bar
Instead of having to remember which file defines Foo and Bar.