Modules In Python

Modules in Python:

  • Apart from the code written in Python interactive console and other less frequent use cases, Python source code is stored in .py files.
  • A file containing the python source code - a collection of classes, functions and literals defines a Python module. The name of the file excluding the .py extension becomes the name of the Python module.
  • A .py file, which is empty, can still be loaded as a module. However such module will not define any name.
  • Python Modules can come from only a single directory or from many sources like multiple directories, a subset of files from a directory, a zip file containing files or from a network location. The first system is called regular packages and the second system is called namespace packages. Python has both the mechanisms available for backward compatibility.
  • For the Python environment, a module is a type. Python loads both packages and modules using the type module.
  • Once a module is loaded using import, the name of the module is available as an instance of type module. This instance is used to access the functions, classes, literals or all put together the names or the namespace contained in the module using the . operator.

Modules in Python

Example:

import socket

import threading

import multiprocessing

 

# Print the type of names

print(type(socket));

print(type(threading));

print(type(threading.Thread));

print(type(multiprocessing));

 

Output:

<class 'module'>

<class 'module'>

<class 'type'>

<class 'module'>

 


Copyright 2023 © pythontic.com