Skip to content
Advertisement

Determine if Python variable is an instance of a built-in type

I need to determine if a given Python variable is an instance of native type: str, int, float, bool, list, dict and so on. Is there elegant way to doing it?

Or is this the only way:

if myvar in (str, int, float, bool):
    # do something

Advertisement

Answer

The best way to achieve this is to collect the types in a list of tuple called primitiveTypes and:

if isinstance(myvar, primitiveTypes): ...

The types module contains collections of all important types which can help to build the list/tuple.

Works since Python 2.2

User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement