PEP: Specialization Syntax

Nicolas Fleury nid_oizo at yahoo.com_remove_the_
Tue Aug 9 23:41:08 CEST 2005


Martin v. Löwis wrote:
> Nicolas Fleury wrote:
> 
>>Well, I'm using the alternatives.
> 
> Perhaps not to the full power.

Not perhaps, surely;)  Who does anyway;)

> So you don't want to write the makeArrayType function, right?
> 
> How about this:
> 
> # declaration
> class Array(object):
>   __typeargs__ = ['arg1', ('arg2', someDefault)]
>   ...
> 
> # use
> t = specialize(Array, arg1=Int32)
> 
> where specialize is defined as
> 
> def specialize(ptype, *args):
>   result = type(ptype.__name__, (ptype,), args)
>   for t in result.__typeargs__:
>       if isinstance(t, string):
>           if not hasattr(result, t):
>               raise TypeError("missing parameter "+t)
>       else:
>           name,val = t
>           if not hasattr(result, name):
>               setattr(result, val)
>    return result

That exact solution would not work for me, since that would replace the 
class metaclass, right?  However, you have a good point.  Such a 
function could be done by using the class metaclass instead of type, 
passing the base classes and dictionary (basically copying the class) 
and using a dictionary with args values as a key to avoid redundacies 
(can't see if there's something else).

Thx and regards,
Nicolas



More information about the Python-list mailing list