10.7. Reflection Use Cases

10.7.1. Use Case - 1

>>> class Point:
...     x: int
...     y: int
...     z: int
...
...     def __setattr__(self, attrname, value):
...         if attrname not in ('x', 'y', 'z'):
...             raise NameError('You can set only x, y, z attributes')
...         if type(value) not in (int,float):
...             raise TypeError('Attribute value must be int or float')
...         if value < 0:
...             raise ValueError('Attribute value cannot be negative')
...         return super().__setattr__(attrname, value)
>>> pt = Point()
>>> pt.x = 1
>>> pt.y = 2
>>> pt.z = 3
>>>
>>> pt.x = -1
Traceback (most recent call last):
ValueError: Attribute value cannot be negative
>>>
>>> pt.x = 'one'
Traceback (most recent call last):
TypeError: Attribute value must be int or float
>>>
>>> pt.notexisting = 1
Traceback (most recent call last):
NameError: You can set only x, y, z attributes

10.7.2. Use Case - 2

  • Get Attribute Both

>>> class Point:
...     x: int
...     y: int
...     z: int
...
...     def __getattribute__(self, attrname):
...         if attrname == 'y':
...             raise PermissionError('Attribute y access is forbidden')
...         return super().__getattribute__(attrname)
...
...     def __getattr__(self, attrname):
...         print(f'Attribute {attrname} does not exist')
...         super().__setattr__(attrname, 0)
...         print(f'Attribute {attrname} initialized with value 0')
>>> pt = Point()
>>>
>>> pt.x = 1
>>> pt.y = 2
>>>
>>> vars(pt)
{'x': 1, 'y': 2}
>>> pt.x
1
>>> pt.y
Traceback (most recent call last):
PermissionError: Attribute y access is forbidden
>>> pt.z
Attribute z does not exist
Attribute z initialized with value 0
>>>
>>> pt.z
0
>>> vars(pt)
{'x': 1, 'y': 2, 'z': 0}

10.7.3. Use Case - 3

>>> class User:
...     def __setattr__(self, attrname, value):
...         if attrname.startswith('_'):
...             raise PermissionError('Field is protected')
...         else:
...             return super().__setattr__(attrname, value)
>>>
>>>
>>> mark = User()
>>> mark.name = 'Mark Watney'
>>> print(mark.name)
Mark Watney
>>>
>>> mark._salary = 1000
Traceback (most recent call last):
PermissionError: Field is protected

10.7.4. Use Case - 4

>>> class User:
...     def __delattr__(self, attrname):
...         if attrname.startswith('_'):
...             raise PermissionError('Field is protected')
...         else:
...             return super().__delattr__(attrname)
>>>
>>>
>>> mark = User()
>>> mark.name = 'Mark Watney'
>>> mark._salary = 1000
>>>
>>> del mark.name
>>> del mark._salary
Traceback (most recent call last):
PermissionError: Field is protected

10.7.5. Use Case - 5

>>> class User:
...     def __getattribute__(self, attrname):
...         if attrname.startswith('_'):
...             raise PermissionError('Field is protected')
...         else:
...             return super().__getattribute__(attrname)
>>>
>>>
>>> mark = User()
>>>
>>> mark.name = 'Mark Watney'
>>> print(mark.name)
Mark Watney
>>>
>>> print(mark._salary)
Traceback (most recent call last):
PermissionError: Field is protected

10.7.6. Use Case - 6

>>> class User:
...     def __init__(self, name):
...         self.name = name
>>>
>>>
>>> mark = User('Mark Watney')
>>>
>>> hasattr(mark, 'name')
True
>>>
>>> hasattr(mark, 'mission')
False
>>>
>>> mark.mission = 'secret'
>>> hasattr(mark, 'mission')
True

10.7.7. Use Case - 7

