[Python-Dev] Polymorphic best practices [was: (Not) delaying the 3.2 release] (original) (raw)

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 stringliterals: pass class bytesliterals: pass for name, value in literals.items(): setattr(stringliterals, name, value) setattr(bytesliterals, name, bytes(value, 'ASCII')) del literals, name, value And the subclasses do: class BytesHeader(BaseHeader): lit = email.utils.bytesliterals class StringHeader(BaseHeader): lit = email.utils.stringliterals

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