Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why there is no UserSet class defined in Python?

Why python does not provide UserSetclass to extend and define user defined Set. It does provide UserDict,UserList, UserString but no UserSet.

I'm referring to Python Documentation

like image 639
Jyotirup Avatar asked Jul 21 '19 11:07

Jyotirup


1 Answers

PEP 3108 provides some insight into why no UserSet or similar implementations were added in similar fashion to UserDict and the like.

Guido pronounced that "silly old stuff" is to be deleted from the stdlib for Py3K. This is open-ended on purpose. Each module to be removed needs to have a justification as to why it should no longer be distributed with Python.

UserDict, UserList, and UserString are all listed in the "Obsolete" section of PEP 3108 with the following reason noted and an indication that they were moved to the collections module.

Not as useful since types can be a superclass

Given that they were considered "obsolete", it is unsurprising that similar classes were not implemented for other types such as sets.

Since types can be superclasses and abstract base classes provide a reasonable alternative for creating subclasses of various set, sequence, mapping, and other types with significant changes that would be difficult to implement by extending the built-in types themselves, it seems unnecessary to include these "starter" classes for each and every type beyond what is already provided in collections.abc.

Following is a very basic implementation of UserSet with a data attribute that stores the contents of the class in a real set (similar to the approach taken with UserDict and the like). While it might be useful to you to have such an implementation included in the standard library, it is not terribly difficult to implement yourself (and if everything that was potentially "useful" to someone was included in the standard library, Python would become awfully bloated).

from collections.abc import Hashable, MutableSet

class UserSet(Hashable, MutableSet):
    __hash__ = MutableSet._hash

    def __init__(self, iterable=()):
        self.data = set(iterable)

    def __contains__(self, value):
        return value in self.data

    def __iter__(self):
        return iter(self.data)

    def __len__(self):
        return len(self.data)

    def __repr__(self):
        return repr(self.data)

    def add(self, item):
        self.data.add(item)

    def discard(self, item):
        self.data.discard(item)


s = UserSet([1,1,2,3])
print(s)
# {1, 2, 3}
like image 180
benvc Avatar answered Nov 20 '22 13:11

benvc