[Python-Dev] Polymorphic best practices [was: (Not) delaying the 3.2 release]
Baptiste Carvello
baptiste13z at free.fr
Fri Sep 17 11:25:20 CEST 2010
R. David Murray a écrit :
> I'm trying one approach in email6:
> Bytes and String subclasses, where the subclasses have an attribute
> named 'literals' derived from a utility module that does this:
>
> literals = dict(
> empty = '',
> colon = ':',
> newline = '\n',
> space = ' ',
> tab = '\t',
> fws = ' \t',
> headersep = ': ',
> )
>
> class _string_literals:
> pass
> class _bytes_literals:
> pass
>
> for name, value in literals.items():
> setattr(_string_literals, name, value)
> setattr(_bytes_literals, name, bytes(value, 'ASCII'))
> del literals, name, value
>
> And the subclasses do:
>
> class BytesHeader(BaseHeader):
> lit = email.utils._bytes_literals
>
> class StringHeader(BaseHeader):
> lit = email.utils._string_literals
>
I've just written a decorator which applies a similar strategy for insulated
functions, by passing them an appropriate namespace as an argument. It could be
useful in cases where only a few functions are polymorphic, not a full class or
module.
http://code.activestate.com/recipes/577393-decorator-for-writing-polymorphic-functions/
Cheers, B.
More information about the Python-Dev
mailing list