Importing across a python package

0 votes
pkg/
    __init__.py
    foo.py
    bar.py
    baz.py
 

I have a bunch of module imports that are the same across foo.py, bar.py, and baz.py.

Is there a way I can do the imports in __init__.py? What would I have to write in foo.py?
Jun 3 in Python by ana1504.k
• 7,870 points
14 views

1 answer to this question.

0 votes
Placing the imports in __init__.py would be a bad idea; __init__.py is used as the contents of your module object, so it is a public interface. Also, __init_.py is imported initially when your package is imported, while you don't actually need the imports to occur until your submodules need them.

The best approach is to put common code in an internal detail module, marked with a single initial underscore (meaning "private"), e.g. _imports.py, then in your other files write from ._imports import *.
answered Jun 3 by SDeb
• 13,160 points

Related Questions In Python

0 votes
1 answer
+3 votes
7 answers

How can I rename a file in Python?

yes, you can use "os.rename" for that. ...READ MORE

answered Mar 31, 2018 in Python by DareDev
• 6,810 points
111 views
+2 votes
2 answers

How can I create a new file in Python?

You can try the below code which ...READ MORE

answered Mar 31, 2018 in Python by anto.trigg4
• 3,420 points
78 views
+2 votes
2 answers

How to make a laplacian pyramid using OpenCV python?

down voteacceptTheeThe problem is that you're iterating ...READ MORE

answered Apr 3, 2018 in Python by charlie_brown
• 7,710 points
1,173 views
+1 vote
2 answers

how can i count the items in a list?

Syntax :            list. count(value) Code: colors = ['red', 'green', ...READ MORE

answered Jul 6 in Python by Neha
• 330 points

edited Jul 8 by Kalgi 168 views
0 votes
1 answer

Is there a string 'contains' in python?

In this case, you can use the ...READ MORE

answered Sep 25, 2018 in Python by SDeb
• 13,160 points
56 views
0 votes
1 answer

How to Reverse a list in Python

You can use the reversed function in ...READ MORE

answered Sep 28, 2018 in Python by SDeb
• 13,160 points
64 views