Тёмный

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

anthonywritescode
Подписаться 40 тыс.
Просмотров 10 тыс.
50% 1

ParamSpec / TypeVar / Callable oh my! this skips all of that and gives a simple easy-to-reuse decorator (and more!)
- how @ contextmanager works: • how @contextmanager wo...
- contextmanagers the easy way: • with + context manager...
playlist: • anthony explains
==========
twitch: / anthonywritescode
dicsord: / discord
twitter: / codewithanthony
github: github.com/asottile
stream github: github.com/anthonywritescode
I won't ask for subscriptions / likes / comments in videos but it really helps the channel. If you have any suggestions or things you'd like to see please comment below!

Наука

Опубликовано:

 

14 май 2024

Поделиться:

Ссылка:

Скачать:

Готовим ссылку...

Добавить в:

Мой плейлист
Посмотреть позже
Комментарии : 57   
@ArcRCG
@ArcRCG Месяц назад
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.
@philipreinhold1180
@philipreinhold1180 2 месяца назад
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❤
@sadhlife
@sadhlife 3 месяца назад
wow that's a hack that I can use a lot more of
@mrswats
@mrswats 3 месяца назад
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 3 месяца назад
yeah it got added after contextmanager was introduced
@Finezzato
@Finezzato 2 месяца назад
@@anthonywritescode so you basically dismissed decorators and then you used decorators
@anthonywritescode
@anthonywritescode 2 месяца назад
???
@FunkyELF
@FunkyELF 2 месяца назад
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.
@neonwatty
@neonwatty 3 месяца назад
good god man this is fantastic - thanks!
@bryanbanda
@bryanbanda 3 месяца назад
So obvious and straightforward! Love it
@helleye311
@helleye311 2 месяца назад
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 3 месяца назад
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 3 месяца назад
You can get access to anything with the inspect module, but things will start getting slow.
@anthonywritescode
@anthonywritescode 3 месяца назад
nope. though arguably those are need special handling anyway and I would not recommend personally
@TheTugaMachine
@TheTugaMachine 3 месяца назад
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)
@theendlessriver13
@theendlessriver13 3 месяца назад
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 3 месяца назад
the only downside is no argument hackery signature modification but imo that's a good thing
@ericwadebrown
@ericwadebrown 2 месяца назад
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.
@senseikoudai6186
@senseikoudai6186 3 месяца назад
This is incredible!
@notmymainaccount477
@notmymainaccount477 3 месяца назад
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 3 месяца назад
it's an alias on the platforms I care about and good enough on windows
@notmymainaccount477
@notmymainaccount477 3 месяца назад
@@anthonywritescode ah i see, thanks
@littlepharaoh455
@littlepharaoh455 3 месяца назад
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 3 месяца назад
This isn't nano. This is babi. The gigachad here wrote it himself
@anthonywritescode
@anthonywritescode 3 месяца назад
framing this lol. this is my editor I made github.com/asottile/babi
@littlepharaoh455
@littlepharaoh455 3 месяца назад
@@anthonywritescode Wow what a crazy one. I will look at it :)
@Xx00aquaman00xX
@Xx00aquaman00xX 3 месяца назад
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 2 месяца назад
you can't, but I see that as a good thing
@447xpro
@447xpro 28 дней назад
Thanks!
@KhalilMuhammad
@KhalilMuhammad 2 месяца назад
Amazing! So all these times I've been creating context managers, I could've also used them as a decorator? 🤯
@trupalcanada
@trupalcanada 2 месяца назад
This feels like black magic
@shunitsu__
@shunitsu__ 2 месяца назад
Very interesting! Is this possible for concatenate introduced in PEP 612? like the one example in your previous video adding a logger
@anthonywritescode
@anthonywritescode 2 месяца назад
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
@flipbit03
@flipbit03 2 месяца назад
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 2 месяца назад
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!)
@bacon4life
@bacon4life 3 месяца назад
That's super smart
@yorailevi6747
@yorailevi6747 2 месяца назад
Is there no down sides to this?
@SQADIqw
@SQADIqw 2 месяца назад
Does it make any sense if you are not into typing?
@anthonywritescode
@anthonywritescode 2 месяца назад
yes, it is still a simpler way to make decorators
@MichalPlichta
@MichalPlichta 3 месяца назад
That's kind if new.... Contex manager working as decorator 🧐.... I need try....
@1rbroderi
@1rbroderi 3 месяца назад
Anyway to generalize this to create a decorator that decorates another decorator?
@anthonywritescode
@anthonywritescode 3 месяца назад
I mean, it should work
@murphygreen8484
@murphygreen8484 2 месяца назад
What is the [None, None, None] typing for on the generator?
@philipreinhold1180
@philipreinhold1180 2 месяца назад
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 2 месяца назад
@@philipreinhold1180 thank you!
@anthonywritescode
@anthonywritescode 2 месяца назад
ru-vid.com/video/%D0%B2%D0%B8%D0%B4%D0%B5%D0%BE-DTegfCNAXoM.html for my video on the subject
@wexwexexort
@wexwexexort 2 месяца назад
I just wondered if you use an IDE at work
@anthonywritescode
@anthonywritescode 2 месяца назад
why wouldn't I use my own text editor?
@float32
@float32 3 месяца назад
Am I noticing correctly that the context manager method has 1000x overhead? 2ms vs the 0.002ms of the decorator!?
@hemerythrin
@hemerythrin 3 месяца назад
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 3 месяца назад
I intentionally added a sleep so the timing output was interesting
@float32
@float32 3 месяца назад
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 3 месяца назад
ah probably just python show plus vm plus recording
@thagreatone402
@thagreatone402 3 месяца назад
Blasphemy
@wagneralberto5456
@wagneralberto5456 3 месяца назад
first!
@NeatMemesDotCom
@NeatMemesDotCom 3 месяца назад
At this you should probably go writing rust code. Easier than all this
@anthonywritescode
@anthonywritescode 3 месяца назад
toxic
Далее
БАТЯ В ДЕПРЕССИИ
00:52
Просмотров 688 тыс.
Хитрость старого мастера #diy
00:54
Why You Shouldn't Nest Your Code
8:30
Просмотров 2,7 млн
Naming Things in Code
7:25
Просмотров 2,1 млн
python descriptors! (advanced) anthony explains #519
19:04
5 Design Patterns That Are ACTUALLY Used By Developers
9:27
Мой новый мега монитор!🤯
1:00
Samsung vs iPhone ☠️ #shorts
0:18
Просмотров 13 млн
БОЛЬШЕ ВИДЕОКАРТ - БОЛЬШЕ FPS??
1:00