0

I have a function func(a=1, b=2, c=3). Different things happen if all arguments are left as default and if any given two are user-specified, even if the user coincidentally specifies values to be default. Eg:

  • User enters func() -> thing 1 happens
  • User enters func(a=42, c=191) -> thing 2 happens
  • User enters func(a=1, c=3) -> thing 2 also happens (even though user-specified values happen to be default).

So in order to decide whether to proceed to thing 1 or thing 2, I can't just compare argument values to default. I need to find out which arguments are user-specified, regardless of their values.

(I've also considered making the defaults values nonsense, like NaN or Inf, then checking which values were user-specified by comparing them to NaN or Inf, and then defining them as a=1, b=2, c=3 if need be. That doesn't work because numpy is not imported and doesn't otherwise need to be, so I don't have access to NaN or Inf. But maybe I'm missing something?)

So: is there a way to find out which parameters were user-specified and/or which were left as default, regardless of their actual value?

1 Answers1

2

(I've also considered making the defaults values nonsense, like NaN or Inf, then checking which values were user-specified ...

That is typically exactly how you would handle this. In the simple case, you would use None as your sentinel value:

def func(a=None, b=None, c=None):
  if a is None:
      print('using default value')
      a = 1
  else:
      print('user specified a value')

But if None is a valid value, you can use some other object. For example:

NOT_SET_BY_CALLER = object()


def func(a=NOT_SET_BY_CALLER, b=NOT_SET_BY_CALLER, c=NOT_SET_BY_CALLER):
  if a is NOT_SET_BY_CALLER:
      print('using default value')
      a = 1
  else:
      print('user specified a value')
larsks
  • 277,717
  • 41
  • 399
  • 399