Search code examples
pythonassert

assert isinstance doesn't work as expected with collection types


I wrote this code:

def func(collection_type):
assert isinstance(collection_type,(list,set))
    

then I wrote:

func(collection_type=set)

And I got AssertionError


Solution

  • assert isinstance(collection_type,(list,set)). This will test whether the given instances belongs to (list,set) or not. So try with instances of list or set like this,

    func(collection_type=[1, 2, 3]) or func(collection_type={1, 2, 3}).

    In python all the classes are instances of type class. So if you pass the class itself like func(collection_type=set). It will check for type, since only (list,set) are there, it will raise assertionError.

    If you want to test with a empty set, try func(collection_type=set())