Skip to content

Make builtins.locals() and FrameType.f_locals return mappings, not dicts - #17048

Open
dongheun89 wants to merge 1 commit into
python:mainfrom
dongheun89:fix/locals-f-locals-mapping
Open

dongheun89 wants to merge 1 commit into
python:mainfrom
dongheun89:fix/locals-f-locals-mapping

Conversation

@dongheun89

Copy link
Copy Markdown

Fixes #14584.

builtins.locals() is documented as returning "a mapping object", and at class scope
it returns "the namespace that will be passed to the metaclass constructor" — that is,
whatever the metaclass's __prepare__ returned, which need not be a dict:

from collections import UserDict

class A(type):
    @classmethod
    def __prepare__(cls, name, bases):
        return UserDict()

class B(metaclass=A):
    print(type(locals()))  # <class 'collections.UserDict'>, not <class 'dict'>

This works the same way on every supported version (checked with 3.12.16, 3.13.5 and
3.14.0b4). types.FrameType.f_locals has the same problem, and since Python 3.13
(PEP 667) it is also not a dict for optimized scopes, where it returns the
write-through proxy:

from inspect import currentframe

def f():
    print(type(currentframe().f_locals))  # <class 'FrameLocalsProxy'>

That proxy is only exposed as the public types.FrameLocalsProxyType in Python 3.15,
which is why the stub could only be made accurate for 3.15+ so far.

Changes:

  • builtins.locals() now returns MutableMapping[str, Any] instead of dict[str, Any].
  • types.FrameType.f_locals now returns MutableMapping[str, Any] before Python 3.15.
    (3.15+ is unchanged: FrameLocalsProxyType | dict[str, Any].)

