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.
A way to have the default value for a parameter as the default of another function: the Default singleton - Ideas - Discussions on Python.org
Return default value if the input is `None`
how to print the default value if argument is None in python - Stack Overflow
Use default argument if argument is None on python method call - Stack Overflow
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?
Does this work for you?
def f(name):
print(name or 'Hello Guest')
def A(name=None):
f(name)
A()
Out: "Hello Guest"
A("Hello World")
Out: "Hello World"
If the name variable is being used multiple times in the function, you could just reassign it in the beginning of the function. name = name or "Hello Guest"
The best way to do this will be to use a shared default:
DEFAULT_NAME = "Hello Guest"
def f(name=DEFAULT_NAME):
print(name)
def A(name=DEFAULT_NAME):
f(name)
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
Python 3:
inp = int(input('Enter the inputs: ').strip() or "42")
Python 2:
inp = int(raw_input('Enter the inputs: ').strip() or "42")
How does it work?
If nothing was entered then input/raw_input returns empty string. Empty string in Python is False, bool("") -> False. Operator or returns first truthy value, which in this case is "42".
This is not sophisticated input validation. It's slightly more robust with the addition of .strip(). That handles the possibility of the user entering spaces or other whitespace, which then would be True.
One way is:
default = 0.025
input = raw_input("Enter the inputs : ")
if not input:
input = default
Another way can be:
input = raw_input("Number: ") or 0.025
Same applies for Python 3, but using input():
ip = input("Ip Address: ") or "127.0.0.1"
for message in d.get('messages') or ():
do_something()
getreturnsNoneby default for missing keys.a or bevaluates tobwhenbool(a) == False. An empty list andNoneare examples of values that are false in a boolean context.- Note that you cannot use this trick if you intend to modify the possibly empty list that is already in the dict. I'm using
()instead of[]to guard against such mistakes. Also, CPython caches the empty tuple, so using it is slightly faster than constructing an empty list.
You have to check for the existence of 'messages' AND the content of 'messages'. It's the same thing you have, but I would write it as:
if 'messages' in d and d['messages'] is not None:
for m in d['messages']:
do_something(m)