John
John

Reputation: 107

How to check for no argument sent to a function in Python

So, within a function I would like to test for the presence of an argument the function is expecting. If there is an argument, do this, if no argument is sent form the calling programme and none is received into the function do that.

def do_something(calculate):
    if calculate == something expected:
        do this
    elif calculate not sent to function:
        do that 

So what would be the logical test/expression I'd need to check for to test if no argument was received into the function please?

Upvotes: 2

Views: 17513

Answers (2)

Hielke Walinga
Hielke Walinga

Reputation: 2845

Use a sentinel.

SENTINEL = object()
def do_something(calculate=SENTINEL):
    if calculate is SENTINEL:
        # do that
        return 'Whatever'
    if calculate == "something expected":
        # do this
    return 'Whateverelse'

This way you can also distinguish between sending None to the function.

Upvotes: 0

han solo
han solo

Reputation: 6590

You could set the argument as None, and check if it is passed or not,

def do_something(calculate=None):
    if calculate is None:
        # do that
        return 'Whatever'
    if calculate == "something expected":
        # do this
    return 'Whateverelse'

Upvotes: 9

Related Questions