Python course ยท Module 3: Object-Oriented Programming

Decorators - adapting to the environment

13 min read ยท
In this lesson12

Welcome to the final lesson in Module 3! Darwin here with an advanced final lesson.

In nature, animals adapt to their environment - chameleons gain the ability to change color, bats develop echolocation, migratory birds develop magnetic navigation. In Python, decorators allow a similar adaptation - they modify the behavior of functions and classes without changing their code!

# Regular function
def observe_species(name):
    print(f"Observation: {name}")

# Function with decorator - automatic logging!
@log_observation
def observe_species(name):
    print(f"Observation: {name}")

The function body did not change. One line, @log_observation, above the definition is enough to log every call automatically. You will see how to write such a decorator in a moment.

What are decorators?

A decorator is a function that takes another function (or class) and returns a modified version.

Safari Analogy: It's like equipping a researcher - binoculars don't change the researcher, but they extend their observation capabilities!

def my_decorator(func):
    """Decorator - takes a function, returns modified version"""
    def wrapper():
        print("Something before the function")
        func()  # Call the original function
        print("Something after the function")
    return wrapper

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

say_hello()

Calling say_hello() prints:

Something before the function
Hello!
Something after the function

The middle line comes from the original function, the other two from the wrapper that the decorator put in place of say_hello.

The @decorator syntax is shorthand for:

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

say_hello = my_decorator(say_hello)  # Manual decorating

How do decorators work?

A decorator is a higher-order function - a function that operates on functions!

def simple_decorator(func):
    """
    Decorator - wrapper pattern

    1. Accept a function
    2. Define wrapper
    3. Return wrapper
    """
    def wrapper():
        print(f"[BEFORE] Calling {func.__name__}")
        result = func()
        print(f"[AFTER] Finished {func.__name__}")
        return result
    return wrapper

@simple_decorator
def greet():
    print("Hello!")
    return "Done"

# greet is now wrapper, not the original function!
greet()

The program prints:

[BEFORE] Calling greet
Hello!
[AFTER] Finished greet

The wrapper also returns the original function's result (result), so the value "Done" is not lost on the way.

Decorators with function arguments

For the decorator to work with functions that accept arguments, use *args and **kwargs:

def log_decorator(func):
    def wrapper(*args, **kwargs):
        """Wrapper accepts any arguments"""
        print(f"Calling {func.__name__} with args={args}, kwargs={kwargs}")
        result = func(*args, **kwargs)
        print(f"Result: {result}")
        return result
    return wrapper

@log_decorator
def add(a, b):
    return a + b

@log_decorator
def greet(name, greeting="Hello"):
    return f"{greeting}, {name}!"

add(5, 3)

greet("Darwin", greeting="Hi")

Both calls print:

Calling add with args=(5, 3), kwargs={}
Result: 8
Calling greet with args=('Darwin',), kwargs={'greeting': 'Hi'}
Result: Hi, Darwin!

The same wrapper handled a function with two positional arguments and a function with a keyword argument: *args collects the positional arguments and **kwargs the keyword ones.

functools.wraps - preserving metadata

Problem: the decorator changes the function's __name__ and __doc__!

def my_decorator(func):
    def wrapper(*args, **kwargs):
        return func(*args, **kwargs)
    return wrapper

@my_decorator
def important_function():
    """This function is important"""
    pass

print(important_function.__name__)  # "wrapper" - wrong!
print(important_function.__doc__)   # None - no documentation!

Solution: Use @functools.wraps!

from functools import wraps

def my_decorator(func):
    @wraps(func)  # Preserve original function metadata
    def wrapper(*args, **kwargs):
        return func(*args, **kwargs)
    return wrapper

@my_decorator
def important_function():
    """This function is important"""
    pass

print(important_function.__name__)  # "important_function" - correct!
print(important_function.__doc__)   # "This function is important" - preserved!

IMPORTANT: Always use @wraps(func) in your decorators!

Decorators with parameters

For a decorator to accept parameters, you need three levels of functions:

def repeat(times):
    """Decorator with parameter - repeat function N times"""
    def decorator(func):
        @wraps(func)
        def wrapper(*args, **kwargs):
            for i in range(times):
                result = func(*args, **kwargs)
            return result
        return wrapper
    return decorator

@repeat(times=3)  # Decorator parameter!
def say_hello():
    print("Hello!")

say_hello()

A single call to say_hello() now prints Hello! three times, because the wrapper runs the original function in a for loop as many times as you pass in times.

Structure:

  1. repeat(times) - returns the decorator
  2. decorator(func) - the actual decorator
  3. wrapper(*args, **kwargs) - the function wrapper

Built-in decorators

You already know some of Python's built-in decorators!

@property, @classmethod, @staticmethod

You know all three from earlier lessons. They are ordinary decorators built into Python: each one changes how the method below it is called.

class Species:
    def __init__(self, name, population):
        self._name = name
        self._population = population

    @property  # Getter
    def name(self):
        return self._name

    @property
    def population(self):
        return self._population

    @population.setter  # Setter
    def population(self, value):
        if value < 0:
            raise ValueError("Population cannot be negative")
        self._population = value

    @classmethod  # Class method
    def from_dict(cls, data):
        return cls(data['name'], data['population'])

    @staticmethod  # Static method
    def is_valid_name(name):
        return len(name) > 0

Practical decorator examples

1. Timing decorator - measuring execution time

This decorator records the time before and after the call and prints the difference in seconds. The measured function does not need any changes:

import time
from functools import wraps

def timer(func):
    """Measure function execution time"""
    @wraps(func)
    def wrapper(*args, **kwargs):
        start = time.time()
        result = func(*args, **kwargs)
        end = time.time()
        print(f"โฑ {func.__name__} took {end - start:.4f}s")
        return result
    return wrapper

@timer
def analyze_dna_sequence(sequence):
    """Simulate DNA analysis - time-consuming operation"""
    time.sleep(2)  # Simulation
    return f"Analyzed {len(sequence)} nucleotides"

result = analyze_dna_sequence("ATCGATCG")  # โฑ analyze_dna_sequence took 2.0015s

2. Logger decorator - automatic logging

The logging decorator prints the date and time, the function name and the arguments of every call, then the result or the error. It doesn't swallow the exception but passes it on with raise:

from functools import wraps
from datetime import datetime

def log_calls(func):
    """Log every function call"""
    @wraps(func)
    def wrapper(*args, **kwargs):
        timestamp = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
        print(f"[{timestamp}] Call: {func.__name__}")
        print(f"  Arguments: args={args}, kwargs={kwargs}")

        try:
            result = func(*args, **kwargs)
            print(f"  Success: {result}")
            return result
        except Exception as e:
            print(f"  Error: {e}")
            raise
    return wrapper

@log_calls
def observe_species(name, location, count):
    """Record a species observation"""
    if count < 0:
        raise ValueError("Count cannot be negative")
    return f"Recorded: {count}x {name} in {location}"

observe_species("Lion", "Serengeti", 12)

The console shows (with the current date and time):

[2024-01-15 14:30:45] Call: observe_species
  Arguments: args=('Lion', 'Serengeti', 12), kwargs={}
  Success: Recorded: 12x Lion in Serengeti

If the function raised an error, for example for a negative count, you would see an Error line instead of Success, and the exception would travel on to the calling code.

3. Cache decorator - memoization

The cache decorator remembers the result for every set of arguments. On a later call with the same arguments it returns the stored value instead of computing it again:

from functools import wraps

def cache(func):
    """Cache results - don't recalculate the same thing twice"""
    cached_results = {}

    @wraps(func)
    def wrapper(*args):
        if args in cached_results:
            print(f"Cache hit for {args}")
            return cached_results[args]

        print(f"Computing for {args}")
        result = func(*args)
        cached_results[args] = result
        return result

    return wrapper

