Python - python package organization

We know some small techniques that we can use to build small programs. but we eventually will progress to build a more complicated program, and we need to organize the program.
The way to organize the program is package. let's see an example, which is called mathproj, and it has the following structure.

├─mathproj
│  │  __init__.py
│  │
│  └─comp
│      │  c1.py
│      │  __init__.py
│      │
│      └─numeric
│              n1.py
│              n2.py
│              n3.py
│              __init__.py
Let's see each file in sequence.

/mathproj/__init__.py

print("Hello from mathproj init")
__all__ = ['comp']
version = 1.03
/mathproj/comp/__init__.py
__all__ = ['c1']
print("Hello from mathproj.comp init")
/math/comp/c1.py
x = 1.00
/math/numeric/__init.__.py
print("Hello from numeric init")
/math/numeric/n1.py
from mathproj import version
from mathproj.comp import c1
from mathproj.comp.numeric.n2 import h

def g():
    print("version is", version)
    print(h())
/math/numeric/n2.py
def h():
    return "Called function h in module n2"

A alternative way of import modules.

We see the /math/numeric/n1.py, it is a bit too much hard coded, and n1 is already deep down the path, in OS, we have . to refer to the current directory and the .. to refers to the parent directory . Can we use that?
Let's see how  it is done, the file n3.py 
'''
file: n3.py
description: this is a transformed of the n2.py which shows  you can do differently with the modules.
'''
from ... import version
from .. import c1
from . n2 import h
# from .n2 import h # this is the same as the line above

def g():
    print("version is", version)
    print(h())

the __all__ attributes

__all__ attribute list the modules explicitly under a package, why we need this, we need this because the OS not consistently designed, some do not treat case sensitive. the __all__ give you a way to control the what modules to be exported in the pacakge.
however, do not use __all__ as a mean of information hiding, if you don't want to expose a module, you'd better rename it to have __ before its name.

你可能感兴趣的:(python)