Aliasing in __init__.py

Question:

I am using python 3.10.7 and facing wierd issue.Kindly let me know if this is correct way to access things

Case 1:

My file structure is as follows:

calculator
 calcfunctions
  addition.py (def sum(a,b) in this file)
  subtraction.py
 __init__.py
main.py

The code in __init__.py is as follows:

list_languages = ["Rust","Java"]
import calcfunctions.addition

when i try to import module in console, it works perfectly fine as follows:

PS E:practicecalculator> python
Python 3.10.7 (tags/v3.10.7:6cc6b13, Sep  5 2022, 14:08:36) [MSC v.1933 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> import calcfunctions 
>>> calcfunctions.addition.sum(2,3) 
5

Case 2:

if i modify the code in __init__.py as follows

list_languages = ["Rust","Java"]
import calcfunctions.addition as summation

Now i try to import in repl, it gives error as follows:

PS E:practicecalculator> python
Python 3.10.7 (tags/v3.10.7:6cc6b13, Sep  5 2022, 14:08:36) [MSC v.1933 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> import calcfunctions
>>> calcfunctions.list_languages
['Rust', 'Java']
>>> calcfunctions.summation(2,3) 
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'module' object is not callable
>>> summation(2,3)               
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'summation' is not defined
>>> summation.sum(2,3)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'summation' is not defined

What i could be doing wrong here?

Asked By: Arshanvit

||

Answers:

It needs to be accessed in following manner:

>>> calcfunctions.summation.sum(2,3)
Answered By: Arshanvit

If you want the summation in the top level of the calcfunction package to be a reference to the sum method defined in calcfunction.addition, you want your import to be from calcfunction.addition import sum as summation. Since you’re doing it in the package, you can use relative imports too, rather than naming calcfunction expicitly: from .addition import sum as summation.

If you want the main module (that you’re running interactively) to have summation defined, you need to do a from calcfunction import summation call, rather than just importing calcfunction itself.

Answered By: Blckknght
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.