>>> class User:
...     def __init__(self):
...         self.name = None
...
...     def __getattr__(self, attrname):
...         return 'Sorry, field does not exist'
>>>
>>>
>>> mark = User()
>>> mark.name = 'Mark Watney'
>>>
>>> print(mark.name)
Mark Watney
>>>
>>> print(mark._salary)
Sorry, field does not exist
>>> class User:
...     def __init__(self):
...         self.name = None
...
...     def __getattribute__(self, attrname):
...         print('Getattribute called... ')
...         result = super().__getattribute__(attrname)
...         print(f'Result was: "{result}"')
...         return result
...
...     def __getattr__(self, attrname):
...         print('Not found. Getattr called...')
...         print(f'Creating attribute {attrname} with `None` value')
...         super().__setattr__(attrname, None)
>>>
>>>
>>>
>>> mark = User()
>>> mark.name = 'Mark Watney'
>>>
>>> mark.name
Getattribute called...
Result was: "Mark Watney"
'Mark Watney'
>>>
>>> mark._salary
Getattribute called...
Not found. Getattr called...
Creating attribute _salary with `None` value
>>>
>>> mark._salary
Getattribute called...
Result was: "None"

10.7.8. Use Case - 8

>>> class User:
...     def __getattribute__(self, attrname):
...         if attrname.startswith('_'):
...             raise PermissionError('Field is protected')
...         else:
...             return super().__getattribute__(attrname)
...
...     def __setattr__(self, attrname, value):
...         if attrname.startswith('_'):
...             raise PermissionError('Field is protected')
...         else:
...             return super().__setattr__(attrname, value)
>>>
>>>
>>> mark = User()
>>>
>>> mark.name = 'Mark Watney'
>>> print(mark.name)
Mark Watney
>>>
>>> mark._salary = 1000
Traceback (most recent call last):
PermissionError: Field is protected
>>>
>>> print(mark._salary)
Traceback (most recent call last):
PermissionError: Field is protected

10.7.9. Use Case - 9

>>> class User:
...     def __init__(self, firstname, lastname):
...         self.firstname = firstname
...         self.lastname = lastname
>>>
>>>
>>> mark = User('Alice', 'Apricot')
>>>
>>> if mark._salary is None:
...     mark._salary = 1000
Traceback (most recent call last):
AttributeError: 'User' object has no attribute '_salary'
>>>
>>>
>>> if not hasattr(mark, '_salary'):
...     mark._salary = 1000
>>>
>>> print(mark._salary)
1000
>>> def input(prompt):
...     return '_salary'
>>>
>>>
>>> attrname = input('Type attribute name: ')   # _salary
>>> value = getattr(mark, attrname, 'no such attribute')
>>> print(value)
1000
>>> def input(prompt):
...     return 'notexisting'
>>>
>>>
>>> attrname = input('Type attribute name: ')  # notexisting
>>> value = getattr(mark, attrname, 'no such attribute')
>>> print(value)
no such attribute

10.7.10. Use Case - 10

>>> class User:
...     def __init__(self, firstname, lastname, username, password):
...         self.firstname = firstname
...         self.lastname = lastname
...         self._username = username
...         self._password = password
...
...     def __getattribute__(self, attrname):
...         if attrname in ('_username', '_password'):
...             raise PermissionError('Access to this field is forbidden')
...         return super().__getattribute__(attrname)
>>> mark = User('Alice', 'Apricot', username='alice', password='secret')
>>> mark.firstname
'Alice'
>>> mark.lastname
'Apricot'
>>> mark._username
Traceback (most recent call last):
PermissionError: Access to this field is forbidden
>>>
>>> mark._password
Traceback (most recent call last):
PermissionError: Access to this field is forbidden
>>> vars(mark)
{'firstname': 'Alice',
 'lastname': 'Apricot',
 '_username': 'alice',
 '_password': 'secret'}

10.7.11. Use Case - 11

>>> class User:
...     def __init__(self, firstname, lastname, username, password):
...         self.firstname = firstname
...         self.lastname = lastname
...         self._username = username
...         self._password = password
...
...     def __getattribute__(self, attrname):
...         return super().__getattribute__(attrname)
...
...     def __setattr__(self, attrname, value):
...         if not hasattr(self, attrname) and attrname in ('_username', '_password'):
...             return super().__setattr__(attrname, value)
...         if attrname.startswith('_'):
...             raise PermissionError('Access to this field is forbidden')
...         return super().__setattr__(attrname, value)
>>> mark = User('Alice', 'Apricot', username='alice', password='secret')
>>> mark._salary = 1000
Traceback (most recent call last):
PermissionError: Access to this field is forbidden
>>> vars(mark)
{'firstname': 'Alice',
 'lastname': 'Apricot',
 '_username': 'alice',
 '_password': 'secret'}
