patternpythonCritical
Determine the type of an object?
Viewed 0 times
determinetypeobjectthe
Problem
Is there a simple way to determine if a variable is a list, dictionary, or something else?
Solution
There are two built-in functions that help you identify the type of an object. You can use
To get the actual type of an object, you use the built-in
This of course also works for custom types:
Note that
To cover that, you should use the
The second parameter of
type() if you need the exact type of an object, and isinstance() to check an object’s type against something. Usually, you want to use isinstance() most of the times since it is very robust and also supports type inheritance.To get the actual type of an object, you use the built-in
type() function. Passing an object as the only parameter will return the type object of that object:>>> type([]) is list
True
>>> type({}) is dict
True
>>> type('') is str
True
>>> type(0) is int
TrueThis of course also works for custom types:
>>> class Test1 (object):
pass
>>> class Test2 (Test1):
pass
>>> a = Test1()
>>> b = Test2()
>>> type(a) is Test1
True
>>> type(b) is Test2
TrueNote that
type() will only return the immediate type of the object, but won’t be able to tell you about type inheritance.>>> type(b) is Test1
FalseTo cover that, you should use the
isinstance function. This of course also works for built-in types:>>> isinstance(b, Test1)
True
>>> isinstance(b, Test2)
True
>>> isinstance(a, Test1)
True
>>> isinstance(a, Test2)
False
>>> isinstance([], list)
True
>>> isinstance({}, dict)
Trueisinstance() is usually the preferred way to ensure the type of an object because it will also accept derived types. So unless you actually need the type object (for whatever reason), using isinstance() is preferred over type().The second parameter of
isinstance() also accepts a tuple of types, so it’s possible to check for multiple types at once. isinstance will then return true, if the object is of any of those types:>>> isinstance([], (tuple, list, set))
TrueCode Snippets
>>> type([]) is list
True
>>> type({}) is dict
True
>>> type('') is str
True
>>> type(0) is int
True>>> class Test1 (object):
pass
>>> class Test2 (Test1):
pass
>>> a = Test1()
>>> b = Test2()
>>> type(a) is Test1
True
>>> type(b) is Test2
True>>> type(b) is Test1
False>>> isinstance(b, Test1)
True
>>> isinstance(b, Test2)
True
>>> isinstance(a, Test1)
True
>>> isinstance(a, Test2)
False
>>> isinstance([], list)
True
>>> isinstance({}, dict)
True>>> isinstance([], (tuple, list, set))
TrueContext
Stack Overflow Q#2225038, score: 2398
Revisions (0)
No revisions yet.