There are cases where the input variable of a function can have different forms (string, list, dictionary…). Here is a nice way to list those types within the function signature. The following code also illustrates how to handle those types within the function itself.
from typing import Union
def my_function(input_dir: Union[str, list]) -> str:
if isinstance(input_dir, str):
print("input_dir is a string")
elif isinstance(input_dir, list):
print("input_dir is a list")
print(f"input_dir: {input_dir}")
return "done"
Links
- Original documentation can be found here
- Repository illustrating its use (python101)
- Repository using it (NeutronImagingScripts)
@thanks to Chen Zhang for introducing me this tool.