'How to access non locals variables (lazy format)?
I am trying to do something like this (Python 3.8.x!):
import inspect
class LazyFStr(str):
_template = ''
def __init__(self, s):
self._template = s
def __repr__(self):
vs = inspect.getclosurevars(lambda: True) #self.__repr__)
print(vs)
return self._template.format(**vs.nonlocals)
and when I call it in the REPL snippet like:
>>> x = 123
>>> s = LazyFStr('aaa {x} bbb')
>>> s
I get:
ClosureVars(nonlocals={}, globals={}, builtins={}, unbound=set())
...
KeyError: 'x'
which means that I cannot access the variable x. How to achieve this?
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