Why MutableMapping and not Mapping:

  • writes through the returned object are part of the documented contract outside of
    optimized scopes ("Changes made through the mapping object returned from locals()
    will be visible as assigned, re-assigned, or deleted local variables"), and every
    object these functions can return is mutable at runtime: a dict (module and
    function scopes), the class namespace mapping (anything __prepare__ returns, which
    must support item assignment), or the PEP 667 proxy, which implements __setitem__,
    pop, setdefault and update.
  • it is the type that type.__prepare__(...) already returns in these stubs
    (MutableMapping[str, object]), and a class body's locals() is exactly that object.

Alternatives considered:

  • A structural Protocol (the issue notes that Mapping/MutableMapping are nominal
    types). Rejected for now: every namespace a class body can actually be given is a
    MutableMapping in practice (dict, UserDict, the PEP 667 proxy), and a protocol
    would force users to name a _typeshed-private type in their own annotations.
  • Mapping[str, Any]: would reject documented, working mutation at module and class
    scope.

Compatibility notes for reviewers: this narrows both types from dict, so code that
assigns the result to a dict-annotated variable, or calls dict-only methods such as
.copy(), now needs an explicit dict(...). The common idioms keep type-checking:
**locals(), dict(locals()), "%(x)s" % locals(), "{x}".format_map(locals()),
keys()/get()/in, and f_locals["x"] = 1 / pop() / update().

Tests: stdlib/@tests/test_cases/builtins/check_locals.py is new, and a
types.FrameType.f_locals case was added to stdlib/@tests/test_cases/check_types.py.

Known limitation (pre-existing, follow-up material): types.FrameLocalsProxyType is
declared as a MutableMapping, but the runtime proxy only implements part of the
mutable API — it has no clear() or popitem(), and _collections_abc registers it
with Mapping only (see framelocalsproxy_methods in CPython's
Objects/frameobject.c). This PR does not change that; the 3.13/3.14 annotation above
is an approximation for the same reason.

…t dicts

At class scope, `locals()` returns the mapping returned by the metaclass's
`__prepare__`, which need not be a dict (see python#14584). Since Python 3.13
(PEP 667), `FrameType.f_locals` returns the write-through
`FrameLocalsProxy` in optimized scopes, which is also not a dict and is
only exposed as `types.FrameLocalsProxyType` in Python 3.15.
@github-actions

github-actions Bot commented Dec 6, 2026

Copy link
Copy Markdown
Contributor

Diff from mypy_primer, showing the effect of this PR on open source code:

spark (https://github.com/apache/spark)
+ python/pyspark/pandas/generic.py:1105: error: Argument 4 to "validate_arguments_and_invoke_function" has incompatible type "MutableMapping[str, Any]"; expected "dict[Any, Any]"  [arg-type]
+ python/pyspark/pandas/generic.py:1223: error: Argument 4 to "validate_arguments_and_invoke_function" has incompatible type "MutableMapping[str, Any]"; expected "dict[Any, Any]"  [arg-type]
+ python/pyspark/pandas/generic.py:3317: error: Argument 4 to "validate_arguments_and_invoke_function" has incompatible type "MutableMapping[str, Any]"; expected "dict[Any, Any]"  [arg-type]
+ python/pyspark/pandas/frame.py:2229: error: Argument 4 to "validate_arguments_and_invoke_function" has incompatible type "MutableMapping[str, Any]"; expected "dict[Any, Any]"  [arg-type]
+ python/pyspark/pandas/frame.py:2351: error: Argument 4 to "validate_arguments_and_invoke_function" has incompatible type "MutableMapping[str, Any]"; expected "dict[Any, Any]"  [arg-type]
+ python/pyspark/pandas/frame.py:2468: error: Argument 4 to "validate_arguments_and_invoke_function" has incompatible type "MutableMapping[str, Any]"; expected "dict[Any, Any]"  [arg-type]
+ python/pyspark/pandas/frame.py:2564: error: Argument 4 to "validate_arguments_and_invoke_function" has incompatible type "MutableMapping[str, Any]"; expected "dict[Any, Any]"  [arg-type]
+ python/pyspark/pandas/frame.py:2684: error: Argument 4 to "validate_arguments_and_invoke_function" has incompatible type "MutableMapping[str, Any]"; expected "dict[Any, Any]"  [arg-type]
+ python/pyspark/pandas/frame.py:2732: error: Argument 4 to "validate_arguments_and_invoke_function" has incompatible type "MutableMapping[str, Any]"; expected "dict[Any, Any]"  [arg-type]
+ python/pyspark/pandas/frame.py:2814: error: Argument 4 to "validate_arguments_and_invoke_function" has incompatible type "MutableMapping[str, Any]"; expected "dict[Any, Any]"  [arg-type]
+ python/pyspark/pandas/frame.py:6067: error: Argument 4 to "validate_arguments_and_invoke_function" has incompatible type "MutableMapping[str, Any]"; expected "dict[Any, Any]"  [arg-type]
+ python/pyspark/pandas/series.py:1664: error: Argument 4 to "validate_arguments_and_invoke_function" has incompatible type "MutableMapping[str, Any]"; expected "dict[Any, Any]"  [arg-type]
+ python/pyspark/pandas/series.py:1673: error: Argument 4 to "validate_arguments_and_invoke_function" has incompatible type "MutableMapping[str, Any]"; expected "dict[Any, Any]"  [arg-type]
+ python/pyspark/pandas/series.py:1717: error: Argument 4 to "validate_arguments_and_invoke_function" has incompatible type "MutableMapping[str, Any]"; expected "dict[Any, Any]"  [arg-type]
+ python/pyspark/pandas/series.py:1746: error: Argument 4 to "validate_arguments_and_invoke_function" has incompatible type "MutableMapping[str, Any]"; expected "dict[Any, Any]"  [arg-type]
+ python/pyspark/pandas/sql_processor.py:208: error: Incompatible return value type (got "MutableMapping[str, Any]", expected "dict[str, Any]")  [return-value]

hydra-zen (https://github.com/mit-ll-responsible-ai/hydra-zen)
+ src/hydra_zen/structured_configs/_make_config.py:275: error: "MutableMapping[str, Any]" has no attribute "copy"  [attr-defined]

zulip (https://github.com/zulip/zulip)
+ zerver/views/streams.py:742: error: Argument 4 to "access_requested_group_permissions_for_streams" has incompatible type "MutableMapping[str, Any]"; expected "dict[str, Any]"  [arg-type]
+ zerver/views/streams.py:909: error: Argument "request_settings_dict" to "list_to_streams" has incompatible type "MutableMapping[str, Any]"; expected "dict[str, Any] | None"  [arg-type]

trio (https://github.com/python-trio/trio)
+ src/trio/__main__.py:3: error: Argument 1 to "main" has incompatible type "MutableMapping[str, Any]"; expected "dict[str, object]"  [arg-type]

pywin32 (https://github.com/mhammond/pywin32)
+ win32/Lib/win32timezone.py:1005:12: error: Incompatible return value type (got "MutableMapping[str, Any]", expected "dict[str, bool]")  [return-value]

discord.py (https://github.com/Rapptz/discord.py)
+ discord/ext/commands/flags.py:331: error: Need type annotation for "local_ns" (hint: "local_ns: dict[<type>, <type>] = ...")  [var-annotated]
+ discord/ext/commands/flags.py:334: error: Incompatible types in assignment (expression has type "MutableMapping[str, Any]", variable has type "dict[Any, Any]")  [assignment]
+ discord/ext/commands/flags.py:336: error: Incompatible types in assignment (expression has type "MutableMapping[str, Any]", variable has type "dict[Any, Any]")  [assignment]

sympy (https://github.com/sympy/sympy)
+ sympy/utilities/matchpy_connector.py:274: error: Argument 2 to "eval" has incompatible type "MutableMapping[str, Any]"; expected "dict[str, Any] | None"  [arg-type]

pandas (https://github.com/pandas-dev/pandas)
+ pandas/core/computation/scope.py:180: error: Item "MutableMapping[str, Any]" of "Any | MutableMapping[str, Any]" has no attribute "copy"  [union-attr]
+ pandas/io/parsers/readers.py:1956: error: "MutableMapping[str, Any]" has no attribute "copy"  [attr-defined]
+ pandas/io/parsers/readers.py:2567: error: "MutableMapping[str, Any]" has no attribute "copy"  [attr-defined]

pytensor (https://github.com/pymc-devs/pytensor)
+ pytensor/link/utils.py:924: error: Incompatible types in assignment (expression has type "MutableMapping[str, Any]", variable has type "dict[Any, Any] | None")  [assignment]

xarray (https://github.com/pydata/xarray)
+ xarray/plot/dataset_plot.py: note: In function "_dsplot":
+ xarray/plot/dataset_plot.py:236: error: "MutableMapping[str, Any]" has no attribute "copy"  [attr-defined]
+ xarray/plot/dataset_plot.py: note: At top level:
+ xarray/plot/dataset_plot.py: note: In function "scatter":
+ xarray/plot/dataset_plot.py:917: error: Argument 3 to "_temp_dataarray" has incompatible type "MutableMapping[str, Any]"; expected "dict[str, Any]"  [arg-type]
+ xarray/plot/dataset_plot.py: note: In function "lines":
+ xarray/plot/dataset_plot.py:1089: error: Argument 3 to "_temp_dataarray" has incompatible type "MutableMapping[str, Any]"; expected "dict[str, Any]"  [arg-type]
+ xarray/plot/dataarray_plot.py: note: In function "line":
+ xarray/plot/dataarray_plot.py:506: error: "MutableMapping[str, Any]" has no attribute "copy"  [attr-defined]
+ xarray/plot/dataarray_plot.py: note: At top level:
+ xarray/plot/dataarray_plot.py: note: In function "_plot1d":
+ xarray/plot/dataarray_plot.py:938: error: "MutableMapping[str, Any]" has no attribute "copy"  [attr-defined]
+ xarray/plot/dataarray_plot.py: note: In function "_plot2d":
+ xarray/plot/dataarray_plot.py:1698: error: "MutableMapping[str, Any]" has no attribute "copy"  [attr-defined]

setuptools (https://github.com/pypa/setuptools)
+ setuptools/build_meta.py:317: error: Argument 2 to "exec" has incompatible type "MutableMapping[str, Any]"; expected "dict[str, Any] | None"  [arg-type]

pytest (https://github.com/pytest-dev/pytest)
+ src/_pytest/_code/code.py:153: error: Incompatible return value type (got "MutableMapping[str, Any]", expected "dict[str, Any]")  [return-value]

dd-trace-py (https://github.com/DataDog/dd-trace-py)
+ ddtrace/appsec/_iast/_taint_tracking/_debug.py:33: error: Incompatible types in assignment (expression has type "MutableMapping[str, Any]", variable has type "dict[str, object]")  [assignment]
+ ddtrace/appsec/_common_module_patches.py:144: error: Incompatible return value type (got "MutableMapping[str, Any]", expected "dict[str, Any]")  [return-value]

werkzeug (https://github.com/pallets/werkzeug)
+ src/werkzeug/debug/repr.py:49: error: Argument 1 to "dump_locals" of "DebugReprGenerator" has incompatible type "MutableMapping[str, Any]"; expected "dict[str, Any]"  [arg-type]

egglog-python (https://github.com/egraphs-good/egglog-python)
+ python/egglog/egraph.py:348: error: Argument 1 to "_FunctionConstructor" has incompatible type "MutableMapping[str, Any] | Any"; expected "dict[str, Any]"  [arg-type]
+ python/egglog/egraph.py:350: error: Argument 1 to "_FunctionConstructor" has incompatible type "MutableMapping[str, Any] | Any"; expected "dict[str, Any]"  [arg-type]
+ python/egglog/egraph.py:564: error: Argument 5 to "_fn_decl" has incompatible type "MutableMapping[str, Any]"; expected "dict[str, Any]"  [arg-type]

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

The types of builtins.locals and types.FrameType.f_locals aren't correct

1 participant