Reputation: 9654
I have a function process
. If attempts to retrieve one of name, address, phone from the input data (in that order) using their own functions which either return the appropriate value or return ''. If all return '' then return the data as it is.
Following is the code, is there a better way to avoid duplicating function invocations in both if check and return?
def process(data):
if get_name(data):
return get_name(data)
elif get_address(data):
return get_address(data)
elif get_phone(data):
return get_phone(data)
return data
Upvotes: 0
Views: 53
Reputation: 2303
You can use walrus operator :=
if you use python 3.8+
def process(data):
if name:=get_name(data):
return name
elif address := get_address(data):
return address
elif phone := get_phone(data):
return phone
return data
Upvotes: 1
Reputation: 2182
As per your code logic, you can write it like this. The or
sequence will return the first positive data, in other words the data that is truthy
.
def process(data):
name = get_name(data)
address = get_address(data)
phone = get_phone(data):
return name or address or phone or data
Upvotes: 2