Packages in Python

 

Packages in Python

 

Built-In Packages in Python:

Built-in packages in Python refer to modules that are included with the Python standard library. These packages provide various functionalities and can be used without the need for installation or additional downloads. Here are some examples of built-in packages along with their functionalities

1.     os: This module provides a way to interact with the operating system. It offers functions for file operations, directory manipulations, and environment variables.

Example:

import os

 

# Get the current working directory

current_dir = os.getcwd()

print("Current directory:", current_dir)

 

# List all files and directories in the current directory

files_and_dirs = os.listdir()

print("Files and directories:", files_and_dirs)

 

2.     sys: The sys module provides access to some variables used or maintained by the Python interpreter and functions that interact with the interpreter.

Example,

import sys

 

# Get the Python version information

print("Python version:", sys.version)

 

# Get the command line arguments

print("Command line arguments:", sys.argv)

3.      datetime: This module supplies classes for manipulating dates and times.

Example,

from datetime import datetime

 

# Get the current date and time

current_time = datetime.now()

print("Current date and time:", current_time)

 

# Format a date

formatted_date = current_time.strftime("%d-%m-%y")

print("Formatted date:", formatted_date)

4.     math: The math module provides mathematical functions defined by the C standard.

Example,

import math

 

# Calculate the square root

sqrt_value = math.sqrt(25)

print("Square root of 25:", sqrt_value)

 

# Calculate the factorial

factorial_value = math.factorial(5)

print("Factorial of 5:", factorial_value)

 

5.     random: This module provides functions for generating random numbers and samples.

Example,

import random

 

# Generate a random integer between 1 and 100

random_number = random.randint(1, 100)

print("Random number:", random_number)

 

# Choose a random element from a sequence

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

random_element = random.choice(my_list)

print("Random element:", random_element)

 

6.     re: The re module provides support for regular expressions, allowing you to search, match, and manipulate strings based on patterns.

Example,

import re

 

# Search for a pattern in a string

text = "The quick brown fox jumps over the lazy dog."

pattern = r'\b\w{4}\b'  # Match four-letter words

matches = re.findall(pattern, text)

print("Matches:", matches)

 

\b: Match the start of a word.

\w{4}: Match exactly four word characters.

\b: Match the end of a word.

 

7.     json: The json module provides functions for encoding and decoding JSON data.

import json

 

# Encode a Python dictionary to JSON

data = {'name': 'John', 'age': 30, 'city': 'New York'}

json_data = json.dumps(data)

print("JSON data:", json_data)

 

# Decode JSON data to a Python dictionary

decoded_data = json.loads(json_data)

print("Decoded data:", decoded_data)

 

 

8.     csv: The csv module provides functions for reading and writing CSV files.

Example,

import csv

 

# Read data from a CSV file

with open('data.csv', 'r') as file:

    reader = csv.reader(file)

    for row in reader:

        print(row)

 

# Write data to a CSV file

with open('output.csv', 'w', newline='') as file:

    writer = csv.writer(file)

    writer.writerow(['Name', 'Age'])

    writer.writerow(['John', 30])

    writer.writerow(['Jane', 25])

 

9.     collections: The collections module provides additional data structures beyond the built-in types like lists, tuples, and dictionaries.

Example,

from collections import Counter

 

# Count the occurrences of elements in a list

my_list = ['a', 'b', 'c', 'a', 'b', 'a']

counter = Counter(my_list)

print("Element counts:", counter)

 

 

working with arrays in Python,

especially for numerical computations, the numpy library is widely used. numpy provides the ndarray data structure, which is a high-performance multidimensional array object. Here are five examples demonstrating the usage of ndarray in numpy

Creating an Array

import numpy as np

 

# Creating a 1D array

arr1d = np.array([1, 2, 3, 4, 5])

print("1D Array:", arr1d)

 

# Creating a 2D array

arr2d = np.array([[1, 2, 3], [4, 5, 6]])

print("2D Array:")

print(arr2d)

 

# Creating a 3D array

arr3d = np.array([[[1, 2], [3, 4]], [[5, 6], [7, 8]]])

print("3D Array:")

print(arr3d)

 

Array Attributes

import numpy as np

 

arr = np.array([[1, 2, 3], [4, 5, 6]])

 

# Shape of the array

print("Shape:", arr.shape)

 

# Number of dimensions

print("Dimensions:", arr.ndim)

 

# Data type of elements

print("Data Type:", arr.dtype)

 

