'Revert to default function argument value when passing from dict with missing key
Suppose I have a function with a default argument value set in the definition, like this:
def foo(a=1):
print(a)
The input data comes from a dictionary which sometimes does or doesn't have the key. I want to have the default value set when the key is not present in the dictionary I am querying. So far I tried to solve it using the .get function, but that's not working as expected because it returns None if the key is missing:
dictionary_a={a:10, b: 100, c: 42}
dictionary_b={b: 100, c: 42}
foo(dictionary_a.get("a"))
> 10
foo(dictionary_b.get("a"))
> None
Querying it like dictionary["a"] also doesn't work because if the key is missing there is an error. How can I make this work as intended?
Solution 1:[1]
Try setting all default parameters to None and change it inside the function.
def foo(a=None, b=None):
if a is None:
a = 1
if b is None:
b = 2
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Aishwarya Patange |
