Python Further Extensions
Python Further Extensions
1. Virtual Environments
Command:
Activate:
Windows: myenv\Scripts\activate
Deactivate: deactivate
Install Packages:
Freeze dependencies:
Install pip:
Upgrade pip:
Install packages:
Uninstall packages:
pip list
3. Modular Programming
Creating Modules:
# mymodule.py
def greet(name):
return f"Hello, {name}!"
Importing Modules:
import mymodule
print(mymodule.greet("Alice"))
Selective Import:
class Dog:
def __init__(self, name, breed):
self.name = name
self.breed = breed
def bark(self):
return "Woof!"
Inheritance:
class Animal:
def speak(self):
return "I am an animal"
class Cat(Animal):
def speak(self):
return "Meow"
5. File Handling
Reading a File:
Writing to a File:
Appending to a File:
Try-Except:
try:
x = 1 / 0
except ZeroDivisionError:
print("Cannot divide by zero")
Multiple Exceptions:
try:
y = int("abc")
except (ValueError, TypeError):
print("Invalid input")
Finally Block:
try:
file = open("file.txt")
finally:
file.close()
7. Decorators
Basic Decorator:
def decorator_func(func):
def wrapper():
print("Before function call")
func()
print("After function call")
return wrapper
@decorator_func
def greet():
print("Hello!")
greet()
Generators:
def my_generator():
for i in range(5):
yield i
Iterators:
my_list = [1, 2, 3]
iter_obj = iter(my_list)
print(next(iter_obj))
9. Context Managers
With Statement:
class ManagedResource:
def __enter__(self):
print("Resource acquired")
with ManagedResource():
print("Using resource")
Unit Testing:
import unittest
class TestMath(unittest.TestCase):
def test_add(self):
self.assertEqual(add(2, 3), 5)
if __name__ == "__main__":
unittest.main()
Debugging:
import pdb
pdb.set_trace()