Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python "self" is not defined in function arguments list

Tags:

python

self

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.

like image 524
dylnmc Avatar asked Dec 21 '25 02:12

dylnmc


2 Answers

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
like image 169
Martijn Pieters Avatar answered Dec 22 '25 16:12

Martijn Pieters


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.

like image 22
Lix Avatar answered Dec 22 '25 17:12

Lix