r/learnpython • • 6d 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

1

u/Sufficient-Tale6131 6d ago

To add to the question further down about why people write argument=None instead of argument={}: the default value is evaluated once, when the def line runs, not each time the function is called. So every call that relies on the default shares the same dict object, and if the function ever modifies it (adds a key, pops something), that change is still there on the next call.

Quick way to see it with a list: def add(item, bucket=[]): bucket.append(item); return bucket. Calling add(1) returns [1], then add(2) returns [1, 2], not [2].

That's why the usual pattern is a None default plus a check inside the function (if d is None: d = {...}), which builds a fresh dict on every call. If your function only reads the dict and never changes it, a literal default works, but the None version is the habit that never bites you.

For what you originally asked (print something custom when it's called with no argument), the same check works: if d is None, print your message and return early, or fall back to a default dict.