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):
...


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

About Me

My name is Tasos Sangiotis and I work at Arpedon, an engineering company. This website is a collection of posts, essays and photos. They are mainly about travel, food and technical stuff. Occasionally I shoot photos. They are mostly on Instagram. If you choose to wander this wasteland do so with caution. Consider this your final warning. To contact me use [email protected]

Newsletter