Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Named parameter with no default?

I know I can create a named parametered python function such as

def t(a=None, b=None):
    return a+b

Then I can call with

 t(b=2, a=5)

However, if both a & b are not optional, then I need to check in the function in runtime, e.g.

def t(a=None, b=None):
    if a is not None and b is not None:
        return a+b
    else:
        raise Exception('Missing a or b')

Is it possible to check in compile time and fail as soon as possible?

e.g.

t(a=3) # raise error
like image 693
Ryan Avatar asked Nov 20 '16 10:11

Ryan


1 Answers

Don't use defaults if the parameters are not optional.

You can still use those parameters as named parameters in the call; all parameters in a Python function are named:

def t(a, b):
    return a+b

t(a=3, b=4)

Note that passing in the wrong count of parameters is always a runtime check, not a compile time check. As a dynamic language, it is impossible to know at compile time what actual object t will be when you call it.

like image 157
Martijn Pieters Avatar answered Sep 28 '22 18:09

Martijn Pieters