point
* .py__name__sample_module.py
def func1(n):
return n
def func2(n):
return n
In the Python interpreter
>>> import sample_module
>>> sample_module.func1('kawauso')
'kawauso'
point
>>> from sample_module import func1, func2
>>> func1('kawauso')
'kawauso'
>>> func2('kawauso')
'kawauso'
* to capture all names defined by the module except those that start with _>>> from sample_module import *
>>> func1('kawauso')
'kawauso'
point
python sample_module.py argument__name__ becomes __main__sample_module.py
def func1(n):
return n
def func2(n):
return n
#This code does not run when imported as a module
if __name__ == "__main__":
import sys
func1(sys.argv[1])
$ python sample_module.py kawauso
kawauso
point
point
__pycache__ directory for faster module loadingmodule.version.pycpoint
winreg module is only available on Windows systemssys is typical of these modules (this is built into all Python interpreters)sys.ps1, sys.ps2 are defined only when the interpreter is in interactive mode.sys.path is a list of strings that specify the interpreter's module search pathsys.path is either PYTHONPATH or the built-in default pathdir () is used to check the name defined by the module (return value is a list of strings)>>> import module
>>> dir(module)
['__builtins__', '__cached__', '__doc__', '__file__', '__loader__', '__name__', '__package__', '__spec__', 'func1', 'func2']
dir () returns a list of names defined at the current level
>>> hoge = 'hoge'
>>> dir()
['__annotations__', '__builtins__',
'__doc__', '__loader__', '__name__', '__package__', '__spec__', 'hoge',
'module']
>>>
dir () does not list built-in function and variable namesbuiltins>>> 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', 'ModuleNotFoundError', 'NameError', 'None', 'NotADirectoryError', 'NotImplemented', 'NotImplementedError', 'OSError', 'OverflowError', 'PendingDeprecationWarning', 'PermissionError', 'ProcessLookupError',
'RecursionError', 'ReferenceError',
'ResourceWarning', 'RuntimeError', 'RuntimeWarning', 'StopAsyncIteration', 'StopIteration', 'SyntaxError', 'SyntaxWarning', 'SystemError', 'SystemExit', 'TabError', 'TimeoutError', 'True', 'TypeError', 'UnboundLocalError', 'UnicodeDecodeError', 'UnicodeEncodeError', 'UnicodeError', 'UnicodeTranslateError', 'UnicodeWarning', 'UserWarning', 'ValueError', 'Warning', 'WindowsError', 'ZeroDivisionError', '_', '__build_class__', '__debug__', '__doc__', '__import__', '__loader__', '__name__', '__package__', '__spec__', 'abs', 'all', 'any', 'ascii', 'bin', 'bool', 'breakpoint', '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']
point
__init__.py file to treat a directory as containing packages__init__.py can be just an empty file, but you can also run the package initialization code and set the __all__ variable.Package configuration example
A/ ->Top level package
__init__.py ->Package initialization
A1/ ->Subpackage 1
__init__.py
hoge1.py
hoge2.py
hoge3.py
A2/ ->Subpackage 2
__init__.py
hoge1.py
hoge2.py
hoge3.py
Load package
import A.A1.hoge1
#References to this must be done with full name
A.A1.hoge1.func1()
There is also another loading method
Load package 2
from A.A1 import hoge1
hoge1.func1()
There is also a way to directly import the desired function or variable.
from A.A1.hoge1 import func1
func1()
point
from A.A1 import *, if the code of __init__.py of the package defines the __all__ variable, import the package defined there.__all__ is not defined, only import ʻA.A1` and import all names defined in the package body__init__.py are also imported__init__.py
__all__ = ["module1", "module2", "module3"]
module4 = func4() #module4 is also imported
#echo and surround modules are imported
import sound.effects.echo
import sound.effects.surround
from sound.effects import *
point
__main__from . import echo #Same hierarchy
from .. import formats #One level up
from ..filters import equalizer #In the filters submodule one level up
point
__path__, it affects the search for modules and subpackages included in the package.Recommended Posts