Peaser
Peaser

Reputation: 575

How to reference first argument of function from second? (python 2.7)

Let's say I have a generic function like this:

def do_thing(arg1, default=len(arg1)): 

assuming arg1 is this string: "hello, world!", the default would be 13. if arg1 was "oh yeah", default would be 7.

Just assume that since the default is a default, I can change it by doing do_thing("hello", 1) for example.

from that point, I get a traceback saying that arg1 is not defined. How can I make this work?

Upvotes: 1

Views: 686

Answers (1)

Ignacio Vazquez-Abrams
Ignacio Vazquez-Abrams

Reputation: 798546

Like so:

def do_thing(arg1, default=None):
  if default is None:
    default = len(arg1)
   ...

Or if None is a possible valid value, create a new sentinel object:

_nolen = object()

def do_thing(arg1, default=_nolen):
  if default is _nolen:
    default = len(arg1)
   ...

Upvotes: 4

Related Questions