[Go to site: main page, start]

0% found this document useful (0 votes)
6 views19 pages

Understanding Python Modules and Importing

A module in Python is a file containing Python code that can include functions, classes, and variables, allowing for code reusability and organization. Modules can be created by saving a .py file and can be imported into other Python programs using various import methods. Python also has built-in, third-party, and user-defined modules, and the module search path can be modified to include custom directories.

Uploaded by

garimar629
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
6 views19 pages

Understanding Python Modules and Importing

A module in Python is a file containing Python code that can include functions, classes, and variables, allowing for code reusability and organization. Modules can be created by saving a .py file and can be imported into other Python programs using various import methods. Python also has built-in, third-party, and user-defined modules, and the module search path can be modified to include custom directories.

Uploaded by

garimar629
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

What is a module in Python?

A module is simply a file containing Python code — functions, classes, variables, and runnable
statements — that you can reuse in other Python programs. Modules help in organizing Python code
into manageable, reusable, and logically structured components.

Example:

# [Link]

def add(a, b):

return a + b

def multiply(a, b):

return a * b

PI = 3.14159 #This is to illustrate that modules can store data too

 A module can hold functions (add, multiply) and constants (PI, E, etc.).

 It shows you can group related items (math operations and math constants) together.

Now any other Python file can use add, multiply, and PI by importing calculator.

2. Need for Modules

Modules provide several key advantages:

 Code Reusability: Once a module is created, you can reuse its code in other programs by
simply importing it, reducing the need to write the same code repeatedly.

 Code Organization: Large programs are easier to manage and maintain when they are split
into smaller, logically organized modules.

 Namespace Management: By dividing code into modules, you minimize the risk of name
conflicts, as each module creates its own namespace.

 Collaboration: Modules make it easier for multiple developers to work on different parts of a
project without causing issues in other sections.

Creating a module
A module is any .py file. Example above is [Link]. Save it in the same
folder as your script and import it.

import calculator
print([Link](2, 3)) # 5
print([Link]) # 3.1415

Importing modules (basic forms)


 import module — brings module object; access with [Link].
 from module import name — imports a specific function/variable into current
namespace.
 import module as alias — alias for convenience.
 from module import * — imports all public names (not recommended).

Once you’ve created a module, you can use it in any other Python program using the import
statement.

Basic Import: To import a module, use the import keyword followed by the module name. After
importing, you can access functions, variables, or classes defined in the module using dot notation.

import math_tools

result = math_tools.multiply(10, 5)

print(result) # Output: 50

Importing Specific Functions or Variables: You can also import specific functions or variables from a
module using the from keyword.

from math_tools import divide

result = divide(10, 2)

print(result) # Output: 5.0

Renaming Modules: You can use the as keyword to give a module or a function an alias.

import math_tools as mt

result = [Link](3, 4)

print(result) # Output: 12

Importing All Items from a Module: You can import all functions, variables, or classes from a module
using the * operator.

from math_tools import *

result = multiply(6, 7)

print(result) # Output: 42

5. Types of Modules
 Built-in Modules: Python comes with several pre-installed modules like math, os, sys, etc.
You can use these modules without installing anything.

Example1: Using the built-in math module:

import math

print([Link](16)) # Output: 4.0

example2:

import datetime

print([Link]())

# Go to the datetime module → find the date class → and run its today() method.”

 Third-party Modules: These are modules that are not built into Python but can be installed
via package managers like pip. For example, numpy is a popular third-party module for
numerical computing.

 User-defined Modules: These are modules that you create for your own applications or
projects, like the math_tools.py example above.

Topic: Path Searching of a Module in Python

Q1. What is Path Searching of a Module?

When you import a module in Python, the interpreter needs to find the file that contains the
module’s code.

The process of locating that file (where the module is stored) is called
Path Searching of a Module.

So, Python looks for the module in a specific order of folders (directories) until it finds it.

Example:

import math

When this line runs, Python has to find where the math module is stored before it can use it.
Q2. How does Python search for a module?

Python searches for a module in the following order:

Step Location Python Checks Explanation


Current Working Directory The folder where your Python program (.py file) is
1
(CWD) running.
PYTHONPATH Any additional directories listed in the
2
(Environment Variable) PYTHONPATH system variable.
Built-in modules like math, os, datetime, etc., stored
3 Standard Library Directories
inside Python’s installation folder.
This is where third-party packages (like numpy,
4 Site-packages Directory
pandas) installed via pip are stored.
Installation-dependent Any other default locations set during Python
5
Directories installation.

