Reputation: 169
I have a few questions about namespaces and init.py in modular programming in python. I will divide my questions into two sections: without init and with init.
Section 1) Without init.py
Suppose that I have a main.py file and a helpers directory (there are utils.py and math_func.py) in my current working directory as below:
In the utils.py I have:
def read_file(file_path):
with open(file_path) as f:
return f.read()
def add(a, b):
return a + b
if __name__ == '__main__':
print(add(3, 4) == 7)
print(dir())
In the math_func I have:
def add(a, b):
return a + b
def subtract(a, b):
return a - b
def tokeniz(sentence):
return sentence.split()
1- In the main.py, if I write "import helpers.math_func" and then look at the namespace, I will find "helpers" there, while if I write "from helpers import math_func", I will find "math_func" in the namespace?
Section 2) With init.py file
Now, suppose that I create a init. file in the helpers directory:
In the init.py, I have:
import helpers.math_func as mf
import helpers.utils
print(dir())
Now, I change the main.py as below:
import helpers
print(dir())
print(helpers.utils.add(3, 4))
print(helpers.math_func.add(3, 4))
print(helpers.mf.add(3, 4))
2- As we know, when we import a package and there is an init file, that file is read and executed. Could you please explain to me why "math_func" and "utils" are found in the namespace when there is a init file, while we don't have them when there isn't an init file (as in question 1)?
Best regards,
Upvotes: 3
Views: 69