10.3. Reflection Delattr

  • Called when trying to delete attribute

  • Typing del obj.attrname

  • Will call delattr(obj, attrname)

  • Which triggers mark.__delattr__(name)

10.3.1. Example

>>> class Point:
...     x: int
...     y: int
...     z: int
...
...     def __delattr__(self, attrname):
...         self.__setattr__(attrname, 0)
>>> pt = Point()
>>> pt.x = 1
>>> pt.y = 2
>>> pt.z = 3
>>> del pt.x, pt.y, pt.z
>>> pt.x, pt.y, pt.z
(0, 0, 0)
>>> del pt.x
>>> pt.x
0
>>> delattr(pt, 'x')
>>> pt.x
0
>>> pt.__delattr__('x')
>>> pt.x
0

10.3.2. Assignments

# %% About
# - Name: Reflection Delattr A
# - Difficulty: easy
# - Lines: 2
# - Minutes: 3

# %% 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 deleting attributes
#    if attempt to delete any attribute
#    raise `PermissionError('Cannot delete attributes')`
# 3. Run doctests - all must succeed

# %% Polish
# 1. Stwórz klasę `Point` z atrybutami `x`, `y`, `z`
# 2. Zablokuj usuwanie atrybutów
#    jeśli nastąpi próba usunięcia jakiegokolwiek atrybutu
#    podnieś `PermissionError('Cannot delete attributes')`
# 3. Uruchom doctesty - wszystkie muszą się powieść

# %% Expected
# >>> pt = Point(1, 2, 3)
#
# >>> pt.x, pt.y, pt.z
# (1, 2, 3)
#
# >>> del pt.x
# Traceback (most recent call last):
# PermissionError: Cannot delete attributes
#
# >>> del pt.notexisting
# Traceback (most recent call last):
# PermissionError: Cannot delete attributes

# %% 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)

>>> del pt.x
Traceback (most recent call last):
PermissionError: Cannot delete attributes

>>> del pt.notexisting
Traceback (most recent call last):
PermissionError: Cannot delete 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
__delattr__: Callable[[object, str], None]

# %% Data

# %% Result
@dataclass
class Point:
    x: int
    y: int
    z: int