1

I'm seeing many examples online that seem to indicate mere inclusion of a blank __init__.py file in a folder turns from a namespace package into a package. I'd like to figure out what this actually means. Consider the following example:

root
└───a
        b.py
        __init__.py

The python files contain no code, as this is only for demonstration purposes. Whether I include the blank __init__.py file or not, there is no difference in the following:

Python 3.9.5 (default, May 18 2021, 14:42:02) [MSC v.1916 64 bit (AMD64)] :: Anaconda, Inc. on win32
>>> import a
>>> a.b
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: module 'a' has no attribute 'b'
>>> b
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'b' is not defined
>>> from a import b
>>> b
<module 'a.b' from 'C:\\Users\\user_id\\desktop\\temp\\packages_question\\a\\b.py'>

I understand that including a from . import b statement inside a_init_.py will change things, but that's not what this question is about. I'm more interested in the role of a blank __init__.py. How does the blank __init__.py change the behavior of import in python?

user32882
  • 5,094
  • 5
  • 43
  • 82
  • Does this answer your question? [What is \_\_init\_\_.py for?](https://stackoverflow.com/questions/448271/what-is-init-py-for) – crissal Jan 15 '22 at 12:29
  • Kind of, although the question is not specifically about *blank* __init__.py files. There is some hint that these are not required anymore in newer python versions but I still would like to know how they change pythons behavior when they are included as blank files... – user32882 Jan 15 '22 at 12:32
  • Try reading [this subparagraph](https://docs.python.org/3/reference/import.html#submodules), it seems to me it's very related to your problem – crissal Jan 15 '22 at 12:34
  • That's still not about blank __init__.py files! – user32882 Jan 15 '22 at 12:37
  • This might clarify things: https://stackoverflow.com/a/62992832 – sinoroc Jan 15 '22 at 15:50

0 Answers0