__getattr__ Falls Back For Missing Attributes
__getattr__ runs only after normal lookup fails, so a settings wrapper can serve defaults lazily while real typos still raise AttributeError.
Code
class EnvSettings:
"""显式值优先;没配置的键由 __getattr__ 回退到默认表。"""
defaults = {'region': 'eu-west-1', 'retries': '3'}
def __init__(self, **explicit) -> None:
# 显式值逐键 setattr 成实例属性:常规查找直接命中,__getattr__ 不触发
for key, value in explicit.items():
setattr(self, key, value)
def __getattr__(self, name: str):
# __getattr__ 只在常规查找失败后才被调用
if name in self.defaults:
return self.defaults[name]
raise AttributeError(f'no setting named {name!r}')
settings = EnvSettings(retries='5')
print(settings.retries) # 实例上有值:常规查找命中,__getattr__ 不触发
print(settings.region) # 实例上没有:回退到 defaults
try:
settings.missing
except AttributeError as exc:
print('missing ->', exc)
print(hasattr(settings, 'region'), getattr(settings, 'tokens', 'unset'))Output
Captured from a sandboxed run of this snippet in the build pipeline.
5
eu-west-1
missing -> no setting named 'missing'
True unsetgetattr Falls Back For Missing Attributes: how the code works
Under the hood: the class EnvSettings and the functions __init__ and __getattr__.
One loop does the cycling here: for key, value in explicit.items() — it runs inside __init__ and only writes each explicit value onto the instance, so normal lookup hits those keys and __getattr__ never fires for them. The AttributeError throw is not wired to that loop: __getattr__ contains no loop of its own — it checks defaults once and throws immediately for any failed lookup whose name is not there, with no loop and no early return involved anywhere on the throw path.
Watch out for
- Standard library only, so copying it in is enough to run.
Putting it to use
The exported logic lives in def __init__(self, **explicit) -> None
The run emits 1 labeled section — missing -> — one per step.
Core lines
def __init__(self, **explicit) -> None:
# 显式值逐键 setattr 成实例属性:常规查找直接命中,__getattr__ 不触发
for key, value in explicit.items():
setattr(self, key, value)
def __getattr__(self, name: str):
# __getattr__ 只在常规查找失败后才被调用
if name in self.defaults:
return self.defaults[name]
raise AttributeError(f'no setting named {name!r}')
except AttributeError as exc:
print('missing ->', exc)
Interactive Tools for This Topic
FAQ
- When does the code throw?
- Immediately, from `__getattr__`: when a lookup fails and the name is not in `defaults`, `raise AttributeError` is the last line of that method, so the throw happens on the spot — no loop and no early return sits on that path. The `for` loop in `__init__` only writes explicit values onto the instance and never reaches the raise.
- Does it depend on any third-party library?
- No third-party library is referenced; the standard library covers it. The file defines `__init__`, `__getattr__` at load time.
Report a problem with this exampleOpens a pre-filled issue on GitHub.