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

Peter Otten __peter__ at web.de
Sun Oct 6 03:25:51 EDT 2013


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.

Personally, I'd rather not copy that kind of interface.

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

Why do you rely on a homebrew solution instead of actually calling the 
function or initializer?

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

inspect.getcallargs() may be worth a look.




More information about the Python-list mailing list