2

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

Yan Khonski
  • 12,225
  • 15
  • 76
  • 114
  • 1
    Check for it being iterable ? https://stackoverflow.com/questions/1952464/in-python-how-do-i-determine-if-an-object-is-iterable – dmitryro Oct 05 '19 at 23:55
  • write your answer, it is acceptable. And what other options? I would like to learn. Also, I would like to have `__len__()` method defined in such container. I am not sure, if iterable has `__len__()` – Yan Khonski Oct 05 '19 at 23:58

1 Answers1

2

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.

dmitryro
  • 3,463
  • 2
  • 20
  • 28