Python module (Python learning memo ④)

About Python modules

point

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'

About module import

point

>>> from sample_module import func1, func2
>>> func1('kawauso')
'kawauso'
>>> func2('kawauso')
'kawauso'
>>> from sample_module import *
>>> func1('kawauso')
'kawauso'

Run the module as a script

point

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

Module search path

point

About compiled Python files

point

Standard module

point

dir () function

>>> import module
>>> dir(module) 
['__builtins__', '__cached__', '__doc__', '__file__', '__loader__', '__name__', '__package__', '__spec__', 'func1', 'func2']

>>> hoge = 'hoge' 
>>> dir()
['__annotations__', '__builtins__', 
'__doc__', '__loader__', '__name__', '__package__', '__spec__', 'hoge', 
'module']
>>>
>>> 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']

package

point

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()

Import * from package

point

__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 *

Cross-reference within the package

point

from . import echo #Same hierarchy
from .. import formats #One level up
from ..filters import equalizer #In the filters submodule one level up

Packages that span multiple directories

point

Recommended Posts

Python module (Python learning memo ④)
Python class (Python learning memo ⑦)
Python exception handling (Python learning memo ⑥)
Python memo
python memo
Python memo
python memo
python learning
Python memo
Python memo
Python memo
Python control syntax, functions (Python learning memo ②)
Input / output with Python (Python learning memo ⑤)
Interval scheduling learning memo ~ by python ~
"Scraping & machine learning with Python" Learning memo
[Python] Memo dictionary
LPIC201 learning memo
[Python] Learning Note 1
python beginner memo (9.2-10)
Python learning notes
Python module import
Django Learning Memo
python beginner memo (9.1)
python learning output
Python learning site
★ Memo ★ Python Iroha
Python learning day 4
[Python] EDA memo
Python Deep Learning
Python 3 operator memo
Python learning (supplement)
Deep learning × Python
[Memo] Machine learning
[My memo] python
Python3 metaclass memo
Python collections module
[Python] Basemap memo
Python beginner memo (2)
python learning notes
[Python] Numpy memo
Python & Machine Learning Study Memo: Environment Preparation
Python numbers, strings, list types (Python learning memo ①)
[Learning memo] Basics of class by python
Python data structure and operation (Python learning memo ③)
Python standard library: second half (Python learning memo ⑨)
Python & Machine Learning Study Memo ③: Neural Network
Python & Machine Learning Study Memo ④: Machine Learning by Backpropagation
Python & Machine Learning Study Memo ⑥: Number Recognition
Python standard library: First half (Python learning memo ⑧)
My python environment memo
Learning Python with ChemTHEATER 03
python openCV installation (memo)
"Object-oriented" learning with python
Reinforcement learning 1 Python installation
Learning Python with ChemTHEATER 05-1
Python: Deep Learning Practices
Python ~ Grammar speed learning ~
Visualization memo by Python
Python: Unsupervised Learning: Basics
Create a Python module
Python & Machine Learning Study Memo ⑤: Classification of irises