Python: multiple possible values for function arguments
-
29-09-2019 - |
Question
I've inherited some Python code that looks like this:
name = 'London'
code = '0.1'
notes = 'Capital of England'
ev = model.City(key=key, code=code, name=name or code, notes=notes)
In the spirit of learning, I'd like to know what's going on with the name or code
argument. Is this saying 'Use name
if it's not null, otherwise use code
'?
And what is the technical term for supplying multiple possible arguments like this, so I can read up on it in the Python docs?
Thanks!
Solution
Almost. It says use name if it does not evaluate to false. Things that evaluate to false include, but are not limited to:
False
- empty sequences (
(), [], ""
) - empty mappings (
{}
) - 0
None
Edit Added the link provided by SilentGhost in his comment to the answer.
OTHER TIPS
In python, the or
operator returns the first operand, unless it evaluates to false, in which case it returns the second operand. In effect this will use name
, with a default fallback of code
if name
is not specified.
Fire up a Python console:
>>> name = None
>>> code = 0.1
>>> name or code
0.10000000000000001
In case name evaluates to false the expression will evaluate to code. Otherwise name will be used.
Correct, that idiom take the first value that evaluates to True (generally not None). Use with care since valid values (like zero) may inadvertently be forsaken. A safer approach is something like:
if name is not None:
# use name
or
name if name is not None else code
You've it it roughly correct, but 'null' is not precisely what decides. Basically anything that will evaluate to false (0, false, empty string '') will cause the second string to be displayed instead of the first. 'x or y' in this sense is kind of equivalent to:
if x: x
else: y
Some console play:
x = ''
y = 'roar'
x or y
-'roar'
x = 'arf'
x or y
-'arf'
x = False
x or y
-'roar'
In the spirit of learning, I'd like to know what's going on with the name or code argument. Is this saying 'Use name if it's not null, otherwise use code'?
yes basically but Null in python can mean more than one thing (empty string , none ..)
like in your case:
>>> name = 'London'
>>> code = 0.1
>>> name or code
'London'
>>> name = ''
>>> code = 0.1
>>> name or code
0.1000....
but it weird thew that a function parameter can be integer sometimes and a string other times.
Hope this can help :=)