Array Operations

import numpy as np

 

arr1 = np.array([[1, 2], [3, 4]])

arr2 = np.array([[5, 6], [7, 8]])

 

# Element-wise addition

print("Addition:")

print(arr1 + arr2)

 

# Element-wise multiplication

print("Multiplication:")

print(arr1 * arr2)

 

# Dot product of arrays

print("Dot Product:")

print(np.dot(arr1, arr2))

 

Indexing and Slicing

import numpy as np

 

arr = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]])

 

# Accessing elements

print("Element at (0, 0):", arr[0, 0])

 

# Slicing rows and columns

print("First row:", arr[0])

print("First column:", arr[:, 0])

 

Array Functions

import numpy as np

 

arr = np.array([1, 2, 3, 4, 5])

 

# Sum of all elements

print("Sum:", np.sum(arr))

 

# Mean of all elements

print("Mean:", np.mean(arr))

 

# Max and min elements

print("Max:", np.max(arr))

print("Min:", np.min(arr))

 

 

 

Example: Packages:

a package is a hierarchical directory structure that organizes Python modules and sub-packages. It is a way to structure Python’s module namespace by using “dotted module names”. Packages are useful for organizing related modules into a single, cohesive unit, making it easier to manage and reuse code.

1.     Packages in Python are directories containing Python modules.

2.     They allow you to organize Python code hierarchically.

3.     A package must contain a special file named __init__.py, which can be empty.

4.     Packages can contain sub-packages and modules.

Types of Packages:

Types of Packages in Python:

1.     Regular Packages:

Regular packages are traditional Python packages that contain an __init__.py file.

The __init__.py file can be empty or contain initialization code that runs when the package is imported.

Regular packages are used for organizing modules and sub-packages and are imported using their package name.

2.     Namespace Packages:

Namespace packages are special types of packages that do not require an __init__.py file.

They allow multiple directories or zip files to act as a single package without any central control.

Namespace packages are useful for distributing modules and sub-packages across different locations, such as multiple directories or zip files.

For example,

my_project/

├── regular_package/

   ├── __init__.py

   ├── module1.py

   └── module2.py

└── namespace_package/

    ├── subpackage1/

       └── module3.py

    └── subpackage2/

        └── module4.py

 

In this example:

 

regular_package is a regular package containing two modules: module1.py and module2.py.

namespace_package is a namespace package containing two sub-packages: subpackage1 and subpackage2, each with their own modules.

Both regular packages and namespace packages are used to organize and structure Python code into reusable components, but they differ in the way they are implemented and used. Regular packages follow the traditional structure with an __init__.py file, while namespace packages do not have this requirement and can span across multiple directories or zip files.


Steps to Create User Defined Packages:

Creating Regular Packages

Step 1:


First create a dirictory for your package

The directory is created at current working directory

to check your directory, first check your current working directory

Code for Creating Userdefined Package

# In Jupyter Cell write code as follows

# Create a directory for your package

!mkdir my_package


!mkdir my_package, is used to create a new directory named my_package in the current working directory.


Here's what each part of the command does:


!: This symbol tells Jupyter Notebook to execute the following command in the shell or command prompt.

mkdir: This is a shell command to create a new directory.

my_package: This is the name of the directory you want to create.

So, when you run !mkdir my_package, Jupyter Notebook creates a new directory named my_package in the current directory where the notebook is located.

Execute this command t check what is your current working directory, because the package or directory will create by default in your current working directory.

import os

os.getcwd()

Run this code and check current working directory.  You can go to the current working directory to see your package is created or not. 

Step 2:

Create __init__.py File

Inside the package directory, create an init.py file. This file can be empty or contain initialization code.

# Create __init__.py file

import os


# Define the package name

package_name = "my_package"


# Define the path to the package directory

package_path = os.path.join(os.getcwd(), package_name)


# Create the package directory

os.makedirs(package_path, exist_ok=True)


# Create the __init__.py file inside the package directory

init_file_path = os.path.join(package_path, '__init__.py')

with open(init_file_path, 'w') as f:

    pass  # This creates an empty __init__.py file

Explanation of Code:

This code creates a Python package named my_package in the current working directory of the Jupyter Notebook environment. Here's what each part of the code does:


1. import os: Imports the os module, which provides functions for interacting with the operating system.

2. package_name = "my_package": Defines the name of the package as "my_package".

