TypedAttributes

9 views
Skip to first unread message

Peter Inglesby

unread,
Sep 4, 2012, 7:13:54 PM9/4/12
to cam...@googlegroups.com
At this evening's meeting I gave a talk about descriptors which included a way of ensuring that an object's attributes are of a certain type.  Tom objected that my original solution was too verbose, with code that looked like this:

>>> class Person(object):
...     name = TypedAttribute("name", str)
...     age = TypedAttribute("age", int)

It was suggested that this could be shortened with the help of a metaclass, and this turned out to be easier than I'd expected:

>>> class _TypedAttribute(object):
...     def __init__(self, name, typ):
...         self.name = name
...         self.typ = typ
...     def __set__(self, inst, val):
...         if isinstance(val, self.typ):
...             inst.__dict__[self.name] = val
...         else:
...             raise TypeError
... 
>>> class TypedAttribute(object):
...     def __init__(self, typ):
...         self.typ = typ
... 
>>> class TypedClass(type):
...     def __new__(cls, name, bases, attrs):
...         for k, v in attrs.items():
...             if isinstance(v, TypedAttribute):
...                 attrs[k] = _TypedAttribute(k, v.typ)
...         return type.__new__(cls, name, bases, attrs)
... 
>>> class Person(object):
...     __metaclass__ = TypedClass
...     name = TypedAttribute(str)
...     age = TypedAttribute(int)
... 
>>> p = Person()
>>> p.name = 'Bill'
>>> p.name
'Bill'
>>> p.age = 25
>>> p.age
25
>>> p.age = '25'
Traceback (most recent call last):
  File "<console>", line 1, in <module>
  File "<console>", line 9, in __set__
TypeError
>>> p.age
25


Tibs

unread,
Sep 5, 2012, 2:57:31 PM9/5/12
to cam...@googlegroups.com
That's really cool.

The other day I was asked if I was an expert Python programmer, and I said that this was difficult to answer in the way they wanted, because I know several EXPERT Python programmers. I stand by that opinion.

Tibs
Reply all
Reply to author
Forward
0 new messages