Nearby lessons

75 of 159

Python - Modules

📌 What You Will Learn
  • Understand what a module is and why modules are used
  • Create a user-defined module and import it with the import statement
  • Use module aliasing, from...import, and member aliasing
  • Reload an imported module with reload() from the importlib module
  • Explore module members using the dir() function
  • Work with special properties like __name__ and __file__

Introduction to Modules

As programs become larger, writing all the code in a single file becomes difficult to manage.

Python solves this problem by allowing us to divide programs into multiple files called Modules.

A module contains related functions, variables, and classes that can be reused in different programs.

Using modules makes programs more organized, reusable, and easier to maintain.

What is a Module?

A Module is a collection of related functions, variables, and classes stored in a single Python file.

Every module is saved with the .py extension.

Instead of writing the same code repeatedly, we can place the code inside a module and use it whenever required.

Definition of Module

A group of functions, variables, and classes saved to a file is called a Module.

Every Python file with the .py extension acts as a module.

Why Do We Use Modules?

Modules provide several advantages while developing Python applications.

They help us organize code, avoid duplication, and make programs easier to understand.

Modules help us:

  • Organize related code into a single file.
  • Reuse the same code in multiple programs.
  • Reduce code duplication.
  • Make programs easier to maintain.
  • Improve readability.
  • Simplify testing and debugging.

Every Python File is a Module

Every Python file (.py) is automatically treated as a module.

For example, if a file is named durgamath.py, Python considers it a module.

Any functions, variables, or classes defined inside that file become members of the module.

Example Module

durgamath.py

Explanation

The file durgamath.py is a Python module.

We can store related mathematical functions inside this file and use them in other Python programs.

Creating a User-Defined Module

A module created by the programmer is called a User-Defined Module.

To create a user-defined module, simply create a Python file and write variables, functions, or classes inside it.

For example, create a file named durgamath.py.

Program - Create a Module (durgamath.py)

🐍Code Cell
1x = 888
2 
3def add(a, b):
4 print("The Sum:", a + b)
5 
6def product(a, b):
7 print("The Product:", a * b)
Output
No output captured.

Understanding the Module

The module contains the following members:

  • One variable: x
  • Function: add()
  • Function: product()

These members can be accessed from another Python program after importing the module.

Using a Module

If we want to use the members of a module in another program, we should import that module.

After importing the module, we can access its variables, functions, and classes.

Syntax

🐍Code Cell
1import modulename
Output
No output captured.

Accessing Module Members

After importing the module, its members are accessed using the module name.

Syntax

🐍Code Cell
1modulename.variable
2 
3modulename.function()
Output
No output captured.

Program - Using the durgamath Module

This example assumes a module named durgamath exists on disk (not available in the in-browser editor).

# test.py

import durgamath

print(durgamath.x)

durgamath.add(10, 20)

durgamath.product(10, 20)
888
The Sum: 30
The Product: 200

Program Explanation

Step 1

import durgamath

Imports the durgamath module.

Step 2

print(durgamath.x)

Accesses the variable x from the module.

Step 3

durgamath.add(10, 20)

Calls the add() function from the module.

Step 4

durgamath.product(10, 20)

Calls the product() function from the module.

Important Note

Whenever we use a module in our program, Python generates a compiled file for that module and stores it permanently on the hard disk.

Module Structure

🐍Code Cell
1durgamath.py
2
3├── Variable x
4├── Function add()
5└── Function product()
Output
No output captured.

Flow of Module Usage

Create Module
      │
      ▼
Import Module
      │
      ▼
Access Variables
      │
      ▼
Call Functions
        

Advantages of Modules

  • Improves code organization.
  • Encourages code reuse.
  • Reduces duplication.
  • Makes maintenance easier.
  • Improves readability.
  • Supports modular programming.
  • Allows multiple programs to share the same code.

Real-World Applications

  • Building reusable utility libraries.
  • Creating large software projects.
  • Organizing application code into separate files.
  • Sharing common functions among multiple programs.
  • Developing reusable APIs and frameworks.

Important Interview Questions

  1. What is a Module in Python?
  2. Why do we use Modules?
  3. Is every Python file a module?
  4. What is a User-Defined Module?
  5. How do you create a module?
  6. How do you import a module?
  7. How do you access variables from a module?
  8. How do you call functions from a module?
  9. What happens when a module is imported?
  10. What are the advantages of using Modules?

Introduction to Module Aliasing

In the previous section, we learned how to create and import user-defined modules.

Python also allows us to import modules in different ways depending on our requirements.

