the right way of handling **args for __init__ and other methods
Bjorn Pettersen
bjorn at roguewave.com
Mon Jul 24 12:16:24 EDT 2000
Oivvio Polite wrote:
>
> Hi all.
> I guess this is more of a design question than a howto question.
>
> It has to do with implementing arbitrary-argument set methods.
> I want the user to be able to use the same interface with __init__ and read.
> This is a stripped down version:
> class argeater:
> def __init__(self, somearg, **args):
> print "init ",args
> self.data = {}
> self.read(somearg, argdict=args)
you can use apply(self.read, (), args) and avoid the special case in
read, or...
> def read(self, somearg, argdict=None,**args):
> print "read ",args
> print "argdict ",argdict
>
> #putting everything from argdict into args
> #feels a bit awkward.
> if argdict:
> assert type(argdict) == types.DictionaryType
> for key in argdict.keys():
> if not args.has_key(key):
> args[key] = argdict[key]
>
> #now do a lot of stuff to self.data
> #based on contents of args
Since args looks to be always empty when argdict != None, you can say
args.update(argdict)
which will overwrite args, or if you want to be able to pass both a
dictionary and keyword args to read:
tmp = {}
tmp.update(args)
tmp.update(argdict)
-- bjorn
More information about the Python-list
mailing list