Skip to content

Creating Variables using frame.f_locals #138029

@kliu04

Description

@kliu04

Bug report

Bug description:

PEP 667 states: "frame.f_locals gives read/write access to the local variables in all scopes, including optimized scopes" and "the view object [...] implement the following mutable mapping operations:

  • using assignment to add new key/value pairs
  • using assignment to update the value associated with a key

All writes to the f_locals mapping will be immediately visible in the underlying variables."

However, creating a variable in an optimized scope causes a crash:

import inspect

def foo():
    frame = inspect.currentframe()
    frame.f_locals["x"] = 1
    print(x)


foo()

yields NameError: name 'x' is not defined

Creating a variable outside of an optimized scope is fine:

import inspect

frame = inspect.currentframe()
frame.f_locals["x"] = 1
print(x)

yields 1.

CPython versions tested on:

3.13

Operating systems tested on:

macOS

Metadata

Metadata

Assignees

No one assigned

    Labels

    interpreter-core(Objects, Python, Grammar, and Parser dirs)pendingThe issue will be closed if no feedback is provided

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions