Let say I have a function
def func(data:str):
pass
what i want to make it accept dataframe as well along with string. How can i do? It mean if string passed it accept and if dataframe it also accept that.
CodePudding user response:
import typing
import pandas as pd
def func(data:typing.Union[str, pd.DataFrame]):
pass
or, if you use python 3.10
or newer:
def func(data:str | pd.DataFrame):
print(type(data))
for more information and future reader:
this is type-hinting
and does not do anything about accept or deny any type
even if you specify only one type
. for more strictness and that the function can't accpet any other type
s, you must use raise
:
def func(data):
if type(data) not in [str, pd.DataFrame]:
raise RuntimeError("This is not good")
even this lenient let you to use string
s as type-hinting, for example:
def func(data: "str"):
print(data)
and, also as you can see in first example, you can use any class
for type-hinting, and this is a good practice.