typing decorators sucks! here's an easier way (intermediate) anthony explains

  Рет қаралды 11,190

anthonywritescode

anthonywritescode

Күн бұрын

Пікірлер: 60
@philipreinhold1180
@philipreinhold1180 6 ай бұрын
Python is easy, just use the contextmanager decorator to turn the generator into a context manager that is also at the same time a decorator factory! For real though i love this❤
@ArcRCG
@ArcRCG 4 ай бұрын
This is cool, this decorator-context manager equivalence reflects that a decorator what basically is doing is "managing" the "context" of the wrapped function and that a context manager is basically is "decorating" an annonymous IIFE. One really beautiful abstraction.
@sadhlife
@sadhlife 6 ай бұрын
wow that's a hack that I can use a lot more of
@fabiolean
@fabiolean 2 ай бұрын
I had no idea that creating a context manager like that also created a decorator. Blowing my mind, here.
@mrswats
@mrswats 6 ай бұрын
Excuse me, what the hell. This is super useful! Plus, much easier to test! Holy crap, I will try to remember to use this. Was this a planned feature? Or a coincidence by how Python is built? Or added afterwards...?
@anthonywritescode
@anthonywritescode 6 ай бұрын
yeah it got added after contextmanager was introduced
@Finezzato
@Finezzato 6 ай бұрын
@@anthonywritescode so you basically dismissed decorators and then you used decorators
@anthonywritescode
@anthonywritescode 6 ай бұрын
???
@neonwatty
@neonwatty 6 ай бұрын
good god man this is fantastic - thanks!
@FunkyELF
@FunkyELF 6 ай бұрын
Cool, didn't know you could do this. This can only be done when the decorator returns the unmodified output of the given function being called with unmodified input... correct? Clearly these kinds of decorators exist... like ones that register stuff, log stuff, etc... but a lot of decorators are used to modify either input, output, coerce stuff, etc. If this can't help in those cases the beginning of this video is actually a great reference for how to properly type regular decorators.
@NoProblem76
@NoProblem76 2 ай бұрын
There’s also the contextdecorator class that’s worth looking into
@bryanbanda
@bryanbanda 6 ай бұрын
So obvious and straightforward! Love it
@ericwadebrown
@ericwadebrown 6 ай бұрын
This is why I was sad to see verbose typing in Python. Reminds of the same thing that happened in Java. Of course, it's still optional, but still.
@helleye311
@helleye311 6 ай бұрын
I don't even write python that much, randomly saw this vid in recommended. It looks amazing! Even without the fact that you don't need to type anything, it's so much nicer than defining 3 nested functions. Tbh python decorators are the only feature i miss in other languages, but they're so nice.
@spyr0th3dr4g0n
@spyr0th3dr4g0n 6 ай бұрын
That's such a nice and smart simplification, completely decoupling the function typing rather than going generic with it. Can the context manager decorator do something like logging the first parameter while also timing it, or are the parameters/return values completely out of reach?
@float32
@float32 6 ай бұрын
You can get access to anything with the inspect module, but things will start getting slow.
@anthonywritescode
@anthonywritescode 6 ай бұрын
nope. though arguably those are need special handling anyway and I would not recommend personally
@TheTugaMachine
@TheTugaMachine 6 ай бұрын
Damn wish I knew this sooner. However the drawback of not accessing arguments and return values kinda limit the scope of this approach (e.g. custom caching decorator)
@senseikoudai6186
@senseikoudai6186 6 ай бұрын
This is incredible!
@theendlessriver13
@theendlessriver13 6 ай бұрын
How long has it been like that? Holy - soooo much easier. Is there any downside to this? Why would you ever use the "old" way? Imagine not using functools either...
@anthonywritescode
@anthonywritescode 6 ай бұрын
the only downside is no argument hackery signature modification but imo that's a good thing
@KhalilMuhammad
@KhalilMuhammad 6 ай бұрын
Amazing! So all these times I've been creating context managers, I could've also used them as a decorator? 🤯
@trupalcanada
@trupalcanada 6 ай бұрын
This feels like black magic
@insanecbrotha
@insanecbrotha 10 күн бұрын
hm, interesting, but you cannot access the decorated function object or the passed args/kwargs, right? So this is only for side-effect decorations, I think.
@bacon4life
@bacon4life 6 ай бұрын
That's super smart
@zeyadmoustafakamal
@zeyadmoustafakamal 6 ай бұрын
Wait how you made nano like this ?? I would like to look at your dotfiles or something like this as I can't believe that nano can be like this. It's like vim or neovim but it's nicer.
@JohnZakaria
@JohnZakaria 6 ай бұрын
This isn't nano. This is babi. The gigachad here wrote it himself
@anthonywritescode
@anthonywritescode 6 ай бұрын
framing this lol. this is my editor I made github.com/asottile/babi
@zeyadmoustafakamal
@zeyadmoustafakamal 6 ай бұрын
@@anthonywritescode Wow what a crazy one. I will look at it :)
@447xpro
@447xpro 4 ай бұрын
Thanks!
@shunitsu__
@shunitsu__ 6 ай бұрын
Very interesting! Is this possible for concatenate introduced in PEP 612? like the one example in your previous video adding a logger
@anthonywritescode
@anthonywritescode 6 ай бұрын
this sort of intentionally prevents you from doing nasty signature mutation. the concatenate example in the other video was to demonstrate the feature and not really something I would ever do in reality
@Xx00aquaman00xX
@Xx00aquaman00xX 6 ай бұрын
This is cool but what if you want override/pass the args/kwargs of the func or you want to get the name of the func?
@anthonywritescode
@anthonywritescode 6 ай бұрын
you can't, but I see that as a good thing
@MichalPlichta
@MichalPlichta 6 ай бұрын
That's kind if new.... Contex manager working as decorator 🧐.... I need try....
@notmymainaccount477
@notmymainaccount477 6 ай бұрын
2:40 is there a specific reason why you use time.monotonic instead of time.perf_counter, because as far as i can remember you have always used time.monotonic in your videos?
@anthonywritescode
@anthonywritescode 6 ай бұрын
it's an alias on the platforms I care about and good enough on windows
@notmymainaccount477
@notmymainaccount477 6 ай бұрын
@@anthonywritescode ah i see, thanks
@SQADIqw
@SQADIqw 6 ай бұрын
Does it make any sense if you are not into typing?
@anthonywritescode
@anthonywritescode 6 ай бұрын
yes, it is still a simpler way to make decorators
@yorailevi6747
@yorailevi6747 6 ай бұрын
Is there no down sides to this?
@flipbit03
@flipbit03 6 ай бұрын
This is awesome, and makes for a much nicer typing experience. Quick question on the @timing_ctx example: is "try: finally:" really needed in this case, or just a "nice to have" for the sake of completeness? i.e. would the section after the "yield" be skipped on an exception inside the decorated function if we ditch the try/finally? I'm asking this because imho, the decorator "setup/teardown" sections would look even better/simpler/more readable without the extra indentation that the finally: block unfortunately imposes on the "teardown" section of it. Thanks in advance, asottile, you are a legend!
@anthonywritescode
@anthonywritescode 6 ай бұрын
yeah finally is necessary to work in the context of exceptions -- this is also true in the decorator code too (if I skipped it there it's a mistake!)
@murphygreen8484
@murphygreen8484 6 ай бұрын
What is the [None, None, None] typing for on the generator?
@philipreinhold1180
@philipreinhold1180 6 ай бұрын
Generator has a yield type (the type in the yield), send type (usually only required for coroutines) and return type (the final returned value after the generator is exhausted)
@murphygreen8484
@murphygreen8484 6 ай бұрын
@@philipreinhold1180 thank you!
@anthonywritescode
@anthonywritescode 6 ай бұрын
kzbin.info/www/bejne/eoXImJl5g6aLpa8 for my video on the subject
@1rbroderi
@1rbroderi 6 ай бұрын
Anyway to generalize this to create a decorator that decorates another decorator?
@anthonywritescode
@anthonywritescode 6 ай бұрын
I mean, it should work
@wexwexexort
@wexwexexort 6 ай бұрын
I just wondered if you use an IDE at work
@anthonywritescode
@anthonywritescode 6 ай бұрын
why wouldn't I use my own text editor?
@thagreatone402
@thagreatone402 6 ай бұрын
Blasphemy
@float32
@float32 6 ай бұрын
Am I noticing correctly that the context manager method has 1000x overhead? 2ms vs the 0.002ms of the decorator!?
@hemerythrin
@hemerythrin 6 ай бұрын
It's 1.7us for the decorator and 1.9us for the context manager. The 200ms one is after he added the with block containing a sleep.
@anthonywritescode
@anthonywritescode 6 ай бұрын
I intentionally added a sleep so the timing output was interesting
@float32
@float32 6 ай бұрын
Ahh, I was just looking at the time beyond the sleep (like 0.207 at 6:19). Maybe it’s a sleep resolution thing.
@anthonywritescode
@anthonywritescode 6 ай бұрын
ah probably just python show plus vm plus recording
@wagneralberto5456
@wagneralberto5456 6 ай бұрын
first!
@NeatMemesDotCom
@NeatMemesDotCom 6 ай бұрын
At this you should probably go writing rust code. Easier than all this
@anthonywritescode
@anthonywritescode 6 ай бұрын
toxic
typing the untype-able with mypy plugins (advanced) anthony explains #574
25:06
Увеличили моцареллу для @Lorenzo.bagnati
00:48
Кушать Хочу
Рет қаралды 8 МЛН
ТВОИ РОДИТЕЛИ И ЧЕЛОВЕК ПАУК 😂#shorts
00:59
BATEK_OFFICIAL
Рет қаралды 6 МЛН
А я думаю что за звук такой знакомый? 😂😂😂
00:15
Денис Кукояка
Рет қаралды 3,9 МЛН
Как Я Брата ОБМАНУЛ (смешное видео, прикол, юмор, поржать)
00:59
Натурал Альбертович
Рет қаралды 3,9 МЛН
5 Useful Python Decorators (ft. Carberra)
14:34
Indently
Рет қаралды 106 М.
FASTEST way to clone a FULL frontend (CopyCoder + Cursor Tutorial)
10:38
This Algorithm is 1,606,240% FASTER
13:31
ThePrimeagen
Рет қаралды 852 М.
adding test == others fail??? (intermediate) anthony explains #572
10:40
anthonywritescode
Рет қаралды 4,3 М.
Harder Than It Seems? 5 Minute Timer in C++
20:10
The Cherno
Рет қаралды 216 М.
Увеличили моцареллу для @Lorenzo.bagnati
00:48
Кушать Хочу
Рет қаралды 8 МЛН