How To Make A Simple Function Decorator (Python Recipes)

  Рет қаралды 8,731

Indently

Indently

20 күн бұрын

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:
www.indently.io
▶ Follow me on Instagram:
/ indentlyreels

Пікірлер: 41
@aaronvegoda1907
@aaronvegoda1907 18 күн бұрын
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.
@ApprendreSansNecessite
@ApprendreSansNecessite 17 күн бұрын
Amazing! You even get the parameter *names* and not only their types That's the way to do it
@JorjaRebeca-qw8tv
@JorjaRebeca-qw8tv 14 күн бұрын
Sorry
@therealslimaddy
@therealslimaddy 16 күн бұрын
Functools wraps solved my biggest problem(I was trying to apply two decorators). Thanks for this!!
@fire17102
@fire17102 18 күн бұрын
Is there a decorator that makes a functuon async? Without infecting all the functions that call it to be async aswell? Thanks
@largewallofbeans9812
@largewallofbeans9812 18 күн бұрын
Making a function async intrinsically requires functions that await it to be async as well. To run an async function without awaiting it, use `asyncio.run(function())`, where "function" is your async function.
@fire17102
@fire17102 18 күн бұрын
@@largewallofbeans9812 thanks! Though still wondering if there's a asyncio decorator that does that automatically
@_Blazing_Inferno_
@_Blazing_Inferno_ 18 күн бұрын
Is there a way of telling from function 2 whether function 1 (which calls function 2) is async? If there is, you might be able to make your own where the wrapper could call async.run(function2()) if function 1 is not async, but if function 1 is async, the wrapper can just call function 2 normally. If there isn’t such a thing you might still be able to make a wrapper like `wrapper(is_async: bool, *args, **kwargs)` which then calls function2(*args, **kwargs) or async.run(function2(*args, **kwargs)) based on what is_async is (which function 1 would have to directly supply). I haven’t messed with async/await yet and haven’t successfully found how to check stuff about caller functions from callee functions, though, so I might be misunderstanding how these things work
@user-vt9bp2ei1w
@user-vt9bp2ei1w 17 күн бұрын
​@@_Blazing_Inferno_This doesn't make sense because you can't nest asyncio.run(), nor should you await arbitrary async functions. In order to make asynchronous execution truly asynchronous, you need asyncio.create_task() to start the task, then await asyncio.gather() to collect the results, handle timeout errors, etc. The entire asynchronous program code is actually much different from the synchronous program.
@mishasawangwan6652
@mishasawangwan6652 8 күн бұрын
you can simply wrap the function in `ensure_future` (which would return an awaitable). also check out `.run_in_executor()` method for related functionality.
@QBitDevs
@QBitDevs 18 күн бұрын
Great video, learned a lot
@at0m1x191919
@at0m1x191919 17 күн бұрын
awesome!
@cocoatea57
@cocoatea57 18 күн бұрын
Thanks for this
@obsidiansiriusblackheart
@obsidiansiriusblackheart 13 күн бұрын
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)
@dipeshsamrawat7957
@dipeshsamrawat7957 17 күн бұрын
Thank you.
@ranjithkumars2398
@ranjithkumars2398 18 күн бұрын
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
@aguy9836
@aguy9836 18 күн бұрын
nice
@anon_y_mousse
@anon_y_mousse 15 күн бұрын
And here I was thinking a decorator in Python was a feather boa. ;)
@danbromberg
@danbromberg 17 күн бұрын
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.
@dereknirenbergmusic
@dereknirenbergmusic 6 күн бұрын
The important thing is the first function, in this video "get_time." Notice that instead of taking variables as an input it takes a function. Adding @get_time as a decorator to "calculate" basically says "send this function through the 'get_time' function." Notice that in the "get_time" function, line 12 of code is what actually runs the "calculate" function. So the decorator is telling Python to send the function it's decorating through the decorator function.
@rishiraj2548
@rishiraj2548 18 күн бұрын
Good day greetings
@celestialowl8865
@celestialowl8865 18 күн бұрын
Lambda and nested lambda decorators are novel but neat
@DrDeuteron
@DrDeuteron 18 күн бұрын
the point of a decorator is reuse code...and lambdas don't do that.
@celestialowl8865
@celestialowl8865 18 күн бұрын
@@DrDeuteron Lambda decorators enable IIFEs in python, but as stated the application is less generally applicable and more just a good tool to have in your toolkit. I use it for debugging on occasion
@ApprendreSansNecessite
@ApprendreSansNecessite 17 күн бұрын
@@celestialowl8865 lambdas have nothing to do with IIFE. You can define an IIFE with a named decorator. And it's not an IIFE anyway because it's not an expression
@celestialowl8865
@celestialowl8865 17 күн бұрын
@@ApprendreSansNecessite I should have specified that they allow for a cleaner standard format*. Obviously anything performed by a lambda can be directly reproduced by a named decorator.
@ApprendreSansNecessite
@ApprendreSansNecessite 17 күн бұрын
​@@celestialowl8865 I totally understand your hype for lambdas but they are half-backed. Most of the use cases I have for them in other languages can't be expressed in (typed) Python
@TristanM971
@TristanM971 11 күн бұрын
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.
@QBitDevs
@QBitDevs 18 күн бұрын
First!
@duWud
@duWud 17 күн бұрын
what code editor are you using?
@milara69
@milara69 15 күн бұрын
pycharm
@ApprendreSansNecessite
@ApprendreSansNecessite 17 күн бұрын
If you do this you totally loose the type signature of your function. It becomes `(...) -> Any`
@harikrishnanb7273
@harikrishnanb7273 5 күн бұрын
is there any better way?
@ApprendreSansNecessite
@ApprendreSansNecessite 5 күн бұрын
Yes, the pinned comment
@kundan.072
@kundan.072 17 күн бұрын
May someone tell me that which app is this?
@tinkuabraham9653
@tinkuabraham9653 18 күн бұрын
which IDE is this?
@throstlewanion
@throstlewanion 18 күн бұрын
Pycharm
@DrDeuteron
@DrDeuteron 18 күн бұрын
I read a decorator is a macro, but it's written in python.
@ApprendreSansNecessite
@ApprendreSansNecessite 17 күн бұрын
It is not a macro, it is a higher order function. It is equivalent to writing `def _fn(x, y): ...; fn = decorator(__fn)` or `fn = decorator(lamda x, y: ... )`. The difference is that you pay the price of this abstraction every time you call `fn` whereas a macro would be executed either at compile time or during an initial macro expansion phase. When you use higher order functions, functions are data, but when you use macros, *code* is data
@looploop6612
@looploop6612 14 күн бұрын
what if func has a return value ?
How To Remove Duplicates From A List (Python Recipes)
1:50
Python Decorators in 15 Minutes
15:14
Kite
Рет қаралды 432 М.
Summer shower by Secret Vlog
00:17
Secret Vlog
Рет қаралды 8 МЛН
Looks realistic #tiktok
00:22
Анастасия Тарасова
Рет қаралды 106 МЛН
Llegó al techo 😱
00:37
Juan De Dios Pantoja
Рет қаралды 52 МЛН
Who has won ?? 😀 #shortvideo #lizzyisaeva
00:24
Lizzy Isaeva
Рет қаралды 65 МЛН
20 Everyday Tips & Tricks in Python
25:18
Indently
Рет қаралды 18 М.
Please Master These 10 Python Functions…
22:17
Tech With Tim
Рет қаралды 100 М.
5 Awful Python Mistakes To Avoid
22:13
Indently
Рет қаралды 24 М.
researchers find an unfixable bug in EVERY ARM cpu
9:48
Low Level Learning
Рет қаралды 464 М.
5 Really Cool Python Functions
19:58
Indently
Рет қаралды 57 М.
3 Bad Python Habits To Avoid
10:40
Indently
Рет қаралды 49 М.
5 Good Python Habits
17:35
Indently
Рет қаралды 453 М.
C++ Developer Learns Python
9:26
PolyMars
Рет қаралды 2,7 МЛН
It’s time to move on from Agile Software Development (It's not working)
11:07
Functools is one of the MOST USEFUL Python modules
13:37
Carberra
Рет қаралды 32 М.
Summer shower by Secret Vlog
00:17
Secret Vlog
Рет қаралды 8 МЛН