@cache
def fibonacci(n):
    """Calculate the n-th Fibonacci number"""
    if n < 2:
        return n
    return fibonacci(n - 1) + fibonacci(n - 2)

print(fibonacci(5))

The program prints:

Computing for (5,)
Computing for (4,)
Computing for (3,)
Computing for (2,)
Computing for (1,)
Computing for (0,)
Cache hit for (1,)
Cache hit for (2,)
Cache hit for (3,)
5

Every value from 0 to 5 is computed only once, and the second calls for 1, 2 and 3 take the result from the cache. Without the decorator the same function would run 15 times, and for a larger n the number of calls explodes.

Note: Python has a built-in @functools.lru_cache!

from functools import lru_cache

@lru_cache(maxsize=128)  # Remembers the last 128 results
def fibonacci(n):
    if n < 2:
        return n
    return fibonacci(n - 1) + fibonacci(n - 2)

4. Access control decorator - authorization

This decorator takes a parameter, the expected code, and checks the first argument of the call. The function receives the remaining arguments only when the code matches:

from functools import wraps

def require_authorization(authorization_code):
    """Decorator with parameter - requires authorization"""
    def decorator(func):
        @wraps(func)
        def wrapper(*args, **kwargs):
            # Check if the first argument is a valid code
            if len(args) == 0 or args[0] != authorization_code:
                raise PermissionError(f"Unauthorized access to {func.__name__}")

            # Remove authorization code from arguments
            return func(*args[1:], **kwargs)
        return wrapper
    return decorator

@require_authorization("SAFARI_2024")
def access_classified_data(species_name):
    """Access to classified data - requires authorization"""
    return f"Classified data about {species_name}: [CLASSIFIED]"

# Correct authorization
print(access_classified_data("SAFARI_2024", "Black Rhinoceros"))
# "Classified data about Black Rhinoceros: [CLASSIFIED]"

# No authorization - error!
try:
    print(access_classified_data("WRONG_CODE", "Black Rhinoceros"))
except PermissionError as e:
    print(f"Error: {e}")

5. Retry decorator - automatic retrying

A connection to a remote research station sometimes drops. The retry decorator catches the exception, waits a moment and tries again until it runs out of attempts:

from functools import wraps
import time

def retry(max_attempts=3, delay=1):
    """Retry operation on error"""
    def decorator(func):
        @wraps(func)
        def wrapper(*args, **kwargs):
            for attempt in range(1, max_attempts + 1):
                try:
                    return func(*args, **kwargs)
                except Exception as e:
                    print(f"Attempt {attempt}/{max_attempts} failed: {e}")
                    if attempt < max_attempts:
                        print(f"Retrying in {delay}s...")
                        time.sleep(delay)
                    else:
                        print("All attempts exhausted")
                        raise
        return wrapper
    return decorator

@retry(max_attempts=3, delay=0.5)
def unstable_connection(success_rate=0.3):
    """Simulate an unstable connection"""
    import random
    if random.random() > success_rate:
        raise ConnectionError("Connection interrupted")
    return "Success!"

# Automatically retries on error
result = unstable_connection(success_rate=0.8)

Stacking multiple decorators

Decorators can be stacked - apply multiple at once!

@decorator1
@decorator2
@decorator3
def my_function():
    pass

This works the same as wrapping by hand: my_function = decorator1(decorator2(decorator3(my_function))). decorator3 is closest to the function, so it wraps it first.

Order matters - executed bottom to top!

from functools import wraps

def bold(func):
    @wraps(func)
    def wrapper(*args, **kwargs):
        return f"**{func(*args, **kwargs)}**"
    return wrapper

def italic(func):
    @wraps(func)
    def wrapper(*args, **kwargs):
        return f"_{func(*args, **kwargs)}_"
    return wrapper

@bold
@italic
def greet(name):
    return f"Hello, {name}"

print(greet("Darwin"))  # "**_Hello, Darwin_**"

First italic wrapped the result in underscores, then bold added the asterisks. The order of execution is greet โ†’ italic โ†’ bold.

Class decorators

Decorators can also modify entire classes!

def singleton(cls):
    """Class decorator - Singleton pattern"""
    instances = {}

    @wraps(cls)
    def get_instance(*args, **kwargs):
        if cls not in instances:
            instances[cls] = cls(*args, **kwargs)
        return instances[cls]

    return get_instance

@singleton
class DatabaseConnection:
    def __init__(self, host):
        self.host = host
        print(f"Connecting to {host}...")

# First instance
db1 = DatabaseConnection("localhost")  # Prints: "Connecting to localhost..."

# "Second" instance - actually the same one!
db2 = DatabaseConnection("localhost")  # Prints nothing

print(db1 is db2)  # True - same object!

Safari example - complete system with decorators

Finally, a species class with five decorators at work: logging and timing of observations, population validation, authorization for deleting, and a cache for calculations.

from functools import wraps
from datetime import datetime
import time
from typing import Callable, Any

# === DECORATORS ===

def log_observation(func: Callable) -> Callable:
    """Log all species observations"""
    @wraps(func)
    def wrapper(*args, **kwargs):
        timestamp = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
        print(f"[{timestamp}] Observation: {func.__name__}")
        result = func(*args, **kwargs)
        print(f"   Recorded: {result}")
        return result
    return wrapper

def measure_time(func: Callable) -> Callable:
    """Measure operation execution time"""
    @wraps(func)
    def wrapper(*args, **kwargs):
        start = time.time()
        result = func(*args, **kwargs)
        elapsed = time.time() - start
        print(f"   โฑ Time: {elapsed:.3f}s")
        return result
    return wrapper

def validate_population(func: Callable) -> Callable:
    """Validate population data before saving"""
    @wraps(func)
    def wrapper(self, population: int, *args, **kwargs):
        if not isinstance(population, int):
            raise TypeError("Population must be an integer")
        if population < 0:
            raise ValueError("Population cannot be negative")
        return func(self, population, *args, **kwargs)
    return wrapper

def require_auth(authorization_level: str):
    """Require authorization level"""
    def decorator(func: Callable) -> Callable:
        @wraps(func)
        def wrapper(self, auth_code: str, *args, **kwargs):
            if auth_code != f"SAFARI_{authorization_level}":
                raise PermissionError(
                    f"Required level: {authorization_level}"
                )
            return func(self, *args, **kwargs)
        return wrapper
    return decorator

def cache_result(func: Callable) -> Callable:
    """Cache computation results"""
    cache = {}

    @wraps(func)
    def wrapper(*args):
        if args in cache:
            print(f"   Cache hit")
            return cache[args]

        result = func(*args)
        cache[args] = result
        return result

    return wrapper

# === CLASS WITH DECORATORS ===

