r/learnpython • u/Emergency-Egg-0230 • 6h 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
3
Upvotes
3
u/kilkil 3h ago
When you define a function in Python, you can specify default values for its arguments (these are called "default arguments").
for example, say I have a greeting function that says hello to people, given a name:
now let's say I want to change this function, so that if I don't provide a name, it will just say "hello world" by default. I can do this by specifying a default value for the
nameargument, like so:now if I call
greet()without any arguments, it will print "hello world!".the same can be achieved in other ways. for example, the default value could be
None(Python's way of representing a value that is completely empty/meaningless), and I could have some logic that checks whether the argument was set toNoneand decide what do print based on that:Or I could do a mix of the two, and if I detect that the value is
NoneI can assign a replacement value within the function itself:Of these 3 approaches, the 1st one is the simplest and looks the nicest. Unfortunately, as the documentation linked above states, if you use the 1st one for any mutable object (like your own usecase, which involves a dictionary), the same object will effectively continue being reused and modified across every time that function is called (it won't "reset" between function calls, the way it would if it was an int or a string, like in my example).
To avoid this people usually end up using the 3rd approach, because it looks almost as clean as the 1st one, but lets you avoid dealing with that whole headache.
so in your specific case: