r/learnpython • • 13h 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

2 Upvotes

14 comments sorted by

31

u/atarivcs 13h 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

5

u/Adbelhak_Unsicker 12h ago

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

3

u/pdpi 10h 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).

6

u/JanEric1 5h 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 10h 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.

6

u/mrswats 13h ago

What have you tried? What's not working? Show us some code so we can help you with it.

But also, you could check the documentation and see if you can figure it out yourself.

3

u/kilkil 10h 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:

def greet(name):
    print(f"hello {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 name argument, like so:

def greet(name="world"):
    print(f"hello {name}!")

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 to None and decide what do print based on that:

def greet(name=None):
    if name is None:
        print("hello world!")
    else:
        print("hello {name}!")

Or I could do a mix of the two, and if I detect that the value is None I can assign a replacement value within the function itself:

def greet(name=None):
    if name is None:
        name = "world"
    print(f"hello {name}!")

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:

def myfunction(my_dict=None):
    if my_dict is None:
        # handle default argument, assign as needed
    ...
    # rest of function proceeds like normal

1

u/stepback269 8h ago

Yes. I was going to say the same thing.
Use a keyword/ default value parameter such as:
def my_callable(Default_dict = [1: "one", 2:"two", 3: "three"]):
return None

1

u/Mooball123 9h 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.

1

u/Classic-Rate-5104 4h ago

Many answers suggest function(argument=None) and then testing for "argument is None". Why not simply function(argument={}) or whatever default you want?

-6

u/ninhaomah 13h ago

Use normal language.

Example : I want McDonald's breakfast. If I didn't specify the drink , would it DEFAULT to hot coffee ?

2

u/csabinho 12h ago

It's rather "I want a McDonalds burger: if I didn't specify my extras, it would be prepared with the default ingredients." And your extras are in a data structure that is empty by default.

3

u/atarivcs 13h ago

This isn't a good example, because if the order-taker is doing their job properly, they will certainly ask what drink you want.

Even if they say "Do you want coffee to drink?", that is still asking.

1

u/LeonardUnger 12h ago

The function is asking, as it's checking for the presence of an argument.