python Python PEPs ·

PEP 837: Clarifying Name Resolution in Python Class Namespaces

engineer
announcement

This draft PEP proposes to address long-standing inconsistencies in how variable names are resolved within Python class namespaces. The current behavior is described as partially dynamic and differs between top-level and nested class definitions, potentially leading to surprising outcomes. The proposal aims to simplify and unify name resolution, making it more predictable for developers, though it may introduce breaking changes for code relying on the existing, albeit inconsistent, behavior.

  • PEP 837 addresses class namespace name resolution inconsistencies
  • Current name resolution in classes is complex and sometimes surprising
  • Proposal to unify class namespace resolution with function scopes
  • Ambiguity in free variable resolution is a key challenge
Notes (4)
  • PEP 837 addresses class namespace name resolution inconsistencies

    This draft PEP, 'Name Resolution in Class Namespaces', authored by Jeremy Hylton, outlines the inconsistent behavior in how Python resolves variable names within class definitions. It notes that names can be resolved both locally and globally depending on assignments during execution, and behavior differs based on whether the class is top-level or nested.

  • Current name resolution in classes is complex and sometimes surprising

    The document illustrates how free variables in classes are resolved to enclosing scopes, but local variables used before assignment are looked up in the global scope. This behavior, established through various PEPs and opcode changes over Python versions, is not consistently reflected in the language specification and has been noted as a 'wart' in prior discussions.

  • Proposal to unify class namespace resolution with function scopes

    Several alternatives are discussed for unifying name resolution. One approach suggests treating class namespaces more like function namespaces, where unbound local variables raise a NameError, a change that would break existing code relying on the current behavior. Other options explore resolving unbound locals in enclosing scopes or strictly in the global namespace.

  • Ambiguity in free variable resolution is a key challenge

    A core challenge lies in determining how to resolve unbound local variables when they shadow names in enclosing scopes. The PEP questions why only the global namespace should be consulted if a name is bound elsewhere, proposing a more comprehensive resolution process, though acknowledging the implementation complexity.

Read the original announcement →

https://peps.python.org/pep-0837/

Related releases