Reputation: 115
I am trying to make a package from a code that I made. Let's say that 'mypackage' folder contains the package.py
and the __init__.py
files. When I want to import this package I have to write
import mypackage.package
so I can access the functions inside the package.py file. I wonder if it is possible to write only
import mypackage
or
import package
to access the functions. Somehow numpy works this way, because one can import numpy via
import numpy
and numpy is actually the name of the folder: ~/anaconda3/lib/python3.8/site-packages/numpy
How can I make a package which is similar to numpy in this sense (in terms of importing)?
Upvotes: 1
Views: 75
Reputation: 833
You can use the __init__.py
for this:
# mypackage/__init__.py:
from mypackage.package import *
This way, when importing mypackage
you will implicitly import package
. For example, assume that there is a function do_something
defined in mypackage/package.py
. Then, for a file test.py
defined in the project root you can do the following:
# test.py, defined in project root
import mypackage
mypackage.do_something()
(Please note that wildcard imports should be avoided, i.e., it is better to only import the functions you need, for instance from mypackage.package import do_something
).
Upvotes: 1