Popular recipes by Baptiste Carvello http://code.activestate.com/recipes/users/4175002/2010-09-21T06:08:48-07:00ActiveState Code RecipesDecorator for writing polymorphic functions (Python)
2010-09-21T06:08:48-07:00Baptiste Carvellohttp://code.activestate.com/recipes/users/4175002/http://code.activestate.com/recipes/577393-decorator-for-writing-polymorphic-functions/
<p style="color: grey">
Python
recipe 577393
by <a href="/recipes/users/4175002/">Baptiste Carvello</a>
(<a href="/recipes/tags/polymorphism/">polymorphism</a>, <a href="/recipes/tags/unicode/">unicode</a>).
Revision 2.
</p>
<p>Python 3 makes a clean separation between unicode text strings (str) and byte
strings (bytes). However, for some tasks (notably networking), it makes sense
to apply the same process to str and bytes, usually relying on the byte string
beeing encoded with an ASCII compatible encoding.</p>
<p>In this context, a polymorphic function is one which will operate on unicode
strings (str) or bytes objects (bytes) depending on the type of the arguments.
The common difficulty is that string constants used in the function also have
to be of the right type. This decorator helps by allowing to use a different
set of constants depending on the type of the argument.</p>