π Mastering Python Decorators, File Handling & Exception Handling! π
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! ππ©βπ»π¨βπ»