r/learnpython • u/Emergency-Egg-0230 • 2d 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
View all comments
1
u/Mooball123 2d ago
You can have arguments have default values by using =. In your case
def my_function(argument=None):
if argument is None:
argument = default_dict
It’s generally good practice to also “type hint” an argument to only accept certain types using :
def my_function(argument: dict | None=None):
if argument is None:
argument = default_dict
Here the | means “or”. So the function can only take arguments of type “dict” or “None”. If you know what types are going to make up the keys and values you can also go one step further and do “dict[str, int]”, for dictionaries with strings as keys and integers as values for example. Another example is “list[str]” for a list of strings. Or “tuple[int…]” for a tuple of an unknown amount of integers.
PS. Take note that you don’t assign the default dict as the default value in the def statement. You do this because when you assign a mutable object (an object that can be edited/added too) as the default, python assigns the same object to all calls of that function. So if you later change the object in the code and call the function again it will use the same changed object as the default.