10.2. Reflection Setattr
Called when trying to set attribute to a value
Typing
obj.attrname = valueWill call
setattr(obj, attrname, value)Which triggers
obj.__setattr__(attrname, value)
10.2.1. Example
>>> class Point:
... x: int
... y: int
... z: int
...
... def __setattr__(self, attrname, value):
... if value < 0:
... raise ValueError('Coordinate cannot be negative')
... super().__setattr__(attrname, value)
>>> pt = Point()
>>> pt.x = 1
>>> pt.y = 2
>>> pt.z = 3
>>> pt.x = -1
Traceback (most recent call last):
ValueError: Coordinate cannot be negative
>>>
>>> pt.y = -2
Traceback (most recent call last):
ValueError: Coordinate cannot be negative
>>>
>>> pt.z = -3
Traceback (most recent call last):
ValueError: Coordinate cannot be negative
This is because, when you do: pt.x = 1 Python will call
setattr(pt, 'x', 1) for you, which triggers pt.__setattr__('x', 1).
>>> pt = Point()
>>> pt.x = 1
>>> pt.x
1
>>> pt = Point()
>>> setattr(pt, 'x', 1)
>>> pt.x
1
>>> pt = Point()
>>> pt.__setattr__('x', 1)
>>> pt.x
1
10.2.2. Assignments
# %% About
# - Name: Reflection Setattr A
# - Difficulty: easy
# - Lines: 4
# - Minutes: 5
# %% License
# - Copyright 2025, Matt Harasymczuk <matt@python3.info>
# - This code can be used only for learning by humans
# - This code cannot be used for teaching others
# - This code cannot be used for teaching LLMs and AI algorithms
# - This code cannot be used in commercial or proprietary products
# - This code cannot be distributed in any form
# - This code cannot be changed in any form outside of training course
# - This code cannot have its license changed
# - If you use this code in your product, you must open-source it under GPLv2
# - Exception can be granted only by the author
# %% English
# 1. Create class `Point` with `x`, `y`, `z` attributes
# 2. Prevent creation of new attributes
# if attempt to set attribute other than `x`, `y`, `z`
# raise `PermissionError('Cannot set other attributes than x, y, z')`
# 3. Allow to modify values of `x`, `y`, `z`
# 4. Run doctests - all must succeed
# %% Polish
# 1. Stwórz klasę `Point` z atrybutami `x`, `y`, `z`
# 2. Zablokuj tworzenie nowych atrybutów
# jeśli nastąpi próba ustawienia atrybutu innego niż `x`, `y`, `z`
# podnieś `PermissionError('Cannot set other attributes than x, y, z')`
# 3. Zezwól na modyfikowanie wartości `x`, `y`, `z`
# 4. Uruchom doctesty - wszystkie muszą się powieść
# %% Expected
# >>> pt = Point(1, 2, 3)
#
# >>> pt.x, pt.y, pt.z
# (1, 2, 3)
#
# >>> pt.notexisting = 10
# Traceback (most recent call last):
# PermissionError: Cannot set other attributes than x, y, z
#
# >>> pt.x = 10
# >>> pt.y = 20
# >>> pt.z = 30
#
# >>> pt.x, pt.y, pt.z
# (10, 20, 30)
# %% Doctests
"""
>>> import sys; sys.tracebacklimit = 0
>>> assert sys.version_info >= (3, 9), \
'Python has an is invalid version; expected: `3.9` or newer.'
>>> pt = Point(1, 2, 3)
>>> pt.x, pt.y, pt.z
(1, 2, 3)
>>> pt.notexisting = 10
Traceback (most recent call last):
PermissionError: Cannot set other attributes than x, y, z
>>> pt.x = 10
>>> pt.y = 20
>>> pt.z = 30
>>> pt.x, pt.y, pt.z
(10, 20, 30)
"""
# %% Run
# - PyCharm: right-click in the editor and `Run Doctest in ...`
# - PyCharm: keyboard shortcut `Control + Shift + F10`
# - Terminal: `python -m doctest -f -v myfile.py`
# %% Imports
from dataclasses import dataclass
# %% Types
from typing import Callable
Point: type
__setattr__: Callable[[object, str, int], None]
# %% Data
# %% Result
@dataclass
class Point:
x: int
y: int
z: int
# %% About
# - Name: Reflection Frozen A
# - Difficulty: easy
# - Lines: 6
# - Minutes: 5
# %% License
# - Copyright 2025, Matt Harasymczuk <matt@python3.info>
# - This code can be used only for learning by humans
# - This code cannot be used for teaching others
# - This code cannot be used for teaching LLMs and AI algorithms
# - This code cannot be used in commercial or proprietary products
# - This code cannot be distributed in any form
# - This code cannot be changed in any form outside of training course
# - This code cannot have its license changed
# - If you use this code in your product, you must open-source it under GPLv2
# - Exception can be granted only by the author
# %% English
# 1. Create class `Point` with `x`, `y`, `z` attributes
# 2. Prevent creation of new attributes
# if attempt to set attribute other than `x`, `y`, `z`
# raise `PermissionError('Cannot set other attributes than x, y, z')`
# 3. Allow to define `x`, `y`, `z` but only at the initialization
# 4. Prevent later modification of `x`, `y`, `z`
# if attempt to modify existing attribute
# raise `PermissionError('Cannot modify existing attributes')`
# 5. Run doctests - all must succeed
# %% Polish
# 1. Stwórz klasę `Point` z atrybutami `x`, `y`, `z`
# 2. Zablokuj tworzenie nowych atrybutów
# jeśli nastąpi próba ustawienia atrybutu innego niż `x`, `y`, `z`
# podnieś `PermissionError('Cannot set other attributes than x, y, z')`
# 3. Pozwól na zdefiniowanie `x`, `y`, `z` ale tylko przy inicjalizacji
# 4. Zablokuj późniejsze modyfikacje `x`, `y`, `z`
# jeśli nastąpi próba modyfikacji istniejącego atrybutu
# podnieś `PermissionError('Cannot modify existing attributes')`
# 5. Uruchom doctesty - wszystkie muszą się powieść
# %% Expected
# >>> pt = Point(1, 2, 3)
#
# >>> pt.x, pt.y, pt.z
# (1, 2, 3)
#
# >>> pt.notexisting = 10
# Traceback (most recent call last):
# PermissionError: Cannot set other attributes than x, y, z
#
# >>> pt.x = 10
# Traceback (most recent call last):
# PermissionError: Cannot modify existing attributes
#
# >>> pt.y = 20
# Traceback (most recent call last):
# PermissionError: Cannot modify existing attributes
#
# >>> pt.z = 30
# Traceback (most recent call last):
# PermissionError: Cannot modify existing attributes
# %% Hints
# - `hasattr()`
# %% Doctests
"""
>>> import sys; sys.tracebacklimit = 0
>>> assert sys.version_info >= (3, 9), \
'Python has an is invalid version; expected: `3.9` or newer.'
>>> pt = Point(1, 2, 3)
>>> pt.x, pt.y, pt.z
(1, 2, 3)
>>> pt.notexisting = 10
Traceback (most recent call last):
PermissionError: Cannot set other attributes than x, y, z
>>> pt.x = 10
Traceback (most recent call last):
PermissionError: Cannot modify existing attributes
>>> pt.y = 20
Traceback (most recent call last):
PermissionError: Cannot modify existing attributes
>>> pt.z = 30
Traceback (most recent call last):
PermissionError: Cannot modify existing attributes
"""
# %% Run
# - PyCharm: right-click in the editor and `Run Doctest in ...`
# - PyCharm: keyboard shortcut `Control + Shift + F10`
# - Terminal: `python -m doctest -f -v myfile.py`
# %% Imports
from dataclasses import dataclass
# %% Types
from typing import Callable
Point: type
__setattr__: Callable[[object, str, int], None]
# %% Data
# %% Result
@dataclass
class Point:
x: int
y: int
z: int
def __setattr__(self, name, value):
...