2

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.

7
  • Are these stand-alone functions or methods? Commented Aug 5, 2014 at 15:57
  • You want to set a default value for an argument based on other arguments? Commented Aug 5, 2014 at 15:57
  • the correct way to do it is: def getTables(self, db = None): Commented Aug 5, 2014 at 15:57
  • 5
    Short answer: no. None is the correct default here. self doesn't exist until inside the method. Commented Aug 5, 2014 at 15:58
  • @Dylan - looks to me like you understood my comment :P Commented Aug 5, 2014 at 16:04

2 Answers 2

8

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
Sign up to request clarification or add additional context in comments.

1 Comment

+1 -- a much better answer than mine, since understanding this is important to understanding (for instance) why def foo(bar={}) is Evil And Wrong (sharing a single, mutable {} object, rather than creating a new dict on every call).
1

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.

2 Comments

I just don't want the if statement in general. I want it in the function parameters list
@Dylan - ah yes... but what about what the python interpreter wants? ;)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.