Quote:I have read dozens of tutorials on how to make a package. I have read dozens of articles about import and __init__.py and PYTHONPATH and setup.py and every topic that looks like it may point toward and answer. I fear I am missing some vital piece Python understanding and this is so trivial that nobody talks about it.Can talk a little about package an some links.
Files:
my_pack\ |-- __init__.py |-- a.py |-- b.py
__init__.py
:import my_pack.a import my_pack.b
a.py
:def my_sum(x, y): return x + y
b.py
:import my_pack.a def average(x, y): return my_pack.a.my_sum(x, y) / 2Now do import work this way
import my_pack
or from my_pack import a, b
.Use my_sum as
sum
word is used by Python.Test:
E:\div_code λ ptpython >>> import my_pack >>> my_pack.a.my_sum(4, 5) 9 >>> my_pack.b.average(4, 5) 4.5 >>> # Using from import >>> from my_pack import a, b >>> a.my_sum(9, 99) 108 >>> b.average(9, 99) 54.0I like to keep imports as simple as possible for users of package eg not use
.
in import,but can use .
internally in a package to eg lift sub-modules.Think of when using one most used and popular packages in Python Requests.
The main import is simple
import requests
,the call function/methods like this
requests.get()
, requests.post()
...ect.So how dos Python find this package?
Python find bye looking in
sys.path
folders,so all module/package which is just files at botton is found by Python trough sys.path
.Some links here lift sub-modules up.
my_pack example
Here more about infrastructure around this,like if want to share at PyPi or make a wheel.
Packaging/Modules--Wheel--pip--setup.py--Freeze