1

enviroment: python3.8

directory:

test\
    module1\
           __init__.py
           mod1.py
    module2\
           mod2.py
    main.py

1. I can import a directory without __init__.py , why?

I want to check how exactly init.py work, so I import the module1 and module2 in main.py

# test\main.py
from module1 import mod1
from module2 import mod2

In my expectation, line2 should occur error, because I didn't create __init__.py in module2

But both of them can be imported.

Now, I'm confused about how exactly __init__.py work


2. I can't import those package which is imported in __init__.py

I try to import mod1.py in main.py in this way:

# test\main.py
import module1
module.mod1.mod1_print() # mod1_print() is a function which is defined in mod1.py

So I import mod1.py in test\module1\__init__.py :

# test\module1\__init__.py
import mod1

But when I execute main.py I got this error:

D:\>"C:/Program Files/Python38/python.exe" d:/test/main.py
Traceback (most recent call last):
  File "d:/test/main.py", line 2, in <module>
    import module1
  File "d:\test\module1\__init__.py", line 1, in <module>
    import mod1
ModuleNotFoundError: No module named 'mod1'

My question is:

If I want to import mod_print() in this form: module.mod1.mod1_print() , what should I do?

2 Answers 2

2

Python 3.3+ has Implicit Namespace Packages that allow it to create packages without an __init__.py file.

Allowing implicit namespace packages means that the requirement to provide an init.py file can be dropped completely, and affected portions can be installed into a common directory or split across multiple directories as distributions see fit.

1
  1. see https://stackoverflow.com/a/37140173/9822 - python >= 3.3 dropped the requirement for __init__.py.
  2. You could try something like this in module1/__init__.py:
import module1.mod1

Not the answer you're looking for? Browse other questions tagged or ask your own question.