Decorators and Generators

  • Decorators: Functions that modify the behavior of another function or method. They are commonly used for logging, access control, memoization, etc.

Example:

  def my_decorator(func):
    def wrapper():
        print("Something is happening before the function is called.")
        func()
        print("Something is happening after the function is called.")
    return wrapper

@my_decorator
def say_hello():
    print("Hello!")

say_hello()
  
  • Generators: Functions that yield values one at a time, allowing for efficient iteration over large datasets. They use the yield keyword instead of return.

Example:

  def count_up_to(max):
    count = 1
    while count <= max:
        yield count
        count += 1

for number in count_up_to(5):
    print(number)
  

Context Managers

  • Context Managers: Allow you to allocate and release resources precisely when you want to. The most common way to manage resources is using the with statement.

Example:

  with open('file.txt', 'w') as file:
    file.write("Hello, World!")
# The file is automatically closed when the block is exited
  

You can create custom context managers using the contextlib module or by defining the __enter__ and __exit__ methods in a class.

Example:

  from contextlib import contextmanager

@contextmanager
def open_file(name, mode):
    file = open(name, mode)
    yield file
    file.close()

with open_file('file.txt', 'w') as f:
    f.write("Hello, World!")
  

Regular Expressions

  • Regular Expressions (Regex): A powerful tool for matching patterns in text. Python provides the re module for working with regular expressions.

Example:

  import re

pattern = r'\d+'  # Matches one or more digits
text = "The year is 2024."

match = re.search(pattern, text)
if match:
    print(f"Found a match: {match.group()}")
  

Common Regex Functions:

  • re.match(): Checks for a match only at the beginning of the string.
  • re.search(): Searches for a match anywhere in the string.
  • re.findall(): Returns a list of all matches.
  • re.sub(): Replaces matches with a string.

Working with Databases (SQLite, MySQL, etc.)

  • SQLite: A lightweight, disk-based database that doesn’t require a separate server process. Python provides the sqlite3 module to interact with SQLite databases.

Example:

  import sqlite3

connection = sqlite3.connect('example.db')
cursor = connection.cursor()

# Create a table
cursor.execute('''CREATE TABLE users (id INTEGER PRIMARY KEY, name TEXT)''')

# Insert data
cursor.execute("INSERT INTO users (name) VALUES ('Alice')")
connection.commit()

# Query data
cursor.execute("SELECT * FROM users")
print(cursor.fetchall())

connection.close()
  
  • MySQL: A popular relational database management system. You can interact with MySQL databases using the mysql-connector-python or pymysql libraries.

Example:

  import mysql.connector

connection = mysql.connector.connect(
    host="localhost",
    user="yourusername",
    password="yourpassword",
    database="yourdatabase"
)

cursor = connection.cursor()
cursor.execute("SELECT * FROM users")

for row in cursor.fetchall():
    print(row)

connection.close()