How to assign instance variables as default values for keyword arguments in the same class in Python
-
20-12-2019 - |
Question
In Python 3.3+, given a class with a method, the class has an instance variable, which is a simple object() object (we'll call it self.FALSE). How do I use that instance variable as a default value for a keyword argument?
class Test:
def __init__(self):
self.FALSE=object();
def Tester(self, key=self.FALSE):
pass;
This, of course, doesn't work because the scope of keyword argument default values does not include self (nor does it include the Test class generally). It does include global variables and at least some objects, however.
Is there a way to do this? I don't have a dire need, right now, but it would be really nice if I could do that, somehow. I would think you would be able to pass anything in as a keyword argument default value. Surely there must be a way.
Solution
Initially have the default of value key
as None
and in the function, if key
is None
, then you can set the default value, whatever you like.
def Tester(self, key=None):
if key is None:
key = self.FALSE
Also, you don't need semicolons in Python, like we need in C/C++/JAVA.
OTHER TIPS
There isn't a way, because instance attributes do not exist until an instance is created, but the methods are defined when the class is created, before any instances exist. That is, saying (as you do in your question) that "the class has an instance variable" is incorrect. The class has no such thing; only the instances have that variable, and only if and when they are created.
You must do as thefourtheye suggests and handle assigning a default inside the method body.