Apr-12-2023, 02:37 PM
I came across something interesting that I can't explain. Perhaps someone here can. When the following code is run with the lambda commented out it produces the output I expect to see.
I get
so perhaps specifying self.b in the lambda expression is causing a problem with the reference counter.
class Exp: def __init__(self): print('__init__') self.b = 1 #self.a = lambda: self.b def __del__(self): print('__del__') obj = Exp() obj = NoneOutput
__init__ __del__But with the lambda uncommented
class Exp: def __init__(self): print('__init__') self.b = 1 self.a = lambda: self.b def __del__(self): print('__del__') obj = Exp() obj = NoneI do not see that __del__ is executed.
__init__As I understand it, __del__ executes when the reference count for an object reaches zero so I can only assume that somehow the lambda line is doing something odd. But if I modify the lambda to
class Exp: def __init__(self): print('__init__') self.b = 1 self.a = lambda: 10 def __del__(self): print('__del__') obj = Exp() obj = None
I get
__init__ __del__I'm not a fan of lambdas, but typically a lambda specifies a parameter and something that operates on that parameter like
self.a = lambda x: x**2
so perhaps specifying self.b in the lambda expression is causing a problem with the reference counter.