Sometimes a module name is too long or conflicts with another identifier in the program.

In such cases, Python allows us to give another name to the module while importing it. This feature is called Module Aliasing.

What is Module Aliasing?

Sometimes we can provide another name to a module while importing it.

This is called Module Aliasing.

Using an alias makes the module name shorter and easier to use throughout the program.

Syntax

🐍Code Cell
1import module_name as alias_name
Output
No output captured.

Example

This example assumes a module named durgamath exists on disk (not available in the in-browser editor).

import durgamath as m

Explanation

In this example:

  • durgamath is the original module name.
  • m is the alias name.

After importing the module with an alias, all members of the module are accessed using the alias name.

Accessing Members by Using Alias Name

After creating an alias, we can access all module members by using the alias name.

Program - Using Module Alias

This example assumes a module named durgamath exists on disk (not available in the in-browser editor).

import durgamath as m

print(m.x)

m.add(10, 20)

m.product(10, 20)
888
The Sum: 30
The Product: 200

Program Explanation

The module durgamath is imported with the alias m.

The variable x is accessed using m.x.

The functions add() and product() are also called using the alias name.

This makes the code shorter and easier to read.

The from ... import Statement

Sometimes we do not need all the members of a module.

Instead of importing the entire module, Python allows us to import only the required members.

This is done using the from ... import statement.

The main advantage is that imported members can be accessed directly without using the module name.

Syntax

🐍Code Cell
1from module_name import member
Output
No output captured.

Program - Import Selected Members

This example assumes a module named durgamath exists on disk (not available in the in-browser editor).

from durgamath import x, add

print(x)

add(10, 20)

product(10, 20)
888
The Sum: 30

NameError: name 'product' is not defined

Explanation

  • x and add() are imported successfully.
  • product() is not imported.
  • Since product() is unavailable, Python raises a NameError.

Importing All Members

If we want to import every member of a module, we can use the * operator.

This imports all variables, functions, and classes from the module.

After importing, the members can be accessed directly without using the module name.

Syntax

🐍Code Cell
1from module_name import *
Output
No output captured.

Program - Import All Members

This example assumes a module named durgamath exists on disk (not available in the in-browser editor).

from durgamath import *

print(x)

add(10, 20)

product(10, 20)
888
The Sum: 30
The Product: 200

Various Possibilities of import

Python supports several ways to import modules.

The appropriate method depends on the requirements of the program.

Different Import Statements

🐍Code Cell
1import modulename
2 
3import module1, module2, module3
4 
5import module1 as m
6 
7import module1 as m1, module2 as m2, module3
8 
9from module import member
10 
11from module import member1, member2, member3
12 
13from module import member1 as x
14 
15from module import *
Output
No output captured.

Member Aliasing

Just as we can rename a module, we can also rename individual module members while importing them.

This feature is called Member Aliasing.

Program - Member Aliasing

This example assumes a module named durgamath exists on disk (not available in the in-browser editor).

from durgamath import x as y, add as sum

print(y)

sum(10, 20)
888
The Sum: 30

Explanation

The variable x is imported with the alias y.

The function add() is imported with the alias sum.

After importing, only the alias names can be used.

Important Rule

Once an alias name is assigned, we must use only the alias name.

The original name cannot be used in the current program.

Program - Using Original Name After Aliasing

This example assumes a module named durgamath exists on disk (not available in the in-browser editor).

from durgamath import x as y

print(x)
NameError: name 'x' is not defined

Explanation

The variable x was imported with the alias y.

Therefore, the original name x is no longer available in the current program.

Using x raises a NameError.

Comparison of Import Statements

Import Statement Access Method
import durgamath durgamath.add()
import durgamath as m m.add()
from durgamath import add add()
from durgamath import * Direct access to all imported members.

Advantages of Module Aliasing

  • Reduces long module names.
  • Makes code easier to read.
  • Improves code readability.
  • Helps avoid naming conflicts.
  • Provides convenient access to module members.

Advantages of from ... import

  • Imports only the required members.
  • Allows direct access without using the module name.
  • Produces shorter code.
  • Improves readability when only a few members are needed.

Real-World Applications

  • Using short aliases for large library names such as numpy as np.
  • Importing only frequently used functions.
  • Avoiding conflicts between modules with similar names.
  • Writing clean and maintainable Python programs.

Important Interview Questions

  1. What is Module Aliasing?
  2. Why do we use the as keyword?
  3. What is the difference between import module and from module import member?
  4. What does from module import * do?
  5. What is Member Aliasing?
  6. Can the original member name be used after aliasing?
  7. What happens if a non-imported member is accessed?
  8. List different ways to import modules in Python.
  9. When should Module Aliasing be used?
  10. What are the advantages of importing selected members?

Introduction to Reloading Modules

When a module is imported into a Python program, Python loads it only once.

Even if the same module is imported multiple times, Python does not reload it again.

This improves program performance because the module does not need to be loaded repeatedly.

However, this behavior creates a problem when the source code of the module is modified after it has already been imported.

In such situations, Python continues using the old version of the module instead of the updated one.

To use the modified version without restarting the Python interpreter, we must reload the module.

Reloading a Module

By default, a module will be loaded only once, even if we import it multiple times.

If we modify the source code of a module after importing it, those changes are not reflected automatically in the current program.

To load the updated version of the module, we must reload it.

Why Reloading is Required?

Suppose:

  • A module is already imported.
  • Later, the module is modified.
  • We want to use the updated version without restarting the Python interpreter.

In this situation, we should reload the module.

reload() Function

The reload() function is used to reload an already imported module.

Before using reload(), we should import it from the importlib module.

After reloading, Python loads the latest version of the module from the source file.

Syntax

🐍Code Cell
1from importlib import reload
2 
3reload(module_name)
Output
No output captured.

Example

Assume the following module already exists.

Program - durgamath.py

🐍Code Cell
1x = 10
2 
3def add(a, b):
4 print(a + b)
Output
No output captured.

Program - test.py

This example assumes a module named durgamath exists on disk (not available in the in-browser editor).

import durgamath

print(durgamath.x)

from importlib import reload

reload(durgamath)

print(durgamath.x)

Program Explanation

Step 1

import durgamath

The durgamath module is imported into the program.

Step 2

print(durgamath.x)

The value of the variable x stored in the module is displayed.

Step 3

from importlib import reload

The reload() function is imported from the importlib module.

Step 4

reload(durgamath)

The module is reloaded so that Python reads the latest version from the source file.

Step 5

print(durgamath.x)

The updated value of x is displayed after the module has been reloaded.

How reload() Works

  1. Python imports the module for the first time.
  2. The module is stored in memory.
  3. If the module source code changes later, Python continues using the old version.
  4. The reload() function forces Python to read the module file again.
  5. The updated module replaces the old version in memory.

Flow of Module Reloading

Import Module
      │
      ▼
Module Loaded into Memory
      │
      ▼
Modify Source Code
      │
      ▼
Old Version Still Used
      │
      ▼
Call reload(module)
      │
      ▼
Latest Version Loaded
        

Important Point

If a module is modified after it has already been imported, Python does not load the modified version automatically.

We must explicitly call:

reload(module_name)

Only then will Python use the updated version of the module in the current program.

When Should We Use reload()?

  • When developing or testing Python modules.
  • When a module is modified while the interpreter is still running.
  • When we want to use the latest version without restarting Python.
  • During debugging to verify changes immediately.

Advantages of reload()

  • Loads the latest version of a module.
  • Removes the need to restart the Python interpreter.
  • Useful during development and debugging.
  • Allows testing updated module code immediately.

Limitations of reload()

  • Works only with modules that have already been imported.
  • Must be called explicitly.
  • Python does not reload modules automatically after they are modified.

Real-World Applications

  • Developing reusable Python libraries.
  • Testing modules during software development.
  • Interactive Python sessions.
  • Debugging applications without restarting the interpreter.
  • Updating utility modules during development.

Important Interview Questions

  1. What is module reloading in Python?
  2. Why is reload() required?
  3. When should we use reload()?
  4. Which module provides the reload() function according to this tutorial?
  5. Can Python automatically reload a modified module?
  6. What happens if a module is modified after it has already been imported?
  7. What is the syntax of the reload() function?
  8. What are the advantages of using reload()?

Introduction to dir() Function

When working with Python modules, we often need to know what variables, functions, classes, and built-in attributes are available inside a module.

Python provides a built-in function called dir() for this purpose.

The dir() function displays all the members available in a specified module.

This makes it easy to explore a module without reading its source code.

dir() Function

The dir() function is used to display all members of a module.

It returns:

  • Variables
  • Functions
  • Classes
  • Built-in attributes

available in the specified module.

Syntax

🐍Code Cell
1dir(module_name)
Output
No output captured.

Program - Display Members of math Module

🐍Code Cell
1import math
2 
3print(dir(math))
Output
No output captured.

Output

Explanation

