#πŸ”’ Unexpected behavior with custom Vec2 class in sets

21 messages Β· Page 1 of 1 (latest)

shadow heath
#

I have a Vec2 with the following implementation:

class Vec2:
    def __init__(self, x, y):
        self.x, self.y = x, y

    def __eq__(self, other: Vec2):
        return self.x == other.x and self.y == other.y

    def __hash__(self):
        return hash(self.xy())

    def __str__(self):
        return f"({self.x}, {self.y})"

    def __repr__(self):
        return str(self)

    def xy(self):
        return self.x, self.y

And I'm getting unexpected behavior when I interact with sets:

pos = Vec2(1, 1)
print(pos)
print(set(pos))
``` I expect

(1, 1)
{(1, 1)}

(1, 1)
{1}

sleek sluiceBOT
#

@shadow heath

Python help channel opened

Remember to:

  • Ask your Python question, not if you can ask or if there's an expert who can help.
  • Show a code sample as text (rather than a screenshot) and the error message, if you've got one.
  • Explain what you expect to happen and what actually happens.

:warning: Do not pip install anything that isn't related to your question, especially if asked to over DMs.

heady trench
#

ah

polar oasis
#

not reproducible... for set(pos) to work you need __iter__

heady trench
#

sorry, last attempt

shadow heath
heady trench
#

!e

class Vec2:
    def __init__(self, x, y):
        self.x, self.y = x, y

    def __eq__(self, other: "Vec2"):
        return self.x == other.x and self.y == other.y

    def __hash__(self):
        return hash(self.xy())

    def __str__(self):
        return f"({self.x}, {self.y})"

    def __repr__(self):
        return str(self)

    def xy(self):
        return self.x, self.y

pos = Vec2(1, 1)
print(pos)
# print(set(pos))
sleek sluiceBOT
#

@heady trench :white_check_mark: Your 3.12 eval job has completed with return code 0.

(1, 1)
normal isle
heady trench
#

it prints what you expect it to

#

oh i'm not helpful at all. i misread the post

polar oasis
#

it's probably best to just use {pos} instead. that will create a set with one element

shadow heath
#

oh yeah that worked, tysm

#

ohhhh, ok i see now

#

it was interpreting it as set(1, 1)

#

which is ofc {1}

polar oasis
#

more or less, yes

shadow heath
#

ty

#

!close

sleek sluiceBOT
#
Python help channel closed

This help channel has been closed and it's no longer possible to send messages here. If your question wasn't answered, feel free to create a new post in #1035199133436354600. To maximize your chances of getting a response, check out this guide on asking good questions.