[Tutor] Polymorphic function in Python 2 & 3?

Albert-Jan Roskam fomcl at yahoo.com
Sat Sep 7 21:45:02 CEST 2013


Hi,

I have a class and I want it's initializer to be able to take both byte strings (python 3: byte objects) and unicode strings (python 3: strings). So it's foward compatible Python 2 code (or backward compatible Python 3 code, if you like). If needed, the arguments of __init__ are converted into bytes using a function called encode(). I pasted the code that I wrote here: http://pastebin.com/2WBQ0H87. Sorry if it's a little long. It works for Python 2.7 and 3.3. But is this the best way to do this? In particular, is inspect.getargs the best way to get the argument names? (I don't want to use **kwargs). Also, I am using setattr to set the parameters, so the encode() method has side effects, which may not be desirable. I need bytes because I am working with binary data.


Thank you in advance!

 
Regards,
Albert-Jan


~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
All right, but apart from the sanitation, the medicine, education, wine, public order, irrigation, roads, a 
fresh water system, and public health, what have the Romans ever done for us?
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ 


More information about the Tutor mailing list