On Saturday, October 5, 2013 9:04:25 PM UTC-7, John Ladasky wrote:
> Hi folks,
> 
> 
> 
> I'm trying to make some of Python class definitions behave like the ones I 
> find in professional packages, such as Matplotlib.  A Matplotlib class can 
> often have a very large number of arguments -- some of which may be optional, 
> some of which will assume default values if the user does not override them, 
> etc.
> 
> 
> 
> I have working code which does this kind of thing.  I define required 
> arguments and their default values as a class attribute, in an OrderedDict, 
> so that I can match up defaults, in order, with *args.  I'm using 
> set.issuperset() to see if an argument passed in **kwargs conflicts with one 
> which was passed in *args.  I use  set.isdisjoint() to look for arguments in 
> **kwargs which are not expected by the class definition, raising an error if 
> such arguments are found.
> 
> 
> 
> Even though my code works, I'm finding it to be a bit clunky.  And now, I'm 
> writing a new class which has subclasses, and so actually keeps the "extra" 
> kwargs instead of raising an error... This is causing me to re-evaluate my 
> original code.
> 
> 
> 
> It also leads me to ask: is there a CLEAN and BROADLY-APPLICABLE way for 
> handling the *args/**kwargs/default values shuffle that I can study?  Or is 
> this sort of thing too idiosyncratic for there to be a general method?
> 
> 
> 
> Thanks for any pointers!

"Subclassing ndarray can get a bit complicated"

Another software pattern idea is "encapsulate don't inherit". When a class is 
really messy to subclass, start fresh with a new class that wraps the messy 
class. Create redirect methods for whatever is needed, then subclass from the 
class you created.

In fact, I'd go so far as to say you should only subclass from classes that 
were designed with subclassing in mind. If you find yourself bending over 
backwards to make subclassing work, it means you should be wrapping and 
redirecting instead.

This is perhaps more true in C#/Java than Python, but still something to think 
about.
-- 
https://mail.python.org/mailman/listinfo/python-list

Reply via email to