sub typing built in type with common attributes. Am I right?

Maric Michaud maric at aristote.info
Fri Jul 18 06:28:26 EDT 2008


Le Friday 18 July 2008 11:36:20 King, vous avez écrit :
> Could you please suggest an alternative or code improvement for the
> matter.

I'm not sure what you are trying to achieve with your snippet, but I suspect 
it's some sort of templating, right ? If so, using the dynamic nature of 
python should help :

>>>[103]: def make_subtype_with_attr(type_, ro_attr, rw_attr) :
    dic = {}
    for i in ro_attr : dic[i] = property(lambda s, n=i : getattr(s, '_'+n))
    def __new__(cls, *args, **kwargs) :
        instance = type_.__new__(cls, *args)
        for i in rw_attr : setattr(instance, i, kwargs[i])
        for i in ro_attr : setattr(instance, '_'+i, ro_attr[i])
        return instance
    dic['__new__'] = __new__
    return type('my_' + type_.__name__, (type_,), dic)
   .....:

>>>[113]: my_int = make_subtype_with_attr(int, 
{'name' : 'myint', 'id':123452}, ('foo',))

>>>[114]: i = my_int(5, foo=3)

>>>[115]: i.foo
...[115]: 3

>>>[116]: i
...[116]: 5

>>>[117]: i.id
...[117]: 123452

>>>[118]: i.id = 2
---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)

/home/maric/<ipython console> in <module>()

AttributeError: can't set attribute


-- 
_____________

Maric Michaud



More information about the Python-list mailing list