function argument dependent on another function argument?

Steven D'Aprano steve at REMOVE-THIS-cybersource.com.au
Sun Jan 18 16:26:25 CET 2009


On Sun, 18 Jan 2009 06:19:03 -0800, Reckoner wrote:

> I  would like to do:
> 
> def foo(self,x,y=self.a)
> 
> where the default value for y=self.a. Since this is not possible, I wind
> up doing
> 
> 
> def foo(self,x,y=None)
>   if not y:
>     y=self.a
> 
> but that seems kind of clumsy.

It's also incorrect, because if you pass y=0 as an argument, or any other 
false value, it will be replaced by self.a.


> Is there a better way to do this?

def foo(self, x, y=None):
    if y is None:
        y = self.a


I don't find that clumsy in the least. I find it perfectly readable and a 
standard idiom.


-- 
Steven



More information about the Python-list mailing list