1 Function Returns

Go to the RMD, PDF, or HTML version of this file. Go back to Python Code Examples Repository (bookdown site) or the pyfan Package (API).

1.1 Function with Multiple Optional Returns

There is a function that is already written, that returns some string value. Without interrupting the existing function, now add an additional return for the function. There is some conditional statement that controls whether the function returns one or two value.

In the example below, if the path contains

Create a testing function:

def get_val(spn_path):
    if 'G:' in spn_path:
        # this returns a tuple of length 2
        return spn_path, 'G:/repos'
    else:
        return spn_path

Call the function with one return, in the two calls below, the first call returns a tuple

# Return tuple
tp_st_return = get_val("G:/Dropbox (UH-ECON)")
# Unpack tuple return
st_path_a, st_path_b = get_val("G:/Dropbox (UH-ECON)")
# Single element return
st_return = get_val("C:/Dropbox (UH-ECON)")
# Print
print(f'{tp_st_return=} and {st_return=}')
## tp_st_return=('G:/Dropbox (UH-ECON)', 'G:/repos') and st_return='C:/Dropbox (UH-ECON)'
print(f'{st_path_a=} and {st_path_b=}')
## st_path_a='G:/Dropbox (UH-ECON)' and st_path_b='G:/repos'
print(f'{isinstance(tp_st_return, str)=}')
## isinstance(tp_st_return, str)=False
print(f'{isinstance(tp_st_return, tuple)=}')
## isinstance(tp_st_return, tuple)=True
print(f'{isinstance(st_return, str)=}')
## isinstance(st_return, str)=True
print(f'{isinstance(st_return, tuple)=}')
## isinstance(st_return, tuple)=False