Reputation: 3336
a = ['a', 'b', 'c', 'd']
b = set(a)
print isinstance(a, types.ListType)
print isinstance(b, types.ListType)
The result shows that b is not of types.ListType. However, there is no 'SetType' in Python. So what is the type 'XXXType' so that isinstance(b, types.XXXType) is True?
Upvotes: 4
Views: 5912
Reputation: 1121446
Use isinstance(b, set)
.
The types
references to built-in types are just there for convenience* and are otherwise deprecated (they have been removed from the Python 3.x version of the types
module). As such set
was never added.
For example, types.ListType
is just an alias for list
:
>>> import types
>>> types.ListType is list
True
>>> isinstance([1, 2, 3], list)
True
If you must have a SetType
reference in the types
module, simply add the alias yourself:
types.SetType = set
If you are looking for an abstract base class for the basic container type, use the collections
module ABCs; these signal what methods a type support and checking against these types can let you detect a wider set of types that support specific operations (rather than be an instance of just the list
and set
types):
>>> from collections import Set, MutableSequence
>>> isinstance([1, 2, 3], MutableSequence)
True
>>> isinstance({1, 2, 3}, Set)
True
* History lesson: Once upon a time, the built-in types like int
and list
were not really classes, and the built-in names int()
and list()
were simply functions to convert to the built-in types. That means that the names were simply not the same object as types.IntType
and types.ListType
and you had to use the types
module to be able to use isinstance()
on a list object. That time is now long, long behind us, and the role of the types
module has changed.
Upvotes: 13