B L G
B L G

Reputation: 1

How do I check if something is a dataframe?

This seems like it should be simple.... but...

I am trying to write a function where I first want to make sure that what has been passed into it is actually a dataframe. So something like:

def function(df1,arg2,arg2):
    if isinstance(df1,pd.DataFrame)==False:
        raise TypeError("Sorry, but data needs to be a DataFrame")

Where I have set pd as short for pandas.

Is this even a valid way of doing things? Or if not what should I be doing to make sure df1 being passed is a dataframe?

I have seen a few similar questions here, but nothing quite the same.

Upvotes: 0

Views: 74

Answers (1)

BoppreH
BoppreH

Reputation: 10173

Yes, this sounds correct. Though in Python the approach is to usually either:

  • Not check the type, and handle the runtime errors if the object type is incompatible. This is called duck typing, and has the advantage of working with similar-but-not-identical types, like DataFrames from other libraries.
  • Add type annotations and check them with an external tool like mypy. Note that by default Python will ignore type annotations!

Your approach is a fine middle-way, and it's correctly using isinstance so it should be compatible with subclasses too.

Upvotes: 0

Related Questions