Reputation: 4010
Is there any way to do the following?
def getTables(self, db = self._dbName):
//do stuff with db
return func(db)
I get a "self" is not defined
. I could do this...
def getTables(self, db = None):
if db is None:
db = self._db
//do stuff with db
return func(db)
... but that is just annoying.
Upvotes: 2
Views: 199
Reputation: 1121634
Function signatures are evaluated when the function is defined, not when the function is called.
When the function is being defined there are no instances yet, there isn't even a class yet.
To be precise: the expressions for a class body are executed before the class object is created. The expressions for function defaults are executed before the function object is created. At that point, you cannot create an instance to bind self
to.
As such, using a sentinel (like None
) is really your only option. If db
is never falsey you can simply use:
def getTables(self, db=None):
db = db or self._db
Upvotes: 8
Reputation: 47966
Perhaps this onle-liner version will be slightly less "annoying":
def getTables( self, db = None):
db = self._db if db is None else db
...
You simply can not set a default value for an argument based upon the value of a another argument because the argument you want to base your default value on hasn't been defined yet.
Upvotes: 1