Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to properly check object types in Python?

Problem: I have to check that the a returned value is a Python dictionary.

Q1. Which of these options is the proper way to do this?

type(x) == dict

type(x) == type(dict)

isinstance(d, dict)

Then there are the other variants using is operator instead of ==.

Q2. Many people say that checking the type of an object is generally a bad practice, but regarding to my initial problem, do I have any other choice?

like image 220
Paolo Avatar asked Mar 15 '26 23:03

Paolo


1 Answers

Q1. Which of these options is the proper way to do this?

Don't waste time on type checking.

It's error-prone because it's based on assumptions.

Q2. ... do I have any other choice?

Yes do this.

try:
    x.the_dict_operation()
except TypeError:
    # x was not the expected type for the operation
    raise # or whatever.

In most cases, this amounts to "do nothing".

Just write the code. If "somehow" a malicious sociopath uses the wrong type, it will just crash like it's supposed to.

like image 105
S.Lott Avatar answered Mar 17 '26 14:03

S.Lott