TransWikia.com

Some questions about __init__.py

Stack Overflow Asked by theabc50111 on December 22, 2021

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

# testmain.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:

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

So I import mod1.py in testmodule1__init__.py :

# testmodule1__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:testmodule1__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

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.

Answered by aamir on December 22, 2021

  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

Answered by Jesse Vogt on December 22, 2021

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP