How To Make A Simple Function Decorator (Python Recipes)

preview_player
Показать описание
In this video I will be showing you how you can create a simple function decorator in Python! Decorators are some of Python's best sugar syntax which make applying extra functionality much more convenient.

▶ Become job-ready with Python:

▶ Follow me on Instagram:
Рекомендации по теме
Комментарии
Автор

For anyone wondering how to fully type hint a decorator, here it is.

import functools
from typing import Callable, ParamSpec, TypeVar

P = ParamSpec("P")
T = TypeVar("T")

def time_func(func: Callable[P, T]) -> Callable[P, T]:
@functools.wraps(func)
def wrapper(*args: P.args, **kwargs: P.kwargs) -> T:
# code
result = func(*args, **kwargs)
# code
return result
return wrapper

What ParamSpec does, is it captures not only the exact signature of the callable, but the names of the args as well.

aaronvegoda
Автор

You should do a pytest video using conftest and show how to mock a wrapped method (I did this recently at work, I'm a senior dev and it certainly wasn't easy just using docs/copilot lol)

obsidiansiriusblackheart
Автор

Functools wraps solved my biggest problem(I was trying to apply two decorators).

Thanks for this!!

therealslimaddy
Автор

I always have a confusion with decorators, Thanks for this video❤

I cannot quite understand the super function can please explain it in the next video

ranjithkumars
Автор

Is there a decorator that makes a functuon async? Without infecting all the functions that call it to be async aswell? Thanks

fire
Автор

Good video but it'd be helpful if you either briefly summarized what a 'decorator' does or pointed to one of your earlier videos that discussed it.

danbromberg
Автор

And here I was thinking a decorator in Python was a feather boa. ;)

anon_y_mousse
Автор

Lambda and nested lambda decorators are novel but neat

celestialowl
Автор

I heard also about decorators with parameters, but the way it's implemented looks dirty to me, so i prefer using functions composition/currying instead of decorators when it becomes more complex.

TristanM
Автор

If you do this you totally loose the type signature of your function. It becomes `(...) -> Any`

ApprendreSansNecessite
Автор

May someone tell me that which app is this?

kundan.
Автор

I read a decorator is a macro, but it's written in python.

DrDeuteron