class Species:
    """
    Species class with Safari decorators

    Demonstration: logging, timing, validation, authorization, cache
    """

    _registry = {}

    def __init__(self, scientific_name: str, common_name: str, population: int):
        self.scientific_name = scientific_name
        self.common_name = common_name
        self._population = population
        self.observations = []

        Species._registry[scientific_name] = self

    @property
    def population(self) -> int:
        """Getter - regular property"""
        return self._population

    @population.setter
    @validate_population  # Validation decorator!
    def population(self, value: int) -> None:
        """Setter with automatic validation"""
        self._population = value

    @log_observation  # Automatic logging
    @measure_time     # Time measurement
    def add_observation(self, location: str, count: int, date: str) -> str:
        """
        Add observation - automatically logged and timed

        Decorators: @log_observation, @measure_time
        """
        time.sleep(0.1)  # Simulate operation
        obs = {
            "location": location,
            "count": count,
            "date": date
        }
        self.observations.append(obs)
        return f"{count}x {self.common_name} in {location}"

    @cache_result  # Cache results
    def calculate_biodiversity_score(self) -> float:
        """
        Calculate biodiversity score - with cache

        Time-consuming operation - cache saves time!
        """
        print(f"   Computing score for {self.common_name}...")
        time.sleep(0.5)  # Simulate complex computations

        total_obs = sum(obs["count"] for obs in self.observations)
        unique_locations = len(set(obs["location"] for obs in self.observations))

        return (total_obs * unique_locations) / (self.population + 1)

    @require_auth("ADMIN")  # Requires ADMIN authorization
    def delete_all_observations(self) -> str:
        """
        Delete all observations - requires ADMIN authorization

        Decorator: @require_auth("ADMIN")
        """
        count = len(self.observations)
        self.observations.clear()
        return f"Deleted observations: {count}"

    @classmethod
    def get_total_population(cls) -> int:
        """Total population of all species"""
        return sum(s.population for s in cls._registry.values())

    @staticmethod
    @cache_result  # Even static methods can be cached!
    def calculate_extinction_risk(population: int, habitat_loss: float) -> str:
        """
        Calculate extinction risk - with cache

        Args:
            population: Number of individuals
            habitat_loss: Habitat loss (0.0-1.0)
        """
        print(f"   Computing risk...")
        time.sleep(0.3)

        risk_score = (1000 - population) * habitat_loss

        if risk_score > 800:
            return "Critical"
        elif risk_score > 500:
            return "High"
        elif risk_score > 200:
            return "Medium"
        else:
            return "Low"

    def __repr__(self) -> str:
        return f"Species('{self.common_name}', pop={self.population})"

# === DEMONSTRATION ===

print("=== SAFARI SYSTEM WITH DECORATORS ===\n")

# Creating species
lion = Species("Panthera leo", "Lion", 120)
rhino = Species("Diceros bicornis", "Rhinoceros", 45)

# 1. Observations - automatic logging and timing
print("\n1. OBSERVATIONS (with @log_observation and @measure_time):")
lion.add_observation("Serengeti", 12, "2024-01-15")
lion.add_observation("Masai Mara", 8, "2024-01-16")

# 2. Population validation
print("\n2. VALIDATION (@validate_population):")
try:
    lion.population = -10  # Error - negative!
except ValueError as e:
    print(f"Validation error: {e}")

try:
    lion.population = "hundred"  # Error - not int!
except TypeError as e:
    print(f"Type error: {e}")

lion.population = 125  # OK
print(f"Population updated: {lion.population}")

# 3. Cache - biodiversity score
print("\n3. CACHE (@cache_result):")
print("First call:")
score1 = lion.calculate_biodiversity_score()
print(f"Score: {score1:.2f}")

print("\nSecond call (from cache):")
score2 = lion.calculate_biodiversity_score()
print(f"Score: {score2:.2f}")

# 4. Authorization
print("\n4. AUTHORIZATION (@require_auth):")
try:
    lion.delete_all_observations("WRONG_CODE")
except PermissionError as e:
    print(f"Access denied: {e}")

result = lion.delete_all_observations("SAFARI_ADMIN")
print(f"{result}")

# 5. Cache in static method
print("\n5. CACHE IN STATIC METHOD:")
print("First call:")
risk1 = Species.calculate_extinction_risk(50, 0.8)
print(f"Risk: {risk1}")

print("\nSecond call (from cache):")
risk2 = Species.calculate_extinction_risk(50, 0.8)
print(f"Risk: {risk2}")

print("\nDifferent parameters (new computation):")
risk3 = Species.calculate_extinction_risk(500, 0.3)
print(f"Risk: {risk3}")

Summary

In this lesson you learned:

  • What decorators are and how they work
  • The @decorator syntax
  • Creating decorators with *args and **kwargs
  • Using @functools.wraps to preserve metadata
  • Decorators with parameters (three levels of functions)
  • Built-in decorators (@property, @classmethod, @staticmethod)
  • Practical examples: timing, logging, cache, authorization, retry
  • Stacking multiple decorators
  • Class decorators
  • Complete Safari system with decorators

Checkpoint

Before moving on:

  • You understand how decorators modify functions
  • You can create a simple decorator
  • You know when to use @wraps
  • You understand decorators with parameters
  • You can stack multiple decorators

Safari Analogy: Decorators are evolutionary adaptations - a chameleon with chromatophores, a bat with echolocation - they extend capabilities without changing the fundamental nature!

Congratulations! You've completed Module 3 - Object-Oriented Programming! You've mastered classes, inheritance, encapsulation, magic methods, type hints, and decorators. You're ready for the next challenges in Python Safari!

Docs entries used in this lesson

Spotted a mistake in this lesson?

Check yourself

Answer the questions from this lesson. Pick an answer to see right away whether it is correct.

  1. 1. A decorator in Python is:

  2. 2. By convention, what is the first parameter of a method marked with @classmethod called?

These are 2 of 6 questions for this lesson. Solve the rest in the game.

Hands-on tasks in the game

  • Horizontal ordering

    Arrange the elements in the correct order:

  • Click in order

    Click elements in the correct order:

  • Code editor

    Create a @classmethod from_dict(cls, data) that creates an Animal from a dictionary with the keys 'name' and 'species', e.g. Animal.from_dict({'name': 'Simba', 'species': 'Lion'})

  • Code editor

    Create a @staticmethod is_dangerous(species) that returns True for the species 'Lion', 'Crocodile' and 'Hippo', and False for any other

  • Horizontal ordering

    Arrange the header of the class method from_dict (the line under the @classmethod decorator):

  • Vertical ordering

    Arrange what happens after calling print(lion) on an object with a __str__ method:

  • Click in order

    Click elements in the correct order:

  • Code editor

    Create classes: Animal (base), Mammal(Animal), Bird(Animal), Tiger(Mammal), Eagle(Bird)

  • Code editor

    In the Animal(name, age, health_status) class, store age and health_status in protected or private attributes (self._age or self.__age) and add the properties age and health_status

  • Vertical ordering

    Arrange the steps for creating a child class:

  • Code editor

    Create a Zoo class with the methods add_animal(animal), remove_animal(name) (removes the animal with that name), find_by_species(species) and list_all() (both return lists of animals). Animals are Animal(name, species) objects

  • Code editor

    Combine Animal and Zoo into a program: create zoo = Zoo() and in a while loop read the choice with input(): 1 - add (name, species), 2 - remove (name), 3 - search by species and print the names, 0 - exit

  • Vertical ordering

    Arrange the method types by their first parameter: first those that receive the object (self), then the class (cls), and last those with neither self nor cls:

  1. QuestionDecorators
  2. Question@classmethod
  3. Question@staticmethod
  4. Put in orderInstance Attribute
  5. Click in orderBuilding a Return Type Hint
  6. Coding taskClass Method
  7. Coding taskStatic Method
  8. Put in orderThe @classmethod Decorator
  9. Put in orderprint() and __str__
  10. Click in orderBuilding a @property Decorator
  11. Coding taskProject - Class Hierarchy
  12. Coding taskProject - Encapsulation
  13. Put in orderInheritance Pattern
  14. Coding taskProject - Zoo Manager
  15. Coding taskProject - Complete System
  16. Put in orderTypes of Methods in a Class
  17. QuestionSummary - Classes
  18. QuestionSummary - Inheritance
  19. QuestionSummary - OOP
  20. Project to submitSubmit Safari Animal Kingdom to Mentor
  21. VideoModule Summary

Useful articles