You could use the or operator:

return x or "default"

Note that this also returns "default" if x is any falsy value, including an empty list, 0, empty string, or even datetime.time(0) (midnight).


Python 3.8+ update: bool(datetime.time(0)) now resolves to True. This was resolved with issue13936. Other "empty" values are still considered "falsy" as expected.

Answer from starhusker on Stack Overflow
🌐
Bobby Hadz
bobbyhadz.com › blog › python-return-default-value-if-none
How to Return a default value if None in Python | bobbyhadz
Use a conditional expression to return a default value if None in Python, e.g. `return "default value" if my_var is None else my_var`.
Discussions

A way to have the default value for a parameter as the default of another function: the Default singleton - Ideas - Discussions on Python.org
Often, I use the defaults of another function in my new function or class. For example: def mysorted(it, key=None, reversed=False): # some code return sorted(it, key=key, reversed=reversed) The majority of times I want to simply adhere to the sign of the original function. More on discuss.python.org
🌐 discuss.python.org
1
September 7, 2022
Return default value if the input is `None`
Initial Checks I have searched Google & GitHub for similar requests and couldn't find anything I have read and followed the docs and still think this feature is missing Description Let'... More on github.com
🌐 github.com
37
March 7, 2024
how to print the default value if argument is None in python - Stack Overflow
I'm expecting the answers by without using much more codes like 'name = name if name is not None else some_default_value' Thanks in advance! ... Instead of the default argument you can have a check inside method and assign default value. More on stackoverflow.com
🌐 stackoverflow.com
Use default argument if argument is None on python method call - Stack Overflow
Kind of a strange question, but I stumbled upon this one while coding. This is my code EDIT: I added classes to make my structure clearer class Hidden(object): def x(self, aa, bb="John Doe")... More on stackoverflow.com
🌐 stackoverflow.com
🌐
Reddit
reddit.com › r/learnpython › type hinting weirdness with "none" as default value when i need to default to class' initial value or get a value from user
r/learnpython on Reddit: Type hinting weirdness with "None" as default value when I need to default to class' initial value or get a value from user
March 29, 2023 -

Sorry for the confusing title.

I have been adding some type hinting into my code and noticed that if I have something like:

def create(self, a: int = None) -> None
a = a or self.a

Where I would like to have the user either give a as an int or just skip it and the function will default to the class' initial value for a. This works just fine but this shows in the IDE as create(self, a: int | None = None) -> None which looks like None is a valid value for a, even though that is not what I am looking for.

Then if I have an artificial case like:

def create(self, a: int = 'test') -> None
...

Which then shows up as create(self, a: int = 'test') -> None which looks weird but at least it doesn't explicitly imply that str is a valid parameter.

So I guess two questions: what makes None special? And, is this the way to use type hinting when I need to default to class' initial value or get an argument from user?

