Evaluation of variable as f-string

Chris Angelico rosuav at gmail.com
Tue Feb 7 12:46:52 EST 2023


On Wed, 8 Feb 2023 at 02:12, Rob Cliffe <rob.cliffe at btinternet.com> wrote:
>
> [re-sending this to both the list and to Chris, as a prior send to the
> list only was bounced back]
> On 31/01/2023 22:33, Chris Angelico wrote:
> >
> >> Thanks for clarifying.
> >> Hm.  So 'x' is neither in locals() nor in globals().  Which starts me
> >> wondering (to go off on a tangent): Should there be a nonlocals()
> >> dictionary?
> > I don't think so, but there might be some value in a dictionary
> > containing all available variables. It would have the same "don't
> > depend on writing" caveats that locals() has (or would be specifically
> > defined as a copy and thus disconnected), so its value would be
> > limited. And it would probably STILL be imperfect, because perfection
> > would require that it be a compiler construct, due to the way that
> > nonlocals are implemented.
> Does that mean that it is not possible to have a (built-in) function
> that would construct and return a dictionary of all available variables
> and their values?  If it were possible, it could be useful, and there
> would be no impact on Python run-time speed if it were only constructed
> on demand.
>

It can't be a built-in function and also be 100% reliable; and if it's
a special compiler construct, its presence in your code would have
semantic impact on all nested functions - even if you never call it:

def func():
    x = Obj()
    def inner():
        if False: get_vars
    return inner

x can no longer be disposed of, just in case you call inner and get the vars.

And quite frankly, I don't think this functionality justifies a magic
compiler construct and consequent keyword. But a builtin won't be
reliable.

ChrisA


More information about the Python-list mailing list