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
Use the typeof operator to check the type of a variable in TypeScript, e.g. if (typeof myVar === 'string') {} . The typeof operator returns a string that indicates the type of the value and can be used as a type guard in TypeScript.
To get the type of a variable in Python, you can use the built-in type() function. In Python, everything is an object. So, when you use the type() function to print the type of the value stored in a variable to the console, it returns the class type of the object.
Get and print the type of an object: type() type() returns the type of an object. You can use this to get and print the type of a variable and a literal like typeof in other programming languages. The return value of type() is type object such as str or int .
type() returns the type of the object you put in as an argument, and is usually not useful unless compared with a real type (such as type(9) == int ). isinstance() returns a boolean - true or false - based on whether the object is of given type.
This is an old question but it seems none of the answers actually answer the specific question: "(How-to) Determine if Python variable is an instance of a built-in type". Note that it's not "[...] of a specific/given built-in type" but of a.
The proper way to determine if a given object is an instance of a buil-in type/class is to check if the type of the object happens to be defined in the module __builtin__
.
def is_builtin_class_instance(obj): return obj.__class__.__module__ == '__builtin__'
Warning: if obj
is a class and not an instance, no matter if that class is built-in or not, True will be returned since a class is also an object, an instance of type
(i.e. AnyClass.__class__
is type
).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With