The output contains all the available members of the math module.

The exact output may vary depending on the Python version being used, but it always includes the members provided by that module.

Understanding dir()

The dir() function is useful when:

  • We want to know what members are available in a module.
  • We do not remember the exact function names.
  • We want to explore a module.

Example - Exploring math Module

🐍Code Cell
1import math
2 
3members = dir(math)
4 
5print(members)
Output
No output captured.

Explanation

First, the math module is imported.

The dir(math) function returns a list containing every available member of the module.

The returned list is stored in the variable members and then displayed.

Common Members Displayed by dir(math)

Member Purpose
sqrt() Returns the square root of a number.
ceil() Returns the smallest integer greater than or equal to a number.
floor() Returns the largest integer less than or equal to a number.
factorial() Returns the factorial of a number.
sin() Returns the sine of an angle.
cos() Returns the cosine of an angle.
tan() Returns the tangent of an angle.
pi Mathematical constant π.
e Euler's mathematical constant.

Difference Between Importing and Reloading

Import Reload
Loads a module for the first time. Loads the updated version of an already imported module.
Uses the import statement. Uses the reload() function.
Executed once. Executed whenever required.

Advantages of dir()

  • Displays all members of a module.
  • Helps discover available functions.
  • Useful for beginners learning new modules.
  • Reduces the need to memorize function names.
  • Helps during debugging and development.
  • Provides information about built-in attributes.

Real-World Applications

  • Exploring built-in Python modules.
  • Learning third-party libraries.
  • Debugging unfamiliar modules.
  • Finding available functions quickly.
  • Understanding APIs without reading source code.

Important Interview Questions

  1. What is the purpose of the dir() function?
  2. What does the dir() function return?
  3. Can dir() display functions available in a module?
  4. How do you display all members of the math module?
  5. What is the difference between import and reload()?
  6. Why is the dir() function useful?
  7. Does dir() display built-in attributes?
  8. When should you use dir() while programming?

Introduction to Special Properties

Whenever a Python module is executed, the Python interpreter automatically adds several special properties to that module.

These properties are created internally by Python and are mainly used by the interpreter for managing the execution of the program.

Although these properties are generated automatically, they can also be accessed from our Python programs whenever required.

These special properties provide useful information about the currently executing module.

Special Properties Added by Python

For every module, at the time of execution, the Python interpreter automatically adds some special properties for internal use.

These properties can also be accessed in our program.

Some of the important special properties are:

  • __builtins__
  • __cached__
  • __doc__
  • __file__
  • __loader__
  • __name__
  • __package__
  • __spec__

Understanding the Special Properties

Each special property stores different information related to the current module.

Some properties describe the module itself, while others help Python manage module loading and execution.

These properties are created automatically, so programmers normally do not need to define them manually.

Program to Access Special Properties

🐍Code Cell
1print(__builtins__)
2 
3print(__cached__)
4 
5print(__doc__)
6 
7print(__file__)
8 
9print(__loader__)
10 
11print(__name__)
12 
13print(__package__)
14 
15print(__spec__)
Output
No output captured.

Output

Program Explanation

The program simply prints every important special property automatically added by Python.

Each statement displays information maintained internally by the Python interpreter.

The displayed values may vary depending on the Python version and execution environment.

__builtins__ Property

__builtins__ refers to the built-in Python module that contains all built-in functions, exceptions, and objects.

Examples include:

  • print()
  • len()
  • input()
  • type()
  • range()

This property allows Python to access all built-in functionality.

__cached__ Property

__cached__ stores information about the compiled version of the module.

If no compiled version exists, its value may be None.

Python internally uses this property while working with compiled module files.

__doc__ Property

__doc__ stores the documentation string (Docstring) of the module.

If no documentation string is available, Python returns None.

__file__ Property

__file__ stores the name or path of the currently executing Python file.

In the example, it displays:

test.py

__loader__ Property

__loader__ contains information about the object responsible for loading the module.

Python uses this loader internally while importing modules.

__name__ Property

__name__ stores information about how the current file is executed.

If the file is executed directly, its value becomes __main__.

If the file is imported as a module, its value becomes the module name.

This important property will be discussed in detail in the next section.

__package__ Property

__package__ stores the package name to which the module belongs.

If the file does not belong to any package, its value is generally None.

__spec__ Property

__spec__ stores information related to the module specification.

This property is mainly used internally by Python's import system.

Summary of Special Properties

