tkarabela / pysubs2

A Python library for editing subtitle files
http://pysubs2.readthedocs.io
MIT License
318 stars 40 forks source link

ssaevent hashable? #52

Closed emperor-limitless closed 2 years ago

emperor-limitless commented 2 years ago

Hi So in a program I'm doing I need to do something like this import pysubs2

subs = pysubs2.load("subtitle.ass", encoding = "utf-8") ... if subtitle in list: print("In.")

However, This doesn't work TypeError: unhashable type: 'SSAEvent' So could it become hashable?

tkarabela commented 2 years ago

Hi Mohamed, SSAEvent is a mutable dataclass - making it hashable would require making it immutable as well, which would be a pretty big and (IMO) somewhat unintuitive change in the API.

Note that SSAEvent does implement ordering and equality - it behaves as a tuple (subtitle.start, subtitle.end). This is mainly so that you can do subs.events.sort() and such. You can also use this to look up subtitles in a list, however this only compares the start/end timestamps and not other attributes like text, which is... somewhat unintuitive:

import pysubs2

subs = pysubs2.SSAFile()
e1 = pysubs2.SSAEvent(start=0, end=10000, text="Subtitle 1")
e2 = pysubs2.SSAEvent(start=10000, end=20000, text="Subtitle 2")
subs.append(e1)
subs.append(e2)

e = pysubs2.SSAEvent(start=0, end=10000, text="Subtitle 1")
print(e in subs)  # -> True, same times
print(e in [e1, e2])  # -> True

e = pysubs2.SSAEvent(start=0, end=10000, text="Subtitle 1 (different text)")
print(e in subs)  # -> True, same times (eh)
print(e in [e1, e2])  # -> True

e = pysubs2.SSAEvent(start=0, end=15000, text="Subtitle 1")
print(e in subs)  # -> False, different time
print(e in [e1, e2])  # -> False

Can you share a bit more of your code so that it's more clear what you're trying to achieve?

emperor-limitless commented 2 years ago

So I see the problem here, Not the fault of the library, But of my code So for some reason if I do the matching, Like this if item in my_set: ... It errors, But with a normal list it works.