python-ulid icon indicating copy to clipboard operation
python-ulid copied to clipboard

Implement __hash__

Open emfdavid opened this issue 3 years ago • 1 comments

Suggest you implement hash to allow use as a dictionary key.

I am getting the following issue using ULID as a custom type in a SqlAlchemy Model.

if key not in self._dict:
  TypeError: unhashable type: 'ULID'

Maybe add something like this?

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

or

def __hash__(self):
  return int(self)

Though, that might be a longer integer than expected for a hash value?

emfdavid avatar Jun 07 '22 20:06 emfdavid

Wow, what a coincidence, I just ran into this limitation today too. I think that the first suggestion is the most straightforward and I added it in the above pull request. I also added tests, which probably wasn't really necessary, since they're basically just testing the built-in hash function, but I thought it couldn't hurt.

bendykst avatar Jun 08 '22 20:06 bendykst

Ran into this issue too and this solution solved it. uuid.UUID implements a __hash__, so this approach seems consistent.

johnpaulett avatar Apr 01 '23 16:04 johnpaulett