Deprecations and Lazy Values at Module Level: Python's __getattr__ and __dir__

This article explains how the module-level __getattr__ and __dir__ functions of PEP 562 let a Python module deprecate renamed attributes and load expensive values on demand, and why global lookups, stacklevel and hasattr make them delicate.

A green tree python with white spots lowering its head from its coils toward a blurred green background
Photo by Peter Neumann on Unsplash

A module exposes its names through its dictionary, so an attribute that does not exist there raises AttributeError with no opportunity to intervene. The present article addresses the module-level functions __getattr__ and __dir__, introduced in Python 3.7 by PEP 562, which let a module supply a value for a missing attribute and describe the names it offers. It applies them to the two uses that the PEP itself names, deprecating renamed attributes and loading expensive values on demand, and analyses the rules that make the technique more delicate than it appears: global lookups bypass the hook, warnings disappear without the correct stacklevel, and every check for an attribute calls it. Intervening exactly when a module is asked for a name it does not have, without touching the names it does have, is the secret weapon of module-level __getattr__.

Deprecating Renamed Attributes

When a module renames a public attribute, removing the old name breaks every program that uses it, while keeping it silently prolongs its use. A module-level __getattr__ resolves the dilemma: the old name is no longer defined, so the normal lookup fails, the function receives the name, issues a DeprecationWarning and returns the new value. The following example builds the module in memory, so that it runs without writing any file, but the code inside source is exactly what a file such as settings.py would contain.

import sys
import types
import warnings

source = '''
import warnings

API_URL = "https://api.example.org"
_RENAMED = {"OLD_URL": "API_URL"}

def __getattr__(name):
    if name in _RENAMED:
        new = _RENAMED[name]
        warnings.warn(f"{name} is deprecated; use {new}",
                      DeprecationWarning, stacklevel=2)
        return globals()[new]
    raise AttributeError(f"module {__name__!r} has no attribute {name!r}")

def __dir__():
    return sorted([*globals(), *_RENAMED])
'''
settings = types.ModuleType("settings")
exec(source, settings.__dict__)
sys.modules["settings"] = settings

with warnings.catch_warnings(record=True) as caught:
    from settings import OLD_URL
print(OLD_URL)                     # Output: https://api.example.org
print(caught[0].message)           # Output: OLD_URL is deprecated; use API_URL
print("OLD_URL" in dir(settings))  # Output: True
try:
    settings.TIMEOUT
except AttributeError as error:
    print(error)  # Output: module 'settings' has no attribute 'TIMEOUT'

The import of OLD_URL succeeds and the warning is recorded, dir lists the old name through __dir__, and an unknown name still raises the conventional AttributeError. The argument stacklevel=2 is essential: it attributes the warning to the code that requested the name rather than to the module, which determines whether the user ever sees it, as the pitfalls below show. The same hook on classes, applied to every attribute of a wrapped object, is the technique described in the article devoted to proxy objects.

Loading Expensive Values on Demand

Open-world games stream each region of the map from disk only when the player approaches it, so the world starts quickly and a visited region stays loaded for later visits. This means that a module can define an expensive value, such as a large table or an optional submodule, only when a caller first requests it, and then store it in its own dictionary so that every later access is an ordinary lookup that never reaches __getattr__. The analogy, however, stops at this point, because a game also unloads distant regions to free memory, whereas a value stored in a module remains there for the rest of the program unless it is deleted explicitly.

import sys
import types

source = '''
loads = 0

def __getattr__(name):
    global loads
    if name == "SQUARES":
        loads += 1
        value = {n: n * n for n in range(1000)}
        globals()[name] = value
        return value
    raise AttributeError(f"module {__name__!r} has no attribute {name!r}")
'''
tables = types.ModuleType("tables")
exec(source, tables.__dict__)
sys.modules["tables"] = tables

print(tables.loads)                         # Output: 0
print(tables.SQUARES[12], tables.SQUARES[30])  # Output: 144 900
print(tables.loads)                         # Output: 1

The table does not exist when the module is imported, it is built on the first access, and the second access finds it in the module dictionary, so the counter stays at one. The same pattern of computing a value on the first request and storing it appears in dictionaries, as described in the article devoted to __missing__; for whole submodules, the import machinery described in the article devoted to import hooks also offers importlib.util.LazyLoader.

Pitfalls of Module-Level getattr

The hook applies only to attribute access on the module object, so most errors come from code that reaches names by another route or from side effects that every access repeats. Six pitfalls are distinguished, which are the following:

  1. Global lookups bypass it. Code inside the module that uses a missing name directly raises NameError, because PEP 562 deliberately excludes global lookups.
  2. Hidden warnings. Without stacklevel=2, a DeprecationWarning is attributed to the module itself, and the default filters, which show such warnings only for code in __main__, hide it.
  3. Repeated work. A value that is not stored in globals() is recomputed, and its warning or log message repeated, on every access.
  4. hasattr triggers it. Checking for an attribute calls __getattr__, so a check alone can load the value or emit the warning.
  5. Wrong exceptions. A hook that raises anything other than AttributeError, or returns None for unknown names, breaks hasattr, getattr with a default and from module import name.
  6. Invisible names. Without __dir__, dynamic names do not appear in dir(); static analysis tools, which do not run the module, may not see them even with it.

The first two pitfalls are reproduced in the following example.

import sys
import types
import warnings

def build(name, stacklevel):
    source = f'''
import warnings

def __getattr__(attr):
    if attr == "OLD":
        warnings.warn("OLD is deprecated", DeprecationWarning, stacklevel={stacklevel})
        return 1
    raise AttributeError(attr)

def uses_old():
    return OLD
'''
    module = types.ModuleType(name)
    exec(source, module.__dict__)
    sys.modules[name] = module
    return module

for level in (1, 2):
    module = build(f"lib{level}", level)
    with warnings.catch_warnings(record=True) as caught:
        module.OLD
    print(level, len(caught))
# Output: 1 0
# Output: 2 1
try:
    module.uses_old()
except NameError as error:
    print(error)  # Output: name 'OLD' is not defined

With the default filters, the warning issued at level one is attributed to the library and discarded, while the one issued at level two is attributed to the calling code in __main__ and recorded. The function uses_old fails because it looks OLD up as a global, a route that never reaches __getattr__; a module that renames a name must therefore update its own internal uses.

Choosing How to Customize a Module

Consequently, module-level __getattr__ suits names that must remain importable but should not exist as ordinary globals, as the following table summarizes.

Situation Recommended approach
A renamed public attribute that must keep working for a while __getattr__ with a DeprecationWarning and stacklevel=2
An expensive value needed only by some callers __getattr__ that stores the value in globals()
A submodule that should be imported only when used __getattr__ with importlib.import_module, or importlib.util.LazyLoader
Listing dynamic names in dir() A module-level __dir__
Properties or controlled assignment on a module Setting the module's __class__ to a types.ModuleType subclass
Names used inside the module itself Ordinary global definitions
Values that are cheap to compute Ordinary module constants

Conclusion

It is concluded that a module-level __getattr__ is called only when a name is missing from the module, that it supports deprecations and lazy values when it warns with stacklevel=2 and stores what it computes, and that __dir__ makes dynamic names visible to dir(). This magic covers attribute access only: global lookups inside the module bypass it, checks with hasattr trigger it, and unknown names must still raise AttributeError. Replacing a missing collaborator with an object that accepts every call and does nothing, so that callers need no checks for None, is the purpose of the Null Object pattern, which is developed in a future article of this series.