>>> mark._username = 'bob'
Traceback (most recent call last):
PermissionError: Access to this field is forbidden

10.7.12. Use Case - 12

>>> class User:
...     def __init__(self, firstname, lastname, username, password):
...         self.firstname = firstname
...         self.lastname = lastname
...         self._username = username
...         self._password = password
...
...     def __delattr__(self, attrname):
...         self.__setattr__(attrname, None)
>>> mark = User('Alice', 'Apricot', username='alice', password='secret')
>>> vars(mark)
{'firstname': 'Alice',
 'lastname': 'Apricot',
 '_username': 'alice',
 '_password': 'secret'}
>>> del mark._username
>>> del mark._password
>>> vars(mark)
{'firstname': 'Alice',
 'lastname': 'Apricot',
 '_username': None,
 '_password': None}

10.7.13. Use Case - 13

>>> class User:
...     def __init__(self, firstname, lastname, username, password):
...         self.firstname = firstname
...         self.lastname = lastname
...         self._username = username
...         self._password = password
...
...     def __getattribute__(self, attrname):
...         if attrname.startswith('_'):
...             raise PermissionError('Access to this field is forbidden')
...         return super().__getattribute__(attrname)
>>> mark = User('Alice', 'Apricot', username='alice', password='secret')
>>> vars(mark)
Traceback (most recent call last):
PermissionError: Access to this field is forbidden
>>>
>>> mark.__dict__
Traceback (most recent call last):
PermissionError: Access to this field is forbidden
>>> dir(mark)
Traceback (most recent call last):
PermissionError: Access to this field is forbidden
>>>
>>> mark.__dir__()
Traceback (most recent call last):
PermissionError: Access to this field is forbidden
>>> help(mark)
Traceback (most recent call last):
PermissionError: Access to this field is forbidden
>>>
>>> mark.__doc__
Traceback (most recent call last):
PermissionError: Access to this field is forbidden
>>> type(mark)
<class '__main__.User'>
>>>
>>> mark.__class__
Traceback (most recent call last):
PermissionError: Access to this field is forbidden

10.7.14. Use Case - 14

>>> class User:
...     def __init__(self, firstname, lastname, username, password):
...         self.firstname = firstname
...         self.lastname = lastname
...         self._username = username
...         self._password = password
...
...     def __getattribute__(self, attrname):
...         if attrname.startswith('_') and not attrname.startswith('__'):
...             raise PermissionError('Access to this field is forbidden')
...         return super().__getattribute__(attrname)
>>> mark = User('Alice', 'Apricot', username='alice', password='secret')
>>> vars(mark)
{'firstname': 'Alice',
 'lastname': 'Apricot',
 '_username': 'alice',
 '_password': 'secret'}
>>> mark._username
Traceback (most recent call last):
PermissionError: Access to this field is forbidden
>>> mark._password
Traceback (most recent call last):
PermissionError: Access to this field is forbidden

10.7.15. Use Case - 15

>>> class User:
...     def __init__(self, firstname, lastname, phone, email, username, password):
...         self.firstname = firstname
...         self.lastname = lastname
...         self._phone = phone
...         self._email = email
...         self.__username = username
...         self.__password = password
...
...     def __getattribute__(self, attrname):
...         if attrname.startswith('_') and not attrname.startswith('__'):
...             raise PermissionError('Access to this field is forbidden')
...         return super().__getattribute__(attrname)
>>> mark = User(
...     firstname='Alice',
...     lastname='Apricot',
...     phone='+1 (234) 555 1337',
...     email='mwatney@nasa.gov',
...     username='alice',
...     password='secret',
... )
>>> vars(mark)
{'firstname': 'Alice',
 'lastname': 'Apricot',
 '_phone': '+1 (234) 555 1337',
 '_email': 'mwatney@nasa.gov',
 '_User__username': 'alice',
 '_User__password': 'secret'}
