Python instance variables as optional arguments

In python, is there a way to use instance variables as optional arguments in a class method? i.e:

def function(self, arg1=val1, arg2=val2, arg3=self.instance_var): # do stuff.... 

Any help would be appreciated.

+7
function python class
source share
5 answers

Try the following:

 def foo(self, blah=None): if blah is None: # faster than blah == None - thanks to kcwu blah = self.instance_var 
+14
source share

All answers suggesting None are correct; if you want to make sure that the caller can pass None as a normal argument, use the special sentinel and test with is :

 class Foo(object): __default = object() def foo(self, blah=Foo.__default): if blah is Foo.__default: blah = self.instavar 

Each call to object() creates a unique object, so is will never be successful between it and any other value. The two underscores in __default mean “highly private”, which means that callers know that they should not try to deal with it (and this will require some work, clearly mimicking the name that the compiler does).

The reason you cannot just use the code you entered is, by the way, the default values ​​that are evaluated when the def statement evaluates, and not later during the call; and at time def , there is as yet no self from which to take an instance variable.

+5
source share

no, because the instance does not exist when the class function definition time

You should rewrite as follows

 def function(self, arg1=val1, arg2=val2, arg3=None): if arg3 is None: arg3 = self.instance_var 

This is slightly different from the original: you cannot pass arg3 with a value of None if you really want to.

Alternative solution:

 def function(self, arg1=val1, arg2=val2, **argd): arg3 = argd.get('arg3', self.instance_var) 
+2
source share
 def foo(self, blah=None): blah = blah if not blah is None else self.instance_var 

This works with python 2.5 onward and handles cases where blah are empty lines, lists, etc.

0
source share

An alternative way to do this:

 def foo(self, blah=None): blah = blah or self.instance_var 

This shorter version looks better, especially when there is more than one optional argument.

Use with caution. See comments below ...

-one
source share

All Articles