3. package_path = os.path.join(os.getcwd(), package_name): Constructs the full path to the package directory by joining the current working directory (os.getcwd()) with the package name.

4. os.makedirs(package_path, exist_ok=True): Creates the package directory specified by package_path. The exist_ok=True parameter ensures that the function doesn't raise an error if the directory already exists.

5. init_file_path = os.path.join(package_path, '__init__.py'): Constructs the full path to the __init__.py file inside the package directory.

6. with open(init_file_path, 'w') as f:: Opens the __init__.py file in write mode. If the file doesn't exist, it creates a new one.

7. pass: Since we're only interested in creating an empty __init__.py file to indicate that the directory is a Python package, we use the pass statement to do nothing inside the file.

Overall, this code sets up the basic structure of a Python package by creating a directory with the package name and adding an empty __init__.py file inside it.


Step 3: Create module files

Create Python module files inside the package directory. These files will contain timport os


# Define the desktop directory path

file_path = os.path.join(os.path.expanduser('~'), "C:\\Users\\Admin\\my_package")


# Create module files inside the package directory

module1_file_path = os.path.join(file_path, 'module1.py')

with open(module1_file_path, 'w') as f:

    pass  # This creates an empty module1.py file


module2_file_path = os.path.join(file_path, 'module2.py')

with open(module2_file_path, 'w') as f:

    pass  # This creates an empty module2.py filehe code for your package's functionality.


Explanation of Code:

This code creates two Python module files (module1.py and module2.py) inside the my_package directory. Here's what each part of the code does:


import os: Imports the os module for interacting with the operating system.

file_path = os.path.join(os.path.expanduser('~'), "C:\\Users\\Admin\\my_package"): Constructs the full path to the my_package directory by joining the user's home directory (os.path.expanduser('~')) with the specified relative path.

module1_file_path = os.path.join(file_path, 'module1.py'): Constructs the full path to the module1.py file inside the my_package directory.

with open(module1_file_path, 'w') as f:: Opens the module1.py file in write mode. If the file doesn't exist, it creates a new one.

pass: Since we're only interested in creating an empty module1.py file, we use the pass statement to do nothing inside the file.

Similar steps are repeated for creating module2.py file.

Overall, this code sets up the basic structure of a Python package by creating two empty module files inside the my_package directory.


Step 4: Write code to Module:

# Write code in module1.py

with open("my_package/module1.py", "w") as f:

    f.write("""

def greet(name):

    return f"Hello, {name}!"

""")


# Write code in module2.py

with open("my_package/module2.py", "w") as f:

    f.write("""

def add(a, b):

    return a + b

""")

Explanation of Code:

This code creates two Python module files, module1.py and module2.py, inside the my_package package directory.


In module1.py, a function greet is defined that takes a name parameter and returns a greeting message.

In module2.py, a function add is defined that takes two parameters a and b, and returns their sum.

Each file is opened in write mode ("w"), allowing new content to be written to it. The write() function is then used to write the Python code defining the respective functions into each file.

Step 5: Import and Use Package

You can now import and use your package and its modules in the same Jupyter Notebook or any other Python script.

# Now you can import the package and its modules

import my_package.module1 as m1

import my_package.module2 as m2


# Use functions from modules

print(m1.greet("Dr. Manisha More"))

print(m2.add(3000, 400000))

Code Explanation:

This code demonstrates how to import modules from the my_package package and use the functions defined within them.


import my_package.module1 as m1 imports module1 from the my_package package and assigns it an alias m1.

import my_package.module2 as m2 imports module2 from the my_package package and assigns it an alias m2.

After importing the modules, their functions can be accessed using the aliases (m1 and m2) followed by a dot (.) notation to access the function names. Finally, the imported functions are invoked with appropriate arguments and their results are printed.

Create Module named module4.py inside the my_package package and write code to find the largest and smallest numbers:

Create Module:

# Create module4.py

with open("my_package/module4.py", "w") as f:

    f.write("""

def find_largest_smallest(numbers):

    if not numbers:

        return None, None

    return max(numbers), min(numbers)

""")

Now You can import your module from your package in Python script to perform the operation

# Now you can import the module and use the function

import my_package.module4 as m4

# Example usage

numbers = [10, 5, 20, 8, 15]

largest, smallest = m4.find_largest_smallest(numbers)

print("Largest number:", largest)

print("Smallest number:", smallest)

Result:

Largest number: 20

Smallest number: 5



टिप्पणी पोस्ट करा

0 टिप्पण्या