[Tutor] Polymorphic function in Python 2 & 3?

Dave Angel davea at davea.name
Sat Sep 7 23:11:25 CEST 2013


On 7/9/2013 15:45, Albert-Jan Roskam wrote:

> 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.
>

Seems to me you went way around the barn, just to avoid the **kwargs
(and *args) construct. Is this an assignment where the teacher specified
extra constraints, or is it a self-challenge, or are you just trying
to learn more about introspection?

Perhaps you were trying to make sure the caller never uses any keyword
arguments other than those 5?  Your sample top-level call never uses
keyword arguments at all, so if that was your goal, you could have used
*args, instead of kwargs.

At the same time, you allow several specific types of data in each
argument.  You don't permit list of dicts, or dict of dict of dict, or
many other variants that could have been done.  So it's not as general
as it might have been, with a little more work.

You give no indication how the user of this library would use the data
stored in the object.  But presently he has to use the names a, b, ...  
instead of the more natural  numeric subscripting if you had just
accepted a *args.

And finally, you say that your data is binary.  But valid utf-8 byte
strings are a tiny subset of possible binary byte strings.  So if some
data is being converted from unicode strings using utf-8, and other data
is binary byte strings, it seems the result might be confusing and error
prone.  If I were mixing binary byte strings and encoded unicode
strings, I'd want to store flags with each.  And what better way to do
that than just not to convert from unicode at all.  The strict typing of
Python handles it nicely.

Presumably you have some real goal which makes all these points moot.


-- 
DaveA




More information about the Tutor mailing list