Skip to content

Latest commit

 

History

History
122 lines (98 loc) · 8.5 KB

PythonVersionAttributesAndMethods.md

File metadata and controls

122 lines (98 loc) · 8.5 KB

Master Guide: Python Version Comparison of Attributes & Methods (Python 2.7 to 3.13)

Welcome to the Master Guide on Python Attributes and Methods Evolution. This reference provides a comprehensive version-by-version comparison of how object attributes, method dispatch mechanisms, descriptors, dunder hooks, and introspection capabilities evolved across every major Python release from Python 2.7 to Python 3.13.


📌 Table of Contents

  1. High-Level Version Comparison Matrix
  2. Detailed Version-by-Version Changelog
  3. Attribute Lookup Resolution Order Summary

📊 High-Level Version Comparison Matrix

Python Version Major Attribute / Method Feature Key Syntax / Dunder Hook Impact on Object Model
Python 2.7 Unbound Methods (instancemethod) def func(self): in old-style vs new-style Class attribute lookups returned unbound method objects
Python 3.0 Unbound methods removed; Zero-arg super() super().method(), def f(*, kw_only): Class method lookups return plain function objects
Python 3.3 Qualified name attribute __qualname__ func.__qualname__, inspect.signature() Enables accurate nested class/method reflection
Python 3.4 Enumerations & class indexing enum.Enum, __class_getitem__ Introduced standard Enum types and generic class slicing
Python 3.5 Async methods & @ matrix operator async def, __aiter__, __matmul__ Native coroutine methods and matrix arithmetic dunders
Python 3.6 PEP 487 Descriptors & Subclass hooks __set_name__, __init_subclass__ Descriptors automatically capture attribute name
Python 3.7 Module-level __getattr__ & __dir__ def __getattr__(name): at module level Dynamic fallback attribute access for modules (PEP 562)
Python 3.8 Positional-Only parameters in methods def method(a, /, b): Enforces positional parameter passing in APIs
Python 3.9 Dict union operators & Built-in generics d1 | d2, list[str] Dunder __or__ / __ior__ added to dict attributes
Python 3.10 Pattern matching on attributes match obj: case Class(attr=val): Destructuring and attribute pattern matching
Python 3.11 Exception notes attribute __notes__ err.add_note("text") Standardized metadata notes attached to exceptions
Python 3.12 Generic type parameters attribute class Stack[T]:, __type_params__ Runtime reflection of generic type parameters
Python 3.13 Free-threaded GIL-free CPython Lock-free parallel attribute access Atomic multi-threaded attribute read/write operations

🔍 Detailed Version-by-Version Changelog

Python 2.7 Context

  • Unbound Methods: Accessing a method on a class (MyClass.my_method) returned an unbound method object requiring explicit instance passing.
  • Old-Style vs New-Style Classes: Classes not inheriting explicitly from object lacked __slots__, descriptors, and properties.
  • Unordered __dict__: Attribute dictionaries had non-deterministic key ordering.

Python 3.0 Major Overhaul

  • Unbound Methods Removed: MyClass.my_method returns a standard function object (<function ...>).
  • Implicit object Base: All classes automatically inherit from object (New-Style classes everywhere).
  • Zero-Argument super(): super().__init__() syntax introduced, avoiding explicit super(MyClass, self) syntax.
  • Keyword-Only Method Parameters: Methods can declare keyword-only arguments following *.

Python 3.3 Milestone (__qualname__)

  • __qualname__ Attribute: Functions and classes gained the __qualname__ attribute containing the dot-separated path from the module top-level (e.g., Outer.Inner.method).
  • inspect.signature(): Standardized inspect module function for analyzing method parameter signatures.

Python 3.4 & 3.5 (Async Methods & Matrix Operators)

  • __class_getitem__: Introduced class-level indexing for type generics (Generic[T]).
  • async def & await: Asynchronous instance methods introduced.
  • Async Dunders: __aiter__(), __anext__(), __aenter__(), __aexit__() added for asynchronous context managers and iterators.
  • Matrix Multiplication Dunder: __matmul__ and __imatmul__ added for the @ operator.

Python 3.6 Game Changer (PEP 487 __set_name__ & __init_subclass__)

  • PEP 487 __set_name__: Descriptors automatically receive their owner class and assigned attribute name string upon class creation:
    def __set_name__(self, owner, name):
        self.storage_name = f"_{name}"
  • __init_subclass__ Hook: Class hook automatically invoked when a class is subclassed, replacing custom metaclass setup logic for plugin registries.
  • Preserved __dict__ Insertion Order: Attribute dictionary insertion order is guaranteed across all instances.

Python 3.7 Module-Level Reflection (PEP 562)

  • PEP 562 Module __getattr__ and __dir__: Modules can define module-level __getattr__(name) and __dir__() functions to intercept missing attribute access and customize module introspection.

Python 3.8 Positional-Only Method Parameters (/)

  • Positional-Only Parameter Syntax: Methods can enforce positional-only arguments using /:
    def set_coordinates(self, x, y, /, z=0):
        self.x, self.y, self.z = x, y, z

Python 3.9 & 3.10 (Dict Union Operators & Attribute Pattern Matching)

  • __or__ and __ior__ Dunders: Added to dictionaries for union operations (d1 | d2).
  • Structural Pattern Matching on Attributes: match statements evaluate instance attribute values:
    match user:
        case User(role="admin", active=True):
            print("Admin active")

Python 3.11 Exception Notes (__notes__) & Adaptive Interpreter

  • __notes__ Exception Attribute: Exceptions support an add_note() method populating the __notes__ list attribute.
  • Specialized Adaptive Interpreter: CPython bytecode inline caching optimizes instance attribute lookups (LOAD_ATTR) and method calls (CALL_METHOD).

Python 3.12 PEP 695 __type_params__ & @override

  • __type_params__ Attribute: Generic classes and functions created with PEP 695 syntax (class Container[T]:) expose generic parameters via __type_params__.
  • @typing.override Decorator: Explicitly indicates that a method overrides a superclass method.

Python 3.13 Free-Threaded GIL-Free Attribute Lookup

  • Free-Threaded CPython (No-GIL Build): Atomic lock-free attribute lookups enable concurrent multi-threaded attribute modification without Global Interpreter Lock contention.
  • Enhanced REPL Introspection: Interactive shell automatically inspects and displays attributes, docstrings, and signatures.

⚙️ Attribute Lookup Resolution Order Summary

When accessing obj.attr_name in Python 3.x, the interpreter resolves attributes using this 6-step hierarchy:

1. Check if '__getattribute__' is overridden on object's class.
2. Check Class MRO for a Data Descriptor (defines __get__ AND __set__).
3. Check Instance '__dict__' for 'attr_name'.
4. Check Class MRO for a Non-Data Descriptor (defines ONLY __get__).
5. Check Class '__dict__' across MRO for raw attribute/method.
6. Fallback to '__getattr__' if attribute was not found.