Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Aliasing in __init__.py

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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:\practice\calculator> 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:\practice\calculator> 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?

>Solution :

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading