Access A Variable By Name Defined In A Parent Function From A Nested Function
Is there a way to use something like
locals() to access a variable defined in a parent function by name (i.e., as a string)?
Both of these examples give
def f(): x = 1 def g(): print(globals()['x']) g() def f(): x = 1 def g(): print(locals()['x']) g()
Yes it's possible, but you are working against Python, don't do this:
In : import inspect In : def f(): ...: x = 1 ...: def g(): ...: print(inspect.currentframe().f_back.f_locals['x']) ...: g() ...: In : f() 1
Seriously, don't. Write good code, not bad code. For all of us.
- → What are the pluses/minuses of different ways to configure GPIOs on the Beaglebone Black?
- → Django, code inside <script> tag doesn't work in a template
- → React - Django webpack config with dynamic 'output'
- → GAE Python app - Does URL matter for SEO?
- → Put a Rendered Django Template in Json along with some other items
- → session disappears when request is sent from fetch
- → Python Shopify API output formatted datetime string in django template
- → Shopify app: adding a new shipping address via webhook
- → Shopify + Python library: how to create new shipping address
- → shopify python api: how do add new assets to published theme?
- → Access 'HTTP_X_SHOPIFY_SHOP_API_CALL_LIMIT' with Python Shopify Module