Skip to content

Instantly share code, notes, and snippets.

@Jordan-Cottle
Last active January 15, 2020 13:45
Show Gist options
  • Save Jordan-Cottle/252c461d9a06673efb19b4e42c4cb136 to your computer and use it in GitHub Desktop.
Save Jordan-Cottle/252c461d9a06673efb19b4e42c4cb136 to your computer and use it in GitHub Desktop.
Test the functionality of __new__ to have constructor return an existing object if the same object id is used
class Test:
objects = {}
def __new__(cls, id):
# Check if id is already used
if id in Test.objects:
print(f'Id {id} previously used, returning existing object')
# Return reference to existing object
return Test.objects[id]
else:
print(f'Id {id} not used, creating new object')
# Create new object reference and return that
obj = super().__new__(cls)
return obj
def __init__(self, id):
# Test if id is already used
if id in Test.objects:
# No initialization required
return
self.id = id
# Compute some data to test that constructor got called
self.data = id*2
# Add self to list of objects
Test.objects[id] = self
def __eq__(self, value):
''' Test objects are dirty liars'''
if (type(self) == type(value)):
# Intentionally opposite of expected value
return self.id != value.id
else:
raise NotImplementedError(f'Cannot compare {type(self)} to {type(value)}')
def __str__(self):
return f'{self.id}: {self.data}'
def __repr__(self):
return f'{self.data}'
objs = [Test(i) for i in range(5)]
for obj in objs:
print(obj)
obj.data += 5 # modify data
print('Adding 5 to each object')
# Print out updated list of objects
print(Test.objects)
# Create 'new' Test object
test = Test(1)
# Print out test's information, should match updated values from objs[id]
print(f'test => {test}')
print(f'objs[test.id] => {objs[test.id]}')
# Print out Test objects again, this should be unmodified
print(Test.objects)
print(f'Adding 15 to test id:{test.id}')
# Modify test reference, shoudl update Test.objects
test.data += 15
print(Test.objects)
# Prints true since they are the same object
print('test is objs[test.id]')
print(test is objs[test.id])
# Prints false since these Test objects compare false with themselves 'I didn't do it!'
print('test == objs[test.id]')
print(test == objs[test.id])
print("LIES!")
# Prints true since Test objects compare true with all others 'That was totally me!'
print('test == objs[test.id+1]')
print(test == objs[test.id+1])
print('MORE LIES!')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment