Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

This may be well written somewhere on the internet (even on SO) but I could not find it.


Suppose I have a Python project structure like the following

mymodule
|—-__init__.py
|—-a.py
|—-b.py
|—-c.py
main.py

Now, I want to import in main.py everything from mymodule, meaning I want to be able to do the following:

import mymodule

mymodule.a.something()
mymodule.b.something_else()

I do not want to do the following:

import mymodule.a
import mymodule.b
import mymodule.c

How can I achieve this? In JS ES6, you would create a file mymodule.js for example, in which you would import everything that you want to export, and then export it. Is there something similar possible in Python?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
285 views
Welcome To Ask or Share your Answers For Others

1 Answer

As previously mentioned, when importing a module you are essentially importing its __init__.py file. The correct way to handle this is to import whatever you need inside mymodule/__init__.py, and then all those imports will be available to whoever imports mymodule.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share

548k questions

547k answers

4 comments

86.3k users

...