Special Property Description
__builtins__ Reference to Python built-in module.
__cached__ Information about compiled module.
__doc__ Module documentation string.
__file__ Name or path of the current Python file.
__loader__ Object responsible for loading the module.
__name__ Execution information of the module.
__package__ Name of the package containing the module.
__spec__ Module specification information.

Advantages of Special Properties

  • Provide internal information about modules.
  • Help Python manage program execution.
  • Useful for debugging.
  • Allow developers to inspect module details.
  • Help understand how modules are loaded.

Real-World Applications

  • Debugging Python programs.
  • Building Python frameworks.
  • Developing reusable libraries.
  • Understanding module loading.
  • Creating developer tools and utilities.

Important Interview Questions

  1. What are Special Properties in Python?
  2. Who creates Special Properties?
  3. When are these properties added to a module?
  4. What is the purpose of __builtins__?
  5. What does __file__ store?
  6. What is stored in __doc__?
  7. What is the use of __loader__?
  8. What information is stored in __package__?
  9. What is __spec__?
  10. Which special property stores execution information?

Introduction to __name__

__name__ is one of the most important special variables automatically added by the Python interpreter.

Every Python module contains this variable.

The value stored in __name__ depends on how the Python file is executed.

Because of this behavior, __name__ is widely used while creating reusable Python modules.

What is __name__?

The special variable __name__ identifies whether a Python file is executed directly or imported as a module.

Python automatically assigns an appropriate value during program execution.

Value of __name__

Execution Method Value of __name__
Executed directly __main__
Imported as a module Name of the module

Why is __name__ Useful?

Sometimes a Python file contains reusable functions as well as testing code.

We want the testing code to execute only when the file is run directly.

If another program imports that file as a module, only the reusable functions should become available.

The __name__ variable helps us achieve this behavior.

Syntax

🐍Code Cell
1if __name__ == "__main__":
2 # Executed only when this file runs directly
Output
No output captured.

Program - module1.py

🐍Code Cell
1print("Module-1 Execution")
2 
3print("__name__ value:", __name__)
4 
5def wish():
6 print("Good Morning")
7 
8if __name__ == "__main__":
9 print("Executed Directly")
10 wish()
Output
No output captured.

Program - test.py

🐍Code Cell
1import module1
2 
3print("Inside test.py")
4 
5module1.wish()
Output
No output captured.

Output - Executing module1.py Directly

Output - Executing test.py

Explanation - Executing module1.py

When module1.py is executed directly, Python assigns:

__name__ = "__main__"

The condition:

if __name__ == "__main__":

becomes true.

Therefore, the statements inside the if block are executed.

Explanation - Importing module1

When module1 is imported into another program, Python assigns:

__name__ = "module1"

The condition:

if __name__ == "__main__":

becomes false.

Hence, the statements inside the if block are not executed.

Only the module members become available for use.

Execution Flow

Python File Starts
        │
        ▼
Is File Executed Directly?
        │
   ┌────┴────┐
   │         │
  Yes        No
   │         │
   ▼         ▼
__name__   __name__
= "__main__" = Module Name
   │         │
   ▼         ▼
if Block    Skip if Block
Executed
        

Advantages of Using __name__

  • Separates testing code from reusable code.
  • Makes modules reusable.
  • Prevents unnecessary execution when importing modules.
  • Improves code organization.
  • Widely used in professional Python projects.

Practical Uses

  • Testing Python modules.
  • Creating reusable libraries.
  • Writing standalone scripts.
  • Developing large Python applications.
  • Separating demonstration code from actual module code.

Comparison

Executed Directly Imported as Module
__name__ = "__main__" __name__ = module_name
if block executes. if block is skipped.
Used for standalone execution. Used for reusable modules.

Important Interview Questions

  1. What is the purpose of the __name__ variable?
  2. Who creates the __name__ variable?
  3. What is the value of __name__ when a file is executed directly?
  4. What is the value of __name__ when a file is imported?
  5. Why is if __name__ == "__main__": used?
  6. Can reusable modules contain testing code?
  7. What happens when a module is imported?
  8. Where is the __name__ variable commonly used?
  9. Why is __name__ important in large projects?
  10. What are the advantages of using __name__?
📝 Key Takeaways
  • A module is a .py file containing related functions, variables, and classes
  • import loads a module only once; from...import brings specific members into scope
  • An alias provides a shorter name for a module or a member
  • reload() from importlib loads the updated version of an already imported module
  • dir() displays all members available in a specified module
  • Special properties like __name__ and __file__ provide internal module information

🧠 Test Your Knowledge

45 Questions
Progress: 0 / 45