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, 2019 in Python by ana1504.k
• 7,890 points
82 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, 2019 by SDeb
• 13,250 points

Related Questions In Python

0 votes
1 answer
0 votes
1 answer

How to list a column of float values from csv file without importing (Python)

Using the default CSV module Demo: import csv with open(filename, "r") ...READ MORE

answered Sep 16 in Python by Rajiv
• 3,220 points
157 views
+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,870 points
9,939 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,440 points
319 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, 2019 in Python by Neha
• 330 points

edited Jul 8, 2019 by Kalgi 1,465 views
0 votes
0 answers
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,250 points
140 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,250 points
198 views