python Python PEPs ·

PEP 840: Standardizing Name Resolution in Python Class Namespaces

engineer
announcement

PEP 840 proposes to standardize name resolution within Python class namespaces, addressing long-standing inconsistencies. The proposal aims to simplify how variable names are resolved, potentially impacting developers who rely on current, nuanced behaviors when defining classes within functions or nested scopes. A primary goal is to make class namespace behavior more consistent with general function scope rules by raising NameErrors for unbound local variables, even when a global or enclosing scope variable exists.

  • Proposal to standardize class namespace name resolution
  • Examining current name resolution behavior with examples
  • Historical context of class namespace scoping
  • Proposed alternatives for consistent name resolution
  • Potential breaking changes and implementation considerations
Notes (5)
  • Proposal to standardize class namespace name resolution

    PEP 840 discusses inconsistencies in Python's name resolution within class namespaces and proposes solutions to make it more predictable. The current behavior can differ based on whether a class is defined at the top-level or within another scope, and how unbound local variables are handled.

  • Examining current name resolution behavior with examples

    The PEP illustrates complex scenarios where variable resolution in classes may not align with intuitive expectations, especially when dealing with global variables, function parameters, and variables defined within the class body before or after their use.

  • Historical context of class namespace scoping

    Since Python 2.0, class namespaces have had unique scoping rules, with a notable bug filed in 2002 that highlighted these 'warts.' Subsequent Python versions introduced lexical scoping and changes to free variable resolution, but class namespaces retained some distinct behaviors, leading to ongoing discussions and bug reports.

  • Proposed alternatives for consistent name resolution

    Several alternatives are presented, including making class namespaces strictly follow function scope rules (raising NameError for unbound locals), using global namespaces for unbound names, or using enclosing scope bindings when available. The most consistent approach aims to use standard name resolution rules.

  • Potential breaking changes and implementation considerations

    One proposed approach of making class namespaces work like function namespaces could break existing code that relies on the current, inconsistent behavior. Statically determining binding behavior for variables shadowed in enclosing scopes is noted as an implementation complexity.

Read the original announcement →

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

Related releases