Tasos Sangiotis

June 15, 2022

Python instance check

Python being a dynamically typed (🦆) language lets you set whatever you want on a variable. Is it a string now and later a float. No worries now, we will worry when we have to.

This is great when you want to set something but dealing with complex, not necessarily cohesive datasets gets you in trouble.

Suppose you don't care about that and you just want to have an endless page of if statements this is what you can do:

if isinstance(value, (int, float, complex)) and not isinstance(value, bool):
    ...


The bool check provides assurance that True and False statements are not delivered as 1 and 0

It is better to do this though but you add an import:

import numbers

if isinstance(value, numbers.Number) and not isinstance(value, bool):
    ...

About Tasos Sangiotis

An electrical engineer at Arpedon with a broad range of interests from electrical, to mechanical & automation. Photoshooter, runner and a fan of good food & alcohol. You can also find me on Twitter, on LinkedIn, and on Instagram. If you choose to wander this wasteland do so with caution. Consider this your final warning.