Variable arguments (*args, **kwargs): seeking elegance

Peter Cacioppi peter.cacioppi at gmail.com
Tue Oct 8 04:30:19 EDT 2013


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!

"One thought -- often, people turn to subclassing as the only tool in
their toolbox. Have you considered that it may be easier/better to work
with delegation and composition instead? "

Double like.

Subclassing is awesome when it is used properly ... which usually means used cautiously.

Delegation/composition just doesn't result in the some sort of weird gotchas.




More information about the Python-list mailing list