Corporate Training
Request Demo
Click me
Menu
Let's Talk
Request Demo

Tutorials

Modules and Packages

Modules and Packages

Modules:
 
1. Introduction to Modules:
  • Modules are separate Python files containing code.
  • Used for organizing related functions, classes, and variables.
2. Creating Modules:
  • Creating your own module by creating a .py file.
  • Defining functions, classes, and variables within the module.
3. Importing Modules:
  • Using the import statement to access module functionality.
  • Importing the entire module or specific items.
4. Using Module Functions and Variables:
  • Accessing functions and variables from the imported module.
  • Using dot notation: module_name.function_name().
5. Aliases and Renaming:
  • Using aliases (as) to provide shorter names for modules.
  • Renaming imported items for clarity.
6. Importing Specific Items:
  • Importing only the necessary items from a module.
  • Reducing memory usage and improving code readability.

Packages:

1. Introduction to Packages:

  • Packages are collections of related modules.
  • Used for organizing larger projects with multiple modules.
2. Creating Packages:
  • Creating a package by organizing modules in a directory.
  • Adding an __init__.py file to indicate the package.
3. Subpackages:
  • Creating subpackages within packages.
  • Organizing related functionality in a hierarchical structure.
4. Importing from Packages:
  • Importing modules from packages using dot notation.
  • Specifying the full path: package_name.module_name.
5. Relative Imports:
  • Using relative imports to reference modules within the same package.
  • Avoiding potential naming conflicts.
6. Package Initialization:
  • Using the __init__.py file to control package initialization.
  • Defining variables or code that should run when the package is imported.

Using External Libraries:

1. Installing External Libraries:
  • Using package managers like pip to install third-party libraries.
  • Managing dependencies and versions.
2. Importing External Libraries:
  • Importing functions and classes from external libraries.
  • Using the library's documentation to understand usage.
3. Exploring Common Libraries:
  • Exploring popular libraries for various purposes (e.g., NumPy, pandas, matplotlib, requests).

Example:

Let's illustrate modules and packages with an example:

Suppose you have a project structure like this:


 

my_project/

├── main.py
├── my_module.py

└── my_package/
├── __init__.py
├── module_a.py
└── module_b.py