1 year ago

#389076

test-img

Sushi

how to import packages properly in an __init__.py files?

I am having issues creating a basic library. This is my first time attempting this so a complete noob here. I am running a simple example case as shown below.

packagetest
     |-> _init_.py
     |-> func
         |-> _init_.py
         |-> sin.py
         |-> cos.py

And, a main file package_test.py

This library and the main file exists in the same directory.

Inside the fucn __inti__.py, I have import numpy as np. I do not import numpy in sin.py and cos.py.

When I access the functions within the sin.py and cos.py modules (which uses numpy), I write from packagetest.func.sin import foo. Imports without an error; however, when I use foo, why do I get an error saying 'np' isn't defined. From reading the Modules documentation and other previous posts, my understanding is that __init__.py is implicty run when I import any module in the directory. And, it does that! I added a print statement in func's __init__ file. When I import, say, sin.py using the statement aforementioned, the print statement gets printed! so, the numpy is being imported --I think. How come the foo within the sin/cos modules don't "see" it? Isn't the purpose of the __init__ to run a common code that can be used/seen by all the module in the same directory? I'm clearly missing a dot here to connect my current understanding of __init__.py files.

Any help is appreciated! Thank you!

python

python-import

0 Answers

Your Answer

Accepted video resources