PEP: Specialization Syntax
"Martin v. Löwis"
martin at v.loewis.de
Tue Aug 9 15:26:53 EDT 2005
Nicolas Fleury wrote:
> Well, I'm using the alternatives.
Perhaps not to the full power.
> __arrayTypes = {}
> def makeArrayType(arg1, arg2=someDefault):
> if (arg1, arg2) in __arrayTypes:
> return __arrayTypes[arg1, arg2]
> renamed_arg1 = arg1
> renamed_arg2 = arg2
> class Array:
> arg1 = renamed_arg1
> arg2 = renamed_arg2
> ...
> __arrayTypes[arg1, arg2] = Array
> return Array
>
> Does it qualify as an "acceptable alternative"? when it could have been:
>
> class Array[arg1, arg2=someDefault]:
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
Regards,
Martin
More information about the Python-list
mailing list