I shrunk my original problem to this MRE. It may be confusing because some parts may still be unnecessary.
Originally, this was an input box that needed to perform special actions when certain keys were pressed.
I need to create multiple instances of the same class. In the constructor, a local variable named var is declared. As I understand, it should be destroyed when exiting the function. I even added the line del var to make sure it was the case, and deleted the old object, but it ended up being useless.
When I then created another object of that same class (the variable is also reset in the function parameters), I find that the variable has never been destroyed, as its old content gets saved, as demonstrated below:
class A:
def __init__(self, var=[]):
var.extend([(10, self.func), (20, lambda: 1)])
self.keycodes = [key for key, f in var]
self.functions = [f for key, f in var]
del var
def update(self, key):
for x in range(len(self.keycodes)):
if key == self.keycodes[x]:
self.functions[x]()
def func(self):
print('Hello World')
a1 = A()
print(a1)
print(a1.functions)
del a1
a2 = A()
print('\n', a2)
print(a2.functions)
Output:
<__main__.A object at 0x00000216B72766A0> [<bound method A.func of <__main__.A object at 0x00000216B72766A0>>, <function A.__init__.<locals>.<lambda> at 0x00000216B72F1550>] <__main__.A object at 0x00000216B72DFD60> [<bound method A.func of <__main__.A object at 0x00000216B72766A0>>, <function A.__init__.<locals>.<lambda> at 0x00000216B72F1550>, <bound method A.func of <__main__.A object at 0x00000216B72DFD60>>, <function A.__init__.<locals>.<lambda> at 0x00000216B72F1820>]
Expected output:
<__main__.A object at 0x00000216B72766A0> [<bound method A.func of <__main__.A object at 0x00000216B72766A0>>, <function A.__init__.<locals>.<lambda> at 0x00000216B72F1550>] <__main__.A object at 0x00000216B72DFD60> [<bound method A.func of <__main__.A object at 0x00000216B72DFD60>>, <function A.__init__.<locals>.<lambda> at 0x00000216B72F1820>]