Python: how to access already instantiated class object in PyQt?
<p>I have a simple subclass of a base class, QLineEdit, which is just an editable text box from PyQt5: </p>

<pre><code>class pQLineEdit(QtWidgets.QLineEdit):
    def __init__(self, parent = None):
        QtWidgets.QWidget.__init__(self,parent)

    def mouseDoubleClickEvent(self,e):
        self.setText("Test")
</code></pre>

<p>This class works fine. The object's text is indeed updated when I double  click it. </p>

<p>However, at this event, I am in need of accessing an object, foo.bar,  from another, already-instantiated class in another file. How can I do this? I have tried </p>

<pre><code>import other_file
...
def mouseDoubleClickEvent(self,e):
  self.setText("Test")
  foo.bar
</code></pre>

<p>I get:</p>

<pre><code> NameError: global name 'foo' is not defined
</code></pre>

<p>I've tried hacking my way just using</p>

<pre><code>eval("foo.bar") 
</code></pre>

<p>But it complains foo.bar is not defined. I feel this is very simple but the answer eludes me. </p>

<p>I should clarify: foo() is a class instantiated in a FUNCTION in the other file, which is main(). I must access the instantiated class because it contains an SSH tunnel. I don't think my question is a dupe as listed. </p>

<p>At the risk of stating the obvious: if you want to access a variable, you need to put it somewhere that is accessible. The local scope of a function is not accessible to any code outside of that function.</p>

<p>To make a variable accessible to another module, it must be assigned in the global scope, or be assigned as an attribute of another object that is in the global scope.</p>

<p>If the variable cannot be assigned when the module is loaded, define it using the <code>global</code> statement:</p>

<pre><code>foo = None

def main():
    global foo
    foo = MyClass()
    ...
</code></pre>

<p>However, a more appropriate approach for a gui application would be for the top-level window to provide access to the variable:</p>

<pre><code>class MainWindow(QtWidgets.QMainWindow):
    def __init__(self):
        super(MainWindow, self).__init__()
        self.foo = MyClass()
</code></pre>

<p>Any child widget that has the main window as its parent can then access the variable via its <code>parent()</code> method:</p>

<pre><code>class LineEdit(QtWidgets.QLineEdit):
    def __init__(self, parent=None):
        super(LineEdit, self).__init__(parent)

    def mouseDoubleClickEvent(self, event):
        bar = self.parent().foo.bar
</code></pre>

<p><strong>PS</strong>:</p>

<p>Note that if you put the line-edit in a layout, it will be automatically re-parented to the layout's parent. In a <code>QMainWindow</code>, this will likely be the central-widget. In that case, you should either set the attribute on the central-widget, or retrieve the main-window with <code>self.parent().parent()</code>.</p>

python oop pyqt