mdomke / python-ulid

ULID implementation for Python
https://python-ulid.rtfd.io
MIT License
391 stars 18 forks source link

Implement __hash__ #3

Closed emfdavid closed 1 year ago

emfdavid commented 2 years ago

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?

bendykst commented 2 years ago

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.

johnpaulett commented 1 year ago

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