Yan Khonski
Yan Khonski

Reputation: 13113

Common super class for set, list, SortedSet and other containers in python

I have a set set(1, 2, 3, 4, 5), list [1, 2, 3, 4], sorted set SortedSet(5, 2, 3). I would like to write a function which works similar to all the types above, for example calculate average, or other stuff. I want my function to be safe. In Java there is Collection interface, common for all standard Java containers.

from sortedcontainers import SortedSet


def is_collection(some_collection):
    return isinstance(some_collection, set) or isinstance(some_collection, list) or isinstance(some_collection, SortedSet)


def calculate_average(some_collection):
    if is_collection(some_collection):
        sum = 0
        size = some_collection.__len__()
        for item in some_collection:
            sum = sum + item

        return sum / size

    return 0

Upvotes: 3

Views: 872

Answers (1)

dmitryro
dmitryro

Reputation: 3516

In Python set, SortedSet and list are collections that are iterable, so you can just check

from collections.abc import Iterable

def is_collection(some_collection):
    return isinstance(some_collection, Iterable) 

That should work for all of your collections, as all of them have __len__() method that can be used.

Upvotes: 3

Related Questions