c z
c z

Reputation: 8967

Python: Extract element from set

I have a class:

class MyClass:
    def__init__( self, name : str ) -> None:
        self.__name : str = name
        self.extra : object = None

    def __eq__( self, other : object ) -> bool:
        if not isinstance( other, MyClass ):
            return False

        return self.__name == other.__name

    def __hash__( self ) -> int:
        return hash( self.__name )

Thus __name is immutable and two MyClasses are equal if they share the same __name.

I have a set defined thus:

eggs = MyClass( "eggs" )
beans = MyClass( "beans" )
spam = MyClass( "spam" )
c.extra = "spam spam spam"
my_set : Set[MyClass] = { eggs, beans, spam }

I can test if spam is in my set:

has_spam : bool = MyClass( "spam" ) in my_set 

But how to I get "spam.extra" by the name? I could use a dict, but this requires duplicating the name property, or I could iterate, but this seems wasteful.

Upvotes: 1

Views: 1135

Answers (1)

ash
ash

Reputation: 5529

There's no way to do what you want with a set that I know of (short of iterating over the whole thing). As I understand it, the only way to get anything out of a set is to iterate over it or use set.pop, which gets you an arbitrary element of the set.

You could use a dictionary to map what you've called __name to extra (and avoid using any custom class), i.e.

my_set = {"eggs": "some extra data", "beans": None, "spam": None}

This seems like exactly the case where you would want to use a dictionary, unless there are more requirements you haven't mentioned.

Upvotes: 1

Related Questions