🌐
Python.org
discuss.python.org › ideas
A way to have the default value for a parameter as the default of another function: the Default singleton - Ideas - Discussions on Python.org
September 7, 2022 - Often, I use the defaults of another function in my new function or class. For example: def mysorted(it, key=None, reversed=False): # some code return sorted(it, key=key, reversed=reversed) The majority of time…
🌐
GeeksforGeeks
geeksforgeeks.org › default-arguments-in-python
Default arguments in Python - GeeksforGeeks
Assign the default value as none and then check in the function if the expected list or dictionary argument is none or not.
Published: September 11, 2024
🌐
Tutorial Reference
tutorialreference.com › python › examples › faq › python-how-to-return-a-default-value-if-none
How to Handle None and Set Default Values in Python | Tutorial Reference
In Python, None represents the absence of a value. It's common to need to provide a default value when a variable might be None. This guide explores various methods for handling this, including conditional expressions (the ternary operator), the or operator, and best practices for function arguments. A conditional expression (often called a "ternary operator") provides a concise way to assign a default value if a variable is None:
🌐
GitHub
github.com › pydantic › pydantic › issues › 8972
Return default value if the input is `None` · Issue #8972 · pydantic/pydantic
March 7, 2024 - >>> from pydantic import BaseModel >>> >>> >>> class Foo(BaseModel): ... bar: list[int] | None = [0,1,2] ... baz: list[str] | None = ["a", "b", "c"] ... >>> Foo() Foo(bar=[0, 1, 2], baz=['a', 'b', 'c']) >>> Foo(bar=[1,2], baz=["a","b"]) Foo(bar=[1, 2], baz=['a', 'b']) >>> Foo(bar=None, baz=None) # Explicitly pass `None` Foo(bar=None, baz=None) # Current Behavior >>> Foo(bar=None, baz=None) # Explicitly pass `None` Foo(bar=[0, 1, 2], baz=['a', 'b', 'c']) # Feature request: Return default value if the input is `None`, possibly a model setting in ConfigDict?
Author: pydantic
🌐
APXML
apxml.com › courses › python-for-beginners › chapter-5-building-blocks-functions › python-default-arguments
Python Default Argument Values | Optional Parameters
The conventional way to handle mutable defaults is to use None as the default value and then create a new mutable object inside the function if the parameter is None.
Find elsewhere
🌐
Real Python
realpython.com › lessons › none-default-parameter
None as a Default Parameter (Video) – Real Python
Now let’s see what happens if I add None to it. 04:47 And you see that what happens this time is it accepted None as an input value and it appended it to the list, so that was working. 04:56 So, the key things to remember here are that you can use None as a default parameter when using mutable data types would result in strange things happening, or unwanted things happening, and also that if you need to be able to add None as a valid input to something, then you can create a class that you can use as a signal not to accept an input.
Published: July 29, 2020
🌐
Note.nkmk.me
note.nkmk.me › home › python
Default Parameter Values in Python Functions | note.nkmk.me
May 12, 2025 - To avoid this behavior, you can use None as the default value and create a new object inside the function. This ensures that a new object is created each time the function is called without the argument.
🌐
Medium
medium.com › opsops › using-default-value-if-string-is-empty-4333e0abc9b3
Using default value if string is empty | by George Shuklin | OpsOps | Medium
June 5, 2020 - If bar is empty, you want to use other value (f.e. string “nothing”). ... But there is a much better way! ... This trick uses python or operator, which return either first value, or second, depending on the truthiness of the first expression. Empty string, empty set, empty list, empty dict, None, all of them are cast to ‘false’, therefore, or returns second expression.
🌐
Reddit
reddit.com › r/learnpython › default value for string parameter, empty string or none?
r/learnpython on Reddit: Default value for string parameter, empty string or None?
February 19, 2022 -

Consider the following class:

class Team:
    def __init__(self, team_members, the_captain):
        ...

Here team_members is a list of strings and the_captain is a string. Now if the_captain is not passed to the constructor, team captain will be selected randomly from team members, otherwise team captain will be the_captain.

I want to set a default value for the_captain, What do you recommend for the default value, None or empty string? In other words which of the following constructor definitions do you think is better?

1

class Team:
    def __init__(self, team_members, the_captain=None):
        ...

2

class Team:
    def __init__(self, team_members, the_captain=""):
        ...

Thanks

🌐
Quantifiedcode
docs.quantifiedcode.com › python-anti-patterns › correctness › not_using_get_to_return_a_default_value_from_a_dictionary.html
Not using get() to return a default value from a dict — Python Anti-Patterns documentation
While there is nothing wrong this, ... the default value specified as the second argument to get() is returned. Note that the default value defaults to None if a second argument is not provided....
🌐
Real Python
realpython.com › python-optional-arguments
Using Python Optional Arguments When Defining Functions – Real Python
July 19, 2026 - If you place a parameter with a default value before one without, then Python raises a SyntaxError. Required parameters must always come before optional ones. When should you use None as a default value instead of a mutable object?Show/Hide
🌐
Real Python
realpython.com › lessons › default-values-for-variables
Default Values for Variables (Video) – Real Python
01:57 On the other hand, if they didn’t provide a value for a, we somehow indicate that with an empty string (""). And then when we say y = a or default, a evaluates to be False, so whatever is in default is returned. 02:17 In this case, we’ll have our workweek beginning on 'Sunday'. Become a Member to join the conversation. ... Get a Python Cheat Sheet (PDF) and learn the basics of Python, like working with data types, dictionaries, lists, and Python functions:
Published: May 18, 2021