If Python doesn’t find the module in any of these locations, it raises an error:

ModuleNotFoundError: No module named 'xyz'

Q3. How can we check the module search path in Python?

You can check where Python looks for modules using the sys module.

import sys

print([Link])

Output Example:

['',

'C:\\Users\\DrRaman\\Desktop',

'C:\\Python311\\Lib',

'C:\\Python311\\Lib\\site-packages']

This output shows a list of directories Python searches when you import a module.

Explanation:

 Each location in this list is a folder path.


 Python searches these folders in order.
 As soon as it finds the module file (like [Link] or numpy), it stops searching.
Q4. Why is Path Searching important?

Reasons:

1. Helps Python locate the correct module to import.


2. Avoids conflicts between modules with the same name.
3. Useful for debugging import errors.
4. Helps developers add their own module paths using [Link]().

Q5. How to add a new path manually?

If your module is stored in a custom folder, you can add that path using:

import sys

[Link]('C:\\Users\\DrRaman\\MyModules')

Now Python will also look inside this folder while importing.

Example:

Suppose you have a file named [Link] inside C:\MyProjects.


You can do:

import sys

[Link]("C:\\MyProjects")

import mycode

Now, Python can successfully import your file.

Q6. Common Errors

Error Cause Solution


Python couldn’t find the Check spelling or install the module
ModuleNotFoundError
module in any path. using pip install modulename.
Problem while importing Check correct syntax: from module
ImportError
specific function/class. import function.
Possible Questions:

1. What is [Link]?

o Answer: [Link] is a list of directories that Python searches when importing a


module. It includes the current directory, directories specified in the PYTHONPATH
environment variable, the standard library, and site-packages.

2. What happens if Python cannot find a module?

o Answer: If Python cannot find a module in the directories listed in [Link], it raises a
ModuleNotFoundError.

3. Can we modify the [Link]?

o Answer: Yes, you can modify [Link] dynamically within a script by appending or
inserting new paths. However, this should be done cautiously.

MODULE RELOADING

🔹 Q1. What is Module Reloading?

When a module is imported, Python loads it only once per session (to save time).
If you change the module file after importing it, Python won’t reflect those changes automatically.

To load the updated version of that module again without restarting Python,
you must reload it manually.

🔹 Q2. How to Reload a Module?

Python provides the importlib module to reload modules.

import importlib

import mymodule

[Link](mymodule)

✅ Explanation:

 mymodule is your custom module.

 The reload() function loads it again, applying any changes made in the module file.

🔹 Q3. Why is Reloading Needed?

 When you edit or update a module during development and want to test changes without
restarting the interpreter.

 Useful during debugging and testing stages.


🔹 Q4. Important Notes

 Works only on modules that were already imported once.

 Built-in modules (like math, os) rarely need reloading.

 Reloading doesn’t clear old data automatically; it just updates the module’s code.

🔹 Q5. Example

File: [Link]

def say_hello():

print("Hello, world!")

Main program:

import greet

greet.say_hello() # Output: Hello, world!

# Now you modify [Link] to:

# def say_hello():

# print("Hello, Python!")

import importlib

[Link](greet)

greet.say_hello() # Output: Hello, Python!

🧠 Q6. Possible Exam Questions

Short Questions

1. What is module reloading in Python?

2. Which module is used for reloading another module?

3. Why do we need to reload a module?

4. Write the syntax for reloading a module.

5. Can we reload built-in modules?

Long / Descriptive Questions


1. Explain the concept of module reloading with an example.

2. Write a Python program to demonstrate module reloading using [Link]().

3. What are the advantages and limitations of reloading a module?

📝 Sample Exam Answer (Long Form):

Answer:
Module reloading means loading an already imported module again to reflect recent changes in its
code.
Python loads modules only once per session. If we modify a module after importing, the new
changes are not visible unless we reload it.

To reload a module, Python provides the importlib module.

Example:

import importlib

import mymodule

[Link](mymodule)

This reloads the module mymodule without restarting the interpreter.


It is mainly used during testing and debugging phases.

2. STANDARD MODULES

🔹 Q1. What are Standard Modules?

Standard Modules are the predefined (built-in) modules that come bundled with Python.
They provide commonly used functionalities such as math operations, date and time handling,
system operations, etc.

You don’t need to install them — just import and use.

🔹 Q2. Examples of Standard Modules

Module Name Purpose

math Mathematical functions like sqrt(), sin(), cos()

datetime Date and time operations

os Interacting with the operating system

