본문 바로가기

카테고리 없음

__init__.py ... what for?

https://www.youtube.com/watch?v=cONc0NcKE7s&ab_channel=EricOMeehan 

resources/object_one.py  where object_one.py defines class One

                /object_two.py

 

import resources

 

a = resources.object_one.One()   // error

----------------------------------

 

from resources.object_one import One

 

a = One() // works

 

-----------------------------------

resources/__init__.py

                /object_one.py  where object_one.py defines class One

                /object_two.py

 

where in __init__py, from resoures.object_one import One

 

import resources

a = resources.object_one.One() // works

 

--------------------------------------

resources/__init__.py

                /object_one.py  where object_one.py defines class One

                /object_two.py

 

where in __init__py, from resoures.object_one import One

 

from resources import One // without explicitly writing "object_one.py" file

a = One() // works

 

--------------------------------------------------------

 

This might looks redundant but imagine the case when I need to import object_one.py and object_one.py to multiples of different modules. Then I need "from resources.object_one import One" for every single module. If, however, I have __init__.py, then I can import them with only "import resources".

 

Why does it work?

As soon as the library "resources" is imported (by "import resources"), it looks up "__init__.py" file in the folder "resources" and run it.