>>> mark._email
Traceback (most recent call last):
PermissionError: Access to this field is forbidden
>>> mark._phone
Traceback (most recent call last):
PermissionError: Access to this field is forbidden
>>> mark._User__username
Traceback (most recent call last):
PermissionError: Access to this field is forbidden
>>> mark._User__password
Traceback (most recent call last):
PermissionError: Access to this field is forbidden

10.7.16. Use Case - 16

>>> class Immutable:
...     def __setattr__(self, attrname, value):
...         raise PermissionError('Immutable')
>>> class Protected:
...     def __setattr__(self, attrname, value):
...         if attrname.startswith('_'):
...             raise PermissionError('Field is protected')
...         else:
...             return super().__setattr__(attrname, value)

10.7.17. Use Case - 17

>>> class Temperature:
...     kelvin: float
...
...     def __init__(self, kelvin):
...         self.kelvin = kelvin
...
...     def __setattr__(self, attrname, value):
...         if attrname == 'kelvin' and value < 0.0:
...             raise ValueError('Kelvin temperature cannot be negative')
...         else:
...             return super().__setattr__(attrname, value)
>>>
>>>
>>> t = Temperature(100)
>>>
>>> t.kelvin = 20
>>> print(t.kelvin)
20
>>>
>>> t.kelvin = -10
Traceback (most recent call last):
ValueError: Kelvin temperature cannot be negative

10.7.18. Use Case - 18

>>> class Temperature:
...     kelvin: float
...     celsius: float
...     fahrenheit: float
...
...     def __getattr__(self, attrname):
...         if attrname == 'kelvin':
...             return super().__getattribute__('kelvin')
...         if attrname == 'celsius':
...             return self.kelvin - 273.15
...         if attrname == 'fahrenheit':
...             return (self.kelvin-273.15) * 1.8 + 32
>>>
>>>
>>> t = Temperature()
>>> t.kelvin = 373.15
>>>
>>> print(t.kelvin)
373.15
>>> print(t.celsius)
100.0
>>> print(t.fahrenheit)
212.0

10.7.19. Use Case - 19

>>> class Container:
...     def __init__(self, **kwargs: dict) -> None:
...         for key, value in kwargs.items():
...             setattr(self, key, value)
>>>
>>>
>>> a = Container(firstname='Alice', lastname='Apricot')
>>> vars(a)
{'firstname': 'Alice', 'lastname': 'Apricot'}
>>>
>>> b = Container(color='red')
>>> vars(b)
{'color': 'red'}
>>>
>>> c = Container(min=1, max=10)
>>> vars(c)
{'min': 1, 'max': 10}

10.7.20. Use Case - 20

>>> class User:
...     def __init__(self, firstname, lastname, username, password):
...         self.firstname = firstname
...         self.lastname = lastname
...         self._password = password
...         self._username = username
...
...     def __getattribute__(self, name):
...         if name == '__dict__':
...             output = super().__getattribute__(name).copy()
...             del output['_password']
...             del output['_username']
...             return output
...         if name.startswith('_') and not name.startswith('__'):
...             raise PermissionError
...         return super().__getattribute__(name)
>>>
>>>
>>> mark = User(
...     firstname='Alice',
...     lastname='Apricot',
...     username='alice',
...     password='secret',
... )

Show vars, note that there is no username and password:

>>> vars(mark)
{'firstname': 'Alice', 'lastname': 'Apricot'}

Show dir, note that there is no username and password:

>>> dir(mark)
['__class__', '__delattr__', '__dict__', '__dir__', '__doc__',
 '__eq__', '__firstlineno__', '__format__', '__ge__', '__getattribute__',
 '__getstate__', '__gt__', '__hash__', '__init__', '__init_subclass__',
 '__le__', '__lt__', '__module__', '__ne__', '__new__', '__reduce__',
 '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__static_attributes__',
 '__str__', '__subclasshook__', '__weakref__', 'firstname', 'lastname']