Packages and modules correspond to the relationship between files and directories. A module can contain multiple modules, whereas a module points to a single file. The program can be structured on a file-by-file basis.
There are many external packages in Python
in addition to the standard packages. This external package is imported and used.
def printmsg():
print('Hello, World')
By using the ʻimport` statement, the above file can be read as a module.
import file_test1
file_test1.printmsg()
When a global variable is defined in a module, the variable in the module will not be rewritten even if a variable with the same name is defined in the import destination. That is, the variables defined in the module are valid for each module.
msg = 'Hello, World'
def printmsg:
print(msg)
The above file defines the global variable msg
.
import file_test2
msg = 'Goodbye, Python'
file_test2.printmsg()
Execution result
Hello, World
The variable msg
is also defined in the import destination, but it is distinguished from the variable msg
in the module.
Files used as modules can also be written as one Python program, so each can be executed individually.
When executing a Python program individually, __main__
is assigned to the variable __name__
, so you can write the test code as follows.
def printmsg:
print('Hello, World')
if __name__ == '__main__':
print('test')
To package the directory, you need to create a file named __init__.py
. In __init__.py
, describe the names of the modules included in the variable __all__
as a list.
For example, if you want to include modules named test3.py
and test4.py
in the same directory as __init__.py
in one package, __init__.py
is written as follows ..
__all__ = ['test3.py', 'test4.py']
If you want to list the elements included in the package, you can use the function dir ()
. Import the package and specify the package name as an argument.
Recommended Posts