3

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:

enter image description here

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? enter image description here

enter image description here

Section 2) With init.py file

Now, suppose that I create a init. file in the helpers directory:

enter image description here

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)?

enter image description here

Best regards,

8Simon8
  • 141
  • 9
  • 1
    2) you get the output from two namespaces, so which one are you asking about? `main.py` only has `helpers` in its namespace while the package has everything. You may want to read about [`import` statement](https://docs.python.org/3/reference/simple_stmts.html#import) and the [import system](https://docs.python.org/3/reference/import.html) – Matiiss Jan 04 '22 at 02:09
  • In the first question, I am looking for namespace in main.py and for the second question, the namespace in init.py. To clarify, I want to know why sometimes "import helpers.math_func", adds "helpers" to the namespace and sometimes both "helpers" and "math_-func". – 8Simon8 Jan 04 '22 at 02:14

0 Answers0