Armani42
Armani42

Reputation: 109

Python hash with if cases

I have a question regarding the hash(self) function of Python.

So in my method I have the following code pieces

def __init__(self, upper1, lower1, upper2, lower2):
    self.phase = 1
    self.gammas = frozenset()
    self.gammabars = frozenset()

def __hash__(self):
    if self.gammas:
        return hash(self.gammas)
    elif self.gammabars:
        return hash(self.gammabars)

So I want to say:

If self.gammas is not empty, then return the hashvalue of self.gammas or self.gammabars etc.

But if I now start my program, I get:

TypeError: __hash__ method should return an integer

So do you know, how to fix that?

Upvotes: 1

Views: 316

Answers (2)

Dan D.
Dan D.

Reputation: 74655

Use the hash of a tuple method:

return hash((self.gammas, self.gammabar))

Upvotes: 1

Yang HG
Yang HG

Reputation: 720

When you called hash(instance), both of your self.gammas or self.gammabars cannot be True. You can try add an else case:

def __hash__(self):
    if self.gammas:
        return hash(self.gammas)
    elif self.gammabars:
        return hash(self.gammabars)
    else:
        return hash(something)
        # or
        raise ValueError('gammas and gammabars are not valid.')

or debug your code to confirm the self.gammas and self.gammabars value.

Upvotes: 3

Related Questions