Skip to content

Instantly share code, notes, and snippets.

@Mikael-Lovqvist
Last active September 15, 2021 20:07
Show Gist options
  • Save Mikael-Lovqvist/cbfd137fb9d766a804387d10030507eb to your computer and use it in GitHub Desktop.
Save Mikael-Lovqvist/cbfd137fb9d766a804387d10030507eb to your computer and use it in GitHub Desktop.
2021-09-15 Video Log - identity tracking in Python
#This is a demo for VLOG entry https://youtu.be/LfRFxkombTw "Python - track object identities [short]"
greek_alphabet = ['Άλφα', 'Βήτα', 'Γάμμα', 'Δέλτα', 'Έψιλον', 'Ζήτα', 'Ήτα', 'Θήτα', 'Ιώτα', 'Κάππα', 'Λάμβδα', 'Μυ', 'Νυ', 'Ξι', 'Όμικρον', 'Πι', 'Ρώ', 'Σίγμα', 'Ταυ', 'Ύψιλον', 'Φι', 'Χι', 'Ψι', 'Ωμέγα']
class identity_reference:
def __init__(self, target):
self.target = target
self.id = id(target)
try:
self.hash = hash(target)
except Exception:
self.hash = self.id
def __hash__(self):
return self.hash
def __eq__(self, other):
if isinstance(other, identity_reference):
return self.id == other.id
else:
return self.id == id(other)
def __repr__(self):
return f'{self.target}(ref)'
class id_representation:
def __init__(self, sequence):
self.sequence = iter(sequence)
self.populated = dict()
def __call__(self, item):
idref = identity_reference(item)
if existing := self.populated.get(idref):
return existing
new = self.sequence.__next__()
self.populated[idref] = new
return new
#Demo
rid = id_representation(greek_alphabet)
a, b, c = object(), object(), object()
print(rid(a), rid(b), rid(c))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment