In strictly standard Python, every argument must have a value. Therefore, you cannot simply leave a value "empty" like in some other languages. However, you can achieve the "optional without a value" effect using two common methods:
1. Using None as a Placeholder
This is the standard Pythonic way to make an argument optional without giving it a "real" data value. You set the default to None and then use an if statement to check if the user provided something.
def greet(name=None):
if name is None:
print("Hello, anonymous person!")
else:
print(f"Hello, {name}!")
greet() # Output: Hello, anonymous person!
greet("Carlos") # Output: Hello, Carlos!
In this case, None acts as a signal that "no value was provided."
2. Using Variable-Length Arguments (*args)
If you want an argument to be truly optional and not even define a name for it unless it's sent, you can use *args. This collects any number of extra arguments into a tuple.
def show_items(*args):
if not args:
print("No items provided.")
else:
for item in args:
print(f"Item: {item}")
show_items() # Output: No items provided.
show_items("Apple", "Box") # Output: Item: Apple, Item: Box
If you don't pass anything, args is just an empty tuple.
3. Using Type Hinting (Advanced)
If you are worried about "defaults" because you are thinking about data types, you can use the Optional type hint (from the typing module), but even then, you still usually assign it None in the actual logic.
Summary
While you technically must assign a default value (like None) to make a parameter optional in a standard function definition, None is the universal way to say "this argument exists but has no value yet."
Does that help clarify how to handle "empty" optional inputs?