Ohumeronen
Ohumeronen

Reputation: 2086

Force function caller decide which default value is used

Lets say I have the following function:

def myFun(a=None, b=None):
    print a, b

Now I call the function:

myFun("hi") # Case 1
>>>hi None

myFun(b="hi") # Case 2
>>>None hi

myFun(a="hi") # Case 3
>>>hi None

Is there a way to throw an exception if the function caller did not decide which variable the value "hi" is assigned to? That means I would like to have an exception in the 1st case but not in the 2nd and 3rd case. I use python 2.7.

Upvotes: 1

Views: 57

Answers (3)

AbrahamB
AbrahamB

Reputation: 1418

You can actually allow the user to provide any arguments they'd like by using **kwargs.

def myFun(**kwargs):
    print kwargs[a]
    print kwargs[b]

This will cause an error if a or b aren't defined, but they're not very helpful.

You can make your own errors by checking if the value exists. For example:

def myFun(**kwargs):
  if not kwargs.get(a):
    raise Exception('a is not here!')
  if not kwargs.get(b):
    raise Exception ('b is not here!')
  print kwargs[a], kwargs[b]

Upvotes: 1

unutbu
unutbu

Reputation: 879113

In Python3 you can specify keyword-only arguments:

def myFun(*, a=None, b=None):
    print(a, b)

myFun('hi')

raises

TypeError: myFun() takes 0 positional arguments but 1 was given

In Python2, as Ricardo Silveira points out you could use **kwargs to force all arguments to be keyword arguments.

def myFun(**kwargs):
    a, b = kwargs.get('a'), kwargs.get('b')
    print(a, b)

myFun('hi')
# TypeError: myFun() takes exactly 0 arguments (1 given)

Upvotes: 5

Ricardo Silveira
Ricardo Silveira

Reputation: 1243

def my_fun(**kwargs):
    a = kwargs.get("a", None)
    b = kwargs.get("b", None)
    # have your code here...

Then: my_fun("hi") shouldn't work...

Upvotes: 2

Related Questions