I have a directory structure like this:
<code>.
├── main.py
└── silly_test
├── __init__.py
└── foo.py
</code>
<code>.
├── main.py
└── silly_test
├── __init__.py
└── foo.py
</code>
.
├── main.py
└── silly_test
├── __init__.py
└── foo.py
<code># main.py
import silly_test.foo
import silly_test.__init__ # This line is unusual - I wouldn't typically do this.
</code>
<code># main.py
import silly_test.foo
import silly_test.__init__ # This line is unusual - I wouldn't typically do this.
</code>
# main.py
import silly_test.foo
import silly_test.__init__ # This line is unusual - I wouldn't typically do this.
<code># silly_test/__init__.py
print(f"Init name: {__name__}")
</code>
<code># silly_test/__init__.py
print(f"Init name: {__name__}")
</code>
# silly_test/__init__.py
print(f"Init name: {__name__}")
<code># silly_test/foo.py
print("Hi from foo")
</code>
<code># silly_test/foo.py
print("Hi from foo")
</code>
# silly_test/foo.py
print("Hi from foo")
This prints:
<code>Init name: silly_test
Hi from foo
Init name: silly_test.__init__ <-- WHAT?!
</code>
<code>Init name: silly_test
Hi from foo
Init name: silly_test.__init__ <-- WHAT?!
</code>
Init name: silly_test
Hi from foo
Init name: silly_test.__init__ <-- WHAT?!
I am surprised by the last line of the output for multiple reasons.
- Generally top level code in a file is only executed once. To my surprise, this is executing twice.
- The
__name__
property of the file is different.
What is going on here? 🙂