+2 votes
2 views
in Python by (3.4k points)
Can someone tell me a easy method to check if a variable is a dictionary, list or anything else? I want to know the object I am getting is of which type.

3 Answers

0 votes
by (2k points)
edited by

You can use _class_ attribute, Look at this example for Ref.

>>> str = "str"
>>> str.__class__
<class 'str'>
>>> w = 4
>>> w.__class__
<class 'int'>
>>> class Test():
...     pass
...
>>> q = Test()
>>> q.__class__
<class '__main__.Test'>

I have checked it in Python 3.3 console, not sure about other versions.

Cheers.

0 votes
by (107k points)

You can do that using type():

>>> a = []

>>> type(a)

<type 'list'>

>>> f = ()

>>> type(f)

<type 'tuple'>

You can use the following video tutorials to clear all your doubts:-

0 votes
by (20.3k points)

To get the type of an object, you can 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

True

>>> type({})

<type 'dict'>

>>> type([])

<type 'list'>

For custom types this will work:

>>> class Test1 (object):

        pass

>>> class Test2 (Test1):

        pass

>>> a = Test1()

>>> b = Test2()

>>> type(a) is Test1

True

>>> type(b) is Test2

True

Note 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

False

To 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)

True

isinstance() 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))

True

Related questions

+2 votes
2 answers
+3 votes
2 answers
0 votes
1 answer
asked Sep 17, 2019 in Python by Sammy (47.8k points)
Welcome to Intellipaat Community. Get your technical queries answered by top developers !


Categories

...