Capturing a function's LOCAL variables?!

preview_player
Показать описание
Trust me, this does actually have a use case! You would ordinarily not be able to access the local variables of a function unless you returned them, but this function captures the internal state of the decorated function at return time, allowing you to verify it's what it should be! Very neat, but definitely a hack!

00:00 - Intro [1]
01:06 - Demonstration [2]
03:13 - Implementing the capture function [3]
10:02 - Strongly typed example
10:45 - Where would you use this?
14:22 - Outro



If you want to see more of me, join my Discord server!

I get a lot of people asking, so here's my setup!

Affiliations (I may earn a commission):



If you have any questions, don't hesitate to ask in the comments! I'll try and answer as soon as I can, providing someone else hasn't already done so.

#python #coding #howto
Рекомендации по теме
Комментарии
Автор

@Carberra I don't expect I'll ever use this just this way, but I'm very glad to have seen you walk through it. Seeing how to use a simply written profiler to react to events and access frames is a very interesting capability I'm not at all sure I would have come across otherwise :) It definitely sheds some light on how profilers and debuggers must work under the hood. Thanks for doing this! :)

stevecanny
Автор

The reason f_locals needs to be nonlocal is because the variable *name* is being assigned to. You can always access variables from the enclosing scope, but you cannot assign a new value to that name. You can, however, mutate variables without marking them nonlocal; if instead, you mutated that f_locals dict by using f_locals.update you could have omitted the nonlocal tag

austinnar
Автор

@Carberra I thought you gonna show:
def summm(a: int, b: int) -> int:
summm.a = a
summm.x = b
summm.y = 4
return a + b
print(summm.y) >>> 4

which seems to me a lot easier

kamenenator
Автор

Woahhh didnt no about this, thank you for sharing 😮😮

කැලණිකුප්පි
Автор

Mmmmh, about the body of the sieve function, how does the variable numbers exist in the first place fit is never been initiated as a list? Can you access items of an existing obj without the need of a __iter__ dunder method or even the __item__ dunder method?

giorgioripani
Автор

1:14 Not even close! :))

error-TOSSED-hen-ease

Stressed syllable in caps. Not phenetics, pronounce as English words.

davidmurphy
Автор

If you ever need something like this, you must be doing something wrong in your code and it's time to rethink the problem

Cojua
Автор

Wow this is really useful for testing closure functions! Thanks for the video!

greob
Автор

looks like a "hack", feels like a "hack", it's a "hack" :P naaaa, I'll skip this 🤪

brunorodriguesmaso
Автор

Aggh!
You try to speak everything in one breath and start the sentence louder and become so quiter in the end !!!
so

khanra
welcome to shbcf.ru