I’m trying to get into metaclass programming in Python and I’d like to know how to restrict attribute type with metaclass.
It’s quite easy with the descriptors, but what about metaclasses?
Here is short example:
>>> class Image(Object):
... height = 0
... width = 0
... path = '/tmp'
... size = 0
>>> img = Image()
>>> img.height = 340
>>> img.height
340
>>> img.path = '/tmp/x00.jpeg'
>>> img.path
'/tmp/x00.jpeg'
>>> img.path = 320
Traceback (most recent call last):
...
TypeError
Python version is 2.7
Just override
__setattr__in the metaclass and check default type for every attribute during initialization:Alternative (and maybe more elegant) method:
Behaviour is the same as before