Python Decorator

Resources

In Python, a decorator is a design pattern that allows you to modify the functionality of a function by wrapping it in another function.

The outer function is called the decorator, which takes the original function as an argument and returns a modified version of it.

def make_pretty(func):
    def inner():
        print("I got decorated")
        func()
    return inner
 
@make_pretty
def ordinary():
    print("I am ordinary")
 
ordinary()  
# Output:
# I got decorated
# I am ordinary

Is there a relationship between Python Decorators and the Decorator Design Pattern that I saw in C++?

class User:
    kind = "human"
 
    def __init__(self, name: str):
        self.name = name
 
    def greet(self):                 # instance method
        return f"hi, I'm {self.name}"
 
    @staticmethod
    def is_valid_name(name: str):     # utility scoped to User
        return bool(name.strip())
 
    @classmethod
    def anonymous(cls):               # respects subclasses
        return cls("anonymous")
 
    @property
    def display_name(self):           # computed attribute
        return self.name.title()