Introduction to a Module
- Any file containing logically organized Python code can be used as a module.
- A module generally contains any of the defined functions, classes and variables. A module can also include executable code.
- Any Python source file can be used as a module by using an import statement in some other Python source file.
Importing a module
Two ways of importing a module:
- First way:
- Specify a module along with ‘import’ key word.
- A dot operator can be used to access attributes and methods of imported module.
#mymath module def square(x): 'Returns square of a number' return x**2 #main.py import mymath n=[1,2,3,4,5] s=[mymath.square(num) for num in n] print(s) #Output: [1, 4, 9, 16, 25]
- Second way:
- Allows the user to directly access the attributes and methods of a module, without using a dot operator.
- The attributes and methods of the imported module types are imported directly into the local namespace. And, they are available directly, without qualification by module name.
- All the available attributes and methods, of a module can be imported using *.
#mymath module def square(x): 'Returns square of a number' return x**2 #main.py from mymath import square n=[1,2,3,4,5] s=[square(num) for num in n] print(s) #Output: [1, 4, 9, 16, 25]
Packages
- A package is a collection of modules present in a folder.
- The name of the package is the name of the folder itself.
- A package generally contains an empty file named
__init__.py
in the same folder, which is required to treat the folder as a package. - Python packages can contain other packages within them to an arbitrary depth — provided each sub-package also has its own ‘__init__.py’ file.