If you have a function that needs to return different types in different situations, that's no problem.
For basic types you can simply use the "var" type, for example:
from pyxll import xl_func
@xl_func("int x, str y, float z, int choice: var")
def choose(x, y, z, choice):
if choice == 1:
return x
elif choice == 2:
return y
elif choice == 3
return z
raise ValueError("Choice should be between 1 and 3")
For more complex types, such as pandas DataFrames, you will need to convert the return value to a simpler value that Excel can understand before returning it.
To do that you can use pyxll.get_type_converter. The get_type_converter function can be used to convert from one type to another using PyXLL's type converters.
The following example shows a function that sometimes returns a string and sometimes a pandas DataFrame.
from pyxll import xl_func, get_type_converter
@xl_func("str s, dataframe df, int choice: var", auto_resize=True)
def dataframe_or_string(s, df, choice):
if choice == 1:
return s
elif choice == 2:
df_to_var = get_type_converter("dataframe<index=True>", "var")
return df_to_var(df)
raise ValueError("Choice should be between 1 and 2")