6. (Module)
Python (script)
Python (module) import import (main)
Python .py __name__ fibo.py
#
def fib(n):
""" n """
a, b = 0, 1
while a < n:
print(a, end=' ')
a, b = b, a+b
print()
def fib2(n):
""" n """
result = []
a, b = 0, 1
while a < n:
result.append(a)
a, b = b, a+b
return result
Python import
>>> import fibo
fibo namespace Python (Scope) (Namespace) fibo
>>> fibo.fib(1000)
0 1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987
>>> fibo.fib2(100)
[0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]
>>> fibo.__name__
'fibo'
>>> fib = fibo.fib
>>> fib(500)
0 1 1 2 3 5 8 13 21 34 55 89 144 233 377
6.1.
import [1]
(namespace)modname.itemname
import import class import
import import import
>>> from fibo import fib, fib2
>>> fib(500)
0 1 1 2 3 5 8 13 21 34 55 89 144 233 377
import fibo
import
>>> from fibo import *
>>> fib(500)
0 1 1 2 3 5 8 13 21 34 55 89 144 233 377
import (_) Python
import *
as as import
>>> import fibo as fib
>>> fib.fib(500)
0 1 1 2 3 5 8 13 21 34 55 89 144 233 377
import import fibo fib
>>> from fibo import fib as fibonacci
>>> fibonacci(500)
0 1 1 2 3 5 8 13 21 34 55 89 144 233 377
session import importlib.reload()import importlib; importlib.reload(modulename)
6.1.1.
Python
python fibo.py <arguments>
import __name__ "__main__"
if __name__ == "__main__":
import sys
fib(int(sys.argv[1]))
import (parse)
$ python fibo.py 50
0 1 1 2 3 5 8 13 21 34
import
>>> import fibo
>>>
6.1.2.
Import spam sys.builtin_module_names sys.path spam.py sys.path
PYTHONPATHshellPATHsite-packagessite
(symlink)
Python sys.path
6.1.3. Python
Python __pycache__ module.version.pyc version Python CPython 3.3 spam.py __pycache__/spam.cpython-33.pyc Python
Python
Python (cache)
.pyc.pycompileall.pyc
6.2.
Python Python winreg Windows sys Python sys.ps1 sys.ps2
>>> import sys
>>> sys.ps1
'>>> '
>>> sys.ps2
'... '
>>> sys.ps1 = 'C> '
C> print('Yuck!')
Yuck!
C>
sys.path list PYTHONPATH PYTHONPATH list
>>> import sys
>>> sys.path.append('/ufs/guido/lib/python')
6.3. dir()
dir() list
>>> import fibo, sys
>>> dir(fibo)
['__name__', 'fib', 'fib2']
>>> dir(sys)
['__breakpointhook__', '__displayhook__', '__doc__', '__excepthook__',
'__interactivehook__', '__loader__', '__name__', '__package__', '__spec__',
'__stderr__', '__stdin__', '__stdout__', '__unraisablehook__',
'_clear_type_cache', '_current_frames', '_debugmallocstats', '_framework',
'_getframe', '_git', '_home', '_xoptions', 'abiflags', 'addaudithook',
'api_version', 'argv', 'audit', 'base_exec_prefix', 'base_prefix',
'breakpointhook', 'builtin_module_names', 'byteorder', 'call_tracing',
'callstats', 'copyright', 'displayhook', 'dont_write_bytecode', 'exc_info',
'excepthook', 'exec_prefix', 'executable', 'exit', 'flags', 'float_info',
'float_repr_style', 'get_asyncgen_hooks', 'get_coroutine_origin_tracking_depth',
'getallocatedblocks', 'getdefaultencoding', 'getdlopenflags',
'getfilesystemencodeerrors', 'getfilesystemencoding', 'getprofile',
'getrecursionlimit', 'getrefcount', 'getsizeof', 'getswitchinterval',
'gettrace', 'hash_info', 'hexversion', 'implementation', 'int_info',
'intern', 'is_finalizing', 'last_traceback', 'last_type', 'last_value',
'maxsize', 'maxunicode', 'meta_path', 'modules', 'path', 'path_hooks',
'path_importer_cache', 'platform', 'prefix', 'ps1', 'ps2', 'pycache_prefix',
'set_asyncgen_hooks', 'set_coroutine_origin_tracking_depth', 'setdlopenflags',
'setprofile', 'setrecursionlimit', 'setswitchinterval', 'settrace', 'stderr',
'stdin', 'stdout', 'thread_info', 'unraisablehook', 'version', 'version_info',
'warnoptions']
>>> a = [1, 2, 3, 4, 5]
>>> import fibo
>>> fib = fibo.fib
>>> dir()
['__builtins__', '__name__', 'a', 'fib', 'fibo', 'sys']
>>> import builtins
>>> dir(builtins)
['ArithmeticError', 'AssertionError', 'AttributeError', 'BaseException',
'BlockingIOError', 'BrokenPipeError', 'BufferError', 'BytesWarning',
'ChildProcessError', 'ConnectionAbortedError', 'ConnectionError',
'ConnectionRefusedError', 'ConnectionResetError', 'DeprecationWarning',
'EOFError', 'Ellipsis', 'EnvironmentError', 'Exception', 'False',
'FileExistsError', 'FileNotFoundError', 'FloatingPointError',
'FutureWarning', 'GeneratorExit', 'IOError', 'ImportError',
'ImportWarning', 'IndentationError', 'IndexError', 'InterruptedError',
'IsADirectoryError', 'KeyError', 'KeyboardInterrupt', 'LookupError',
'MemoryError', 'NameError', 'None', 'NotADirectoryError', 'NotImplemented',
'NotImplementedError', 'OSError', 'OverflowError',
'PendingDeprecationWarning', 'PermissionError', 'ProcessLookupError',
'ReferenceError', 'ResourceWarning', 'RuntimeError', 'RuntimeWarning',
'StopIteration', 'SyntaxError', 'SyntaxWarning', 'SystemError',
'SystemExit', 'TabError', 'TimeoutError', 'True', 'TypeError',
'UnboundLocalError', 'UnicodeDecodeError', 'UnicodeEncodeError',
'UnicodeError', 'UnicodeTranslateError', 'UnicodeWarning', 'UserWarning',
'ValueError', 'Warning', 'ZeroDivisionError', '_', '__build_class__',
'__debug__', '__doc__', '__import__', '__name__', '__package__', 'abs',
'all', 'any', 'ascii', 'bin', 'bool', 'bytearray', 'bytes', 'callable',
'chr', 'classmethod', 'compile', 'complex', 'copyright', 'credits',
'delattr', 'dict', 'dir', 'divmod', 'enumerate', 'eval', 'exec', 'exit',
'filter', 'float', 'format', 'frozenset', 'getattr', 'globals', 'hasattr',
'hash', 'help', 'hex', 'id', 'input', 'int', 'isinstance', 'issubclass',
'iter', 'len', 'license', 'list', 'locals', 'map', 'max', 'memoryview',
'min', 'next', 'object', 'oct', 'open', 'ord', 'pow', 'print', 'property',
'quit', 'range', 'repr', 'reversed', 'round', 'set', 'setattr', 'slice',
'sorted', 'staticmethod', 'str', 'sum', 'super', 'tuple', 'type', 'vars',
'zip']
6.4. (Package)
Python A.B A B NumPy Pillow
.wav.aiff.au
sound/ Top-level package
__init__.py Initialize the sound package
formats/ Subpackage for file format conversions
__init__.py
wavread.py
wavwrite.py
aiffread.py
aiffwrite.py
auread.py
auwrite.py
...
effects/ Subpackage for sound effects
__init__.py
echo.py
surround.py
reverse.py
...
filters/ Subpackage for filters
__init__.py
equalizer.py
vocoder.py
karaoke.py
...
Import Python sys.path
__init__.py Pyhon namespace package string__init__.py __all__
import
import sound.effects.echo
sound.effects.echo
sound.effects.echo.echofilter(input, output, delay=0.7, atten=4)
import
from sound.effects import echo
echo
echo.echofilter(input, output, delay=0.7, atten=4)
import
from sound.effects.echo import echofilter
echo echofilter()
echofilter(input, output, delay=0.7, atten=4)
from package import item item class import item item ImportError
import item.subitem.subsubitem class
6.4.1. import *
from sound.effects import * import import import
import __init__.py __all__ list from package import * import list import * listsound/effects/__init__.py
__all__ = ["echo", "surround", "reverse"]
from sound.effects import * import sound.effects
(locally defined) sound/effects/__init__.py reverse from sound.effects import * echo surround reverse reverse
__all__ = [
"echo", # 'echo.py'
"surround", # 'surround.py'
"reverse", # !!! 'reverse' !!!
]
def reverse(msg: str): # <-- 'from sound.effects import *'
return msg[::-1] # 'reverse.py'
__all__ from sound.effects import * sound.effects import sound.effects import __init__.py import __init__.py import
import sound.effects.echo
import sound.effects.surround
from sound.effects import *
from...import echo surround import sound.effects __all__
import * (production)
from package import specific_submodule import
6.4.2.
sound (absolute) import sound.filters.vocoder sound.effects echo from sound.effects import echo
from module import name import (relative) import import import surround
from . import echo
from .. import formats
from ..filters import equalizer
import Python
[1]