sys Accessing system-specific parameters

random Generating random numbers


Module Name Purpose

re Regular expressions

json Working with JSON data

time Time-related functions

🔹 Q3. Example:

import math

print([Link](25)) # Output: 5.0

import random

print([Link](1, 10)) # Random number between 1 and 10

import datetime

print([Link]()) # Prints current date

🔹 Q4. How to View All Standard Modules

Use:

help('modules')

This lists all modules available in your Python installation.

🧠 Q5. Possible Exam Questions

Short Questions

1. What are standard modules in Python?

2. Give two examples of standard modules and their uses.

3. Name the module used for mathematical operations.

4. Which module is used for date and time functions?

5. What is the use of the sys module?

Long / Descriptive Questions

1. Define standard modules. Explain any three with examples.

2. List some commonly used standard modules in Python and explain their purpose.

3. Write short notes on the math and datetime modules.


📝 Sample Exam Answer:

Answer:
Standard modules are built-in modules provided with Python to perform various common tasks.
They save time by providing pre-written code for mathematical, system, and data-handling
operations.

Examples:

import math

print([Link]) # Displays the value of π

import datetime

print([Link]()) # Displays current date and time

Python has many such modules like os, sys, random, and time.
These modules make Python powerful and extensible.

STANDARD PYTHON MODULES -FOR LONG QUESTION


Standard Python modules are built-in modules that come pre-installed with Python.
They are part of the Python Standard Library, which means you can use them directly without
installing anything extra.

Think of them as ready-made tools — each module provides specific functionality such as working
with math, files, time, dates, operating system tasks, etc.

Some of the built in modules are as follows:

1. os Module (Operating System Interface):

The os module provides a way to interact with the operating system. It allows access to file system
operations, environment variables, and system commands.

 Common Functions:

o [Link](): Returns the current working directory.

o [Link](): Lists all files and directories in a given directory.

o [Link](): Creates a new directory.

o [Link](): Deletes a file.

o [Link](): Joins directory and file paths correctly.

Example:

import os
print([Link]()) # Prints current directory

[Link]("new_folder") # Creates a new folder

2. sys Module (System-Specific Parameters and Functions):

The sys module provides functions and variables used to manipulate different parts of the Python
runtime environment.

 Common Functions:

o [Link]: List of command-line arguments passed to the script.

o [Link](): Exits from Python.

o [Link]: A list of directories Python searches for modules.

o [Link], [Link]: Input and output stream handlers.

Example:

import sys

print([Link]) # Prints command-line arguments

[Link]("Exiting script") # Exits the script with a message

3. math Module (Mathematical Functions):

The math module provides access to mathematical functions like trigonometry, logarithms, and
constants like pi and e.

 Common Functions:

o [Link](x): Returns the square root of x.

o [Link](n): Returns the factorial of n.

o [Link](x, y): Returns x raised to the power of y.

o [Link](x), [Link](x): Trigonometric functions.

Example:

import math

print([Link](16)) # Output: 4.0

print([Link]) # Output: 3.141592653589793

4. random Module (Generating Random Numbers):

The random module is used for generating random numbers, selecting random items from a list,
shuffling a list, etc. It’s often used in games, simulations, and testing.

 Common Functions:

o [Link](): Returns a random float between 0 and 1.

o [Link](a, b): Returns a random integer between a and b.


o [Link](sequence): Returns a random element from a sequence (like a list or
string).

o [Link](list): Randomly shuffles a list.

Example:

import random

print([Link](1, 10)) # Random integer between 1 and 10

numbers = [1, 2, 3, 4, 5]

[Link](numbers) # Shuffles the list in place

print(numbers)

5. datetime Module (Date and Time Handling):

The datetime module provides classes for manipulating dates and times. It allows for time
arithmetic, formatting, and parsing.

 Common Functions:

o [Link](): Returns the current date and time.

o [Link](): Returns today’s date.

o [Link](days=x): Represents the difference between two dates or times.

Example:

import datetime

now = [Link]()

print(now) # Current date and time

today = [Link]()

print(today) # Today's date

6. json Module (Working with JSON Data):

The json module is used for parsing and working with JSON (JavaScript Object Notation) data, which
is commonly used for data interchange in web applications.

 Common Functions:

o [Link](): Parses a JSON string into a Python dictionary.

o [Link](): Converts a Python object (like a dictionary) into a JSON string.

Example:

import json

data = '{"name": "Alice", "age": 25}'

parsed_data = [Link](data)
print(parsed_data) # Output: {'name': 'Alice', 'age': 25}

python_dict = {"name": "Bob", "age": 30}

json_string = [Link](python_dict)

print(json_string) # Output: {"name": "Bob", "age": 30}

7. re Module (Regular Expressions):

The re module is used for matching strings using regular expressions (regex). This allows for pattern-
based searching, matching, and manipulation of strings.

 Common Functions:

o [Link](): Checks if the beginning of a string matches a regex pattern.

o [Link](): Searches for a regex pattern anywhere in the string.

o [Link](): Returns all matches of a regex pattern in a string.

o [Link](): Replaces occurrences of a pattern with a replacement string.

Example:

import re

pattern = r"\d+" # Regex pattern to match digits

text = "The price is 100 dollars"

match = [Link](pattern, text)

print([Link]()) # Output: 100

Conclusion:

These built-in Python modules are powerful and versatile tools that simplify tasks like file operations,
math, random number generation, date handling, JSON parsing, and string pattern matching. They
form an integral part of Python's standard library, allowing developers to efficiently handle common
programming requirements.

PACKAGES

What is a Package in Python?

In Python, a package is a collection of modules that are organized together in a directory (folder) to
make code easier to manage and reuse.
In simple words:
A module is a single Python file (like [Link]),
whereas a package is a folder containing multiple modules and a special file called __init__.py.

Analogy

 Think of a module as a single book (e.g., “Maths Book”).

 A package is like a bookshelf that holds many related books (modules) on one topic.

Structure of a Package
A package is simply a directory with:

 A special file named __init__.py

 One or more Python modules.

Here’s how a simple package looks:

my_package/

├── __init__.py

├── [Link]

├── [Link]

└── [Link]

📘 Explanation:

 __init__.py → tells Python that this folder is a package.


(It can be empty or contain initialization code.)

 [Link], [Link], etc. → are modules inside the package.

Creating a Package (Step-by-Step Example)

Let’s create our own package called calculator.

Step 1️⃣: Create Folder

Create a folder named calculator.


Step 2️⃣: Create Files

Inside it, create:

__init__.py

# __init__.py

print("Calculator package is being imported!")

[Link]

def add(a, b):

return a + b

[Link]

def subtract(a, b):

return a - b

[Link]

def multiply(a, b):

return a * b

Step 3️⃣: Use the Package

Now, create a separate file outside the package (say [Link]):


from calculator import addition, subtraction, multiplication

print([Link](5, 3))

print([Link](10, 4))

print([Link](6, 7))

Output:

Calculator package is being imported!

42

What is __init__.py in a Python Package?

__init__.py is a special file that tells Python that the directory should be treated as a package.

In short:

When Python sees an __init__.py file inside a folder, it knows —


“ This folder is a package, not just a random folder.”

Difference Between Module and Package

Term Description Example

Module A single Python file containing code (functions, classes, etc.) [Link]

Package A folder containing multiple modules and __init__.py numpy, pandas, etc.

Structure of a package

Example Structure

my_package/

├── __init__.py

├── [Link]

├── [Link]
└── sub_package/

├── __init__.py

└── [Link]

Why Use Packages?

Reason Explanation

Organization Keeps large projects well-structured.

Reusability Same package can be reused in different programs.

Maintainability Easier to update or fix one part of the code.

Namespace separation Avoids naming conflicts between different modules.

Using __all__ in __init__.py


__all__ is a list that defines which modules should be imported when you use the wildcard (*)
import.

Example:

# __init__.py

__all__ = ['addition', 'subtraction']

Now:

from calculator import *

will import only those two modules.

Importing from Sub-packages

You can also import from nested packages.

Example:

science/

├── __init__.py

├── physics/

│ ├── __init__.py

│ └── [Link]

└── chemistry/

├── __init__.py

└── [Link]

Usage:
from [Link] import mechanics

Installing and Using External Packages

Python includes a Package Manager called PIP (Pip Installs Packages).

Installing:

pip install numpy

pip install pandas

Using:

import numpy as np

import pandas as pd

arr = [Link]([1, 2, 3])

print(arr)

Creating Your Own Custom Package — Example

Let’s create a simple custom package called mathops.

mathops/

├── __init__.py

├── [Link]

└── [Link]

[Link]

def add(a, b):

return a + b

[Link]

def multiply(a, b):

return a * b

[Link]

from .addition import add

from .multiplication import multiply

[Link]

from mathops import add, multiply


print(add(5, 10))

print(multiply(3, 7))

✅ Output:

15

21

You might also like