2

Let say I have a function

def func(data:str):  
   pass

what I intend to make is to make sure it accepts dataframe as well along with string. How can I do it? I mean if a string is passed it should accept and if dataframe is passed, it also accept that.

1 Answer 1

3
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 types, 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 strings 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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.