🐍 Mastering Python Decorators, File Handling & Exception Handling! πŸš€

Β·

3 min read

Welcome back, Python enthusiasts! 🌟 In this blog, we'll explore some advanced Python concepts, including Decorators, File Handling, Exception Handling, Logging, and Importing Modules. Let’s dive in! πŸ˜ƒ


1️⃣ Decorators: Enhancing Functions Dynamically! 🎨

Decorators are functions that modify other functions without changing their code. Useful for logging, authentication, and more! πŸš€

# Basic Decorator Example 🌟
def decorator(func):
    def wrapper():
        print("Before function call")
        func()
        print("After function call")
    return wrapper

@decorator
def greet():
    print("Hello, World!")

greet()

2️⃣ Property Decorators - Getters, Setters, and Deletes 🏑

Python provides @property, @<property>.setter, and @<property>.deleter to manage access to class attributes. πŸš€

class Student:
    def __init__(self, name, price):
        self.__name = name
        self.__price = price

    # Getter for price
    @property
    def acess_price(self):
        return self.__price

    # Setter for price
    @acess_price.setter
    def price_set(self, price_new):
        self.__price = price_new

    # Deleter for price
    @acess_price.deleter
    def acess_price(self):
        del self.__price


# Create a Student object
s = Student("John", 5000)

# Accessing the price
print(s.acess_price)  # Output: 5000

# Updating the price
s.price_set = 7000
print(s.acess_price)  # Output: 7000

# Deleting the price
del s.acess_price

# Trying to access the price after deletion
try:
    print(s.acess_price)  # This will raise an AttributeError as the price is deleted
except AttributeError as e:
    print("Error:", e)

3️⃣ Working with Files πŸ“‚

Python allows easy file handling using built-in functions like open(). Let's explore reading and writing files. πŸ“

Reading & Writing Files (TXT, CSV, JSON) πŸ“„

# Writing to a text file ✍️
with open("example.txt", "w") as file:
    file.write("Hello, Python File Handling!")

# Reading from a text file πŸ“–
with open("example.txt", "r") as file:
    content = file.read()
    print(content)

Buffered Read & Write πŸš€

Buffered reading improves performance by reading data in chunks.

with open("large_file.txt", "rb") as file:
    chunk = file.read(1024)  # Reads 1024 bytes at a time
    while chunk:
        print(chunk)
        chunk = file.read(1024)

Other File Methods πŸ› οΈ

import os

# Checking if a file exists βœ…
print(os.path.exists("example.txt"))

# Renaming a file πŸ”„
os.rename("example.txt", "new_example.txt")

# Deleting a file ❌
os.remove("new_example.txt")

4️⃣ Exception Handling with Try-Except πŸ›‘

Handling errors prevents program crashes. Try-except helps catch errors smoothly. πŸš€

try:
    x = 1 / 0  # Division by zero error ❌
except ZeroDivisionError as e:
    print("Error:", e)
finally:
    print("Execution Completed!")

Custom Exception Handling: Validating Salary πŸ’°

# Custom Exception for Salary Validation
class Validationsalary(Exception):
    def __init__(self, msg):
        self.msg = msg

# Function to validate salary
def validate_salary(salary):
    if salary < 0:
        raise Validationsalary("Negative Salary is Not Possible!")
    elif salary >= 300000:
        raise Validationsalary("Salary is Unacceptable!")
    else:
        print("Salary is Valid!")

# Input and exception handling
try:
    salary = int(input("Enter a salary: "))
    validate_salary(salary)
except Validationsalary as e:
    print(e)

List of General Use Exceptions πŸ“Œ

  • ZeroDivisionError

  • TypeError

  • ValueError

  • FileNotFoundError

  • KeyError


5️⃣ Logging & Debugging πŸ”Ž

Logging helps track errors and events efficiently. πŸ“

import logging

logging.basicConfig(filename="programlog.log", level=logging.DEBUG, format='%(asctime)s %(levelname)s %(message)s')

l = [1, [4, "as"], "hiii", [1, "derr"]]
l1_int = []
l2_str = []
l3_list = []

for i in l:
    logging.info(f"Processing the element: {i}")
    if isinstance(i, list):
        for j in i:
            logging.info(f"Processing sublist element: {j}")
            if isinstance(j, int):
                l1_int.append(j)
            elif isinstance(j, str):
                l2_str.append(j)
    elif isinstance(i, str):
        l2_str.append(i)
    else:
        l1_int.append(i)

logging.info(f"The result is: {l1_int}, {l2_str}")
logging.shutdown()

6️⃣ Modules & Import Statements πŸ“¦

Python allows importing modules for better code organization. πŸš€

Importing Modules the Right Way βœ…

import os, sys
from os.path import dirname, join, abspath

# Adding parent directory to sys.path πŸ“
parent_dir = abspath(join(dirname(__file__), ".."))
sys.path.insert(0, parent_dir)

# Importing from another module 🎯
from teacher import teacher_detail

def student():
    print("This is the Student Details")

teacher_detail.teacher()  # Calling a function from the imported module

This ensures modular programming and avoids import errors when working with directories.


🎯 Wrapping Up! 🎁

Understanding Decorators, File Handling, Exception Handling, Logging, and Imports will help you write efficient and professional Python code. πŸ† Keep experimenting and practicing! πŸ’»πŸ”₯

Happy Coding! πŸŽ‰πŸ‘©β€πŸ’»πŸ‘¨β€πŸ’»

Β