I spent last night wrangling a particularly confusing bug.
I wrote some proof of concept code to exhibit the issue.
PoC Code
# Standard Imports
import sys
# Import Core Qt modules
from PyQt4.QtGui import QApplication
from PyQt4.QtCore import QObject
class Bar(QObject):
def __init__(self, parent):
QObject.__init__(self, parent)
self.parent = parent
class Foo(QObject):
items = []
def __init__(self, parent, item_count=2):
QObject.__init__(self, parent)
self.parent = parent
# Create some items
for _ in range(item_count):
self.items.append(Bar(self))
# Debug
print "QObject Foo Items: %s" % self.items
print "QObject Foo Children: %s" % self.children()
# Start up main PyQT Application loop
app = QApplication(sys.argv)
# Build Foo classes
aFoo = Foo(app)
aFoo2 = Foo(app)
# Exit program when our window is closed.
sys.exit(app.exec_())
When this code is executed, here is the output
:
QObject Foo Items: [<__main__.Bar object at 0x0234F078>, <__main__.Bar object at 0x0234F0C0>]
QObject Foo Children: [<__main__.Bar object at 0x0234F078>, <__main__.Bar object at 0x0234F0C0>]
QObject Foo Items: [<__main__.Bar object at 0x0234F078>, <__main__.Bar object at 0x0234F0C0>, <__main__.Bar object at 0x0234F150>, <__main__.Bar object at 0x0234F198>]
QObject Foo Children: [<__main__.Bar object at 0x0234F150>, <__main__.Bar object at 0x0234F198>]
Code Explanation
The code is creating two Foo
QObject classes. Each class, during __init__
, creates some Bar
QObject classes and adds them to its class variable self.items
.
The bug here is apparently when the second class prints out the items in its self.items
class variable there are four and not two Bar
classes in there.
The Fix
If you move the class variable definition self.items
into the __init__
block of the Foo
class, then things work fine.
Thoughts
When items
was defined outside of the __init__
call it seems to act like a Singleton
and share state across all Foo
classes.