r/learnpython • • 1d ago

Function without argument

Ive got a function that takes a dictionary as an argument.
Now Id like to program it so when the function is called without any argument, instead of an error message it prints something custom (a dictionary for example).

Any help is appreciated :D

1 Upvotes

16 comments sorted by

View all comments

32

u/atarivcs 1d ago

Assign a default value for the function parameter:

def myfunction(mydict=None):
    if mydict is None:
        # the caller did not pass an argument
        # so handle that however you want
    else:
        # the caller did pass an argument
        # so handle that however you want

7

u/Adbelhak_Unsicker 1d ago

Simple and avoids the mutable default argument issue, cant go wrong with this approach

3

u/pdpi 1d ago

Probably out of scope for OP, but as of Python 3.15, you’re better off using a sentinel value instead of None, so you can identify when the user calls myfunction(None).

8

u/JanEric1 1d ago

No, you should only use sentinel if None is an actual value you might want to normally process in your function but still need to identify if the user passed an argument.

If you function wouldn't work with None there passed explicitly then None is the better and simpler default.

5

u/atarivcs 1d ago

OP says the argument is supposed to be a dict, so I would say myfunction() and myfunction(None) probably should be handled the same way.