Global variables

Hello dear wxpython community:

I have been struggling for a couple of now, trying to figure out how to extract a value from a very nested function that is in my application. Here is my very simplified code:

class MyFrame(wx.Frame):
   
    def __init__(self,parent,id, title):
        wx.Frame.__init__(self,parent,id,title='An application',size=(900,750))
        menuBar=wx.MenuBar()
#some menus

    def opendir(self, event):
        dlg=wx.DirDialog(self,"Choose directory",defaultPath=os.getcwd())
        
        if dlg.ShowModal() == wx.ID_OK:
            self.path=dlg.GetPath()
            self.namedir=os.path.basename(self.path)
            self.maindir=os.path.dirname(self.path)
          
        if "_" in self.namedir:
            small=i.split("_")
        else:
            small=value
                
        for ine,elem in enumerate(small):
            if re.search("day",elem,re.I):
                fii=ine
                lelem=len(elem)
                if lelem==4:
    ### THIS IS THE VALUE I NEED TO PASS TO OTHER CLASSES
                    pival=elem[3]
                else:
                    inn=small[fii+1]
                    pival=elem[fii+1]
        
print pival

class MyApp(wx.App):
    def OnInit(self):
        myframe=MyFrame(None,-1,"")
        myframe.CenterOnScreen()
        myframe.Show(True)
        return True

app=MyApp(0)
app.MainLoop()

   I have tried defining pival (within a function) as a global, but I probably haven't placed the function at the right place. I would appreciate very much any help.

Thank you!

Judith

Hi, Judith.

There are two issues, I think.

One is making the name "pival" available throughout the whole class
called MyFrame; for that, you should call it self.pival instead of
pival. The "self" refers to its parent, the instance of the frame.
With self.pival, any function in the class can access it.

Two is passing anything between classes. This is (understandably)
asked often enough that there should be a wiki page for it, and I am
tempted to try it. Briefly put, and as I understand, there are about
three things you could do.

You can either call the instance of the class you want to pass it to
with self.pival as one of the arguments, e.g.:

otherclass = OtherClass(self.pival)

or you can "Get()" the class if it is a child or parent of your main
class (for example, GetParent()) and then use dot notation to set up
the name in the other class, e.g:

parentclass = otherclass.GetParent()
parentclass.variable = variable

or you can use the wx.lib.pubsub class to "publish" variables to any
"listener" in another class. Pubsub is preferred in terms of keeping
classes from being dependent on each other in a way that makes it
difficult to later revise or reuse the code.

Che

···

On Mon, Feb 9, 2009 at 3:53 PM, Judith Flores <juryef@yahoo.com> wrote:

Hello dear wxpython community:

I have been struggling for a couple of now, trying to figure out how to extract a value from a very nested function that is in my application. Here is my very simplified code:

class MyFrame(wx.Frame):

   def __init__(self,parent,id, title):
       wx.Frame.__init__(self,parent,id,title='An application',size=(900,750))
       menuBar=wx.MenuBar()
#some menus

   def opendir(self, event):
       dlg=wx.DirDialog(self,"Choose directory",defaultPath=os.getcwd())

       if dlg.ShowModal() == wx.ID_OK:
           self.path=dlg.GetPath()
           self.namedir=os.path.basename(self.path)
           self.maindir=os.path.dirname(self.path)

       if "_" in self.namedir:
           small=i.split("_")
       else:
           small=value

       for ine,elem in enumerate(small):
           if re.search("day",elem,re.I):
               fii=ine
               lelem=len(elem)
               if lelem==4:
   ### THIS IS THE VALUE I NEED TO PASS TO OTHER CLASSES
                   pival=elem[3]
               else:
                   inn=small[fii+1]
                   pival=elem[fii+1]

print pival

class MyApp(wx.App):
   def OnInit(self):
       myframe=MyFrame(None,-1,"")
       myframe.CenterOnScreen()
       myframe.Show(True)
       return True

app=MyApp(0)
app.MainLoop()

  I have tried defining pival (within a function) as a global, but I probably haven't placed the function at the right place. I would appreciate very much any help.

Thank you!

Judith

Hi,

Do you really want global variables? From your example doesn't seem like it.
But if you do, a "mini MVC" would be:

- define a model class with your globals in it.
- create the model during app initialization and set a reference
inside your app to it
- you can then get to the model from anywhere wx.GetApp().myModel.myVariable

P.K.

Thank you very much Che,

     I actually had tried self.pival, but then I get an "AttributeError" saying the MyFrame doesn't have attibute 'pival'. Why is that?

Thank you,

Judith

···

----- Original Message ----
From: C M <cmpython@gmail.com>
To: wxpython-users@lists.wxwidgets.org
Sent: Monday, February 9, 2009 1:32:58 PM
Subject: Re: [wxpython-users] Global variables

On Mon, Feb 9, 2009 at 3:53 PM, Judith Flores <juryef@yahoo.com> wrote:

Hello dear wxpython community:

I have been struggling for a couple of now, trying to figure out how to extract a value from a very nested function that is in my application. Here is my very simplified code:

class MyFrame(wx.Frame):

   def __init__(self,parent,id, title):
       wx.Frame.__init__(self,parent,id,title='An application',size=(900,750))
       menuBar=wx.MenuBar()
#some menus

   def opendir(self, event):
       dlg=wx.DirDialog(self,"Choose directory",defaultPath=os.getcwd())

       if dlg.ShowModal() == wx.ID_OK:
           self.path=dlg.GetPath()
           self.namedir=os.path.basename(self.path)
           self.maindir=os.path.dirname(self.path)

       if "_" in self.namedir:
           small=i.split("_")
       else:
           small=value

       for ine,elem in enumerate(small):
           if re.search("day",elem,re.I):
               fii=ine
               lelem=len(elem)
               if lelem==4:
   ### THIS IS THE VALUE I NEED TO PASS TO OTHER CLASSES
                   pival=elem[3]
               else:
                   inn=small[fii+1]
                   pival=elem[fii+1]

print pival

class MyApp(wx.App):
   def OnInit(self):
       myframe=MyFrame(None,-1,"")
       myframe.CenterOnScreen()
       myframe.Show(True)
       return True

app=MyApp(0)
app.MainLoop()

  I have tried defining pival (within a function) as a global, but I probably haven't placed the function at the right place. I would appreciate very much any help.

Thank you!

Judith

Hi, Judith.

There are two issues, I think.

One is making the name "pival" available throughout the whole class
called MyFrame; for that, you should call it self.pival instead of
pival. The "self" refers to its parent, the instance of the frame.
With self.pival, any function in the class can access it.

Two is passing anything between classes. This is (understandably)
asked often enough that there should be a wiki page for it, and I am
tempted to try it. Briefly put, and as I understand, there are about
three things you could do.

You can either call the instance of the class you want to pass it to
with self.pival as one of the arguments, e.g.:

otherclass = OtherClass(self.pival)

or you can "Get()" the class if it is a child or parent of your main
class (for example, GetParent()) and then use dot notation to set up
the name in the other class, e.g:

parentclass = otherclass.GetParent()
parentclass.variable = variable

or you can use the wx.lib.pubsub class to "publish" variables to any
"listener" in another class. Pubsub is preferred in terms of keeping
classes from being dependent on each other in a way that makes it
difficult to later revise or reuse the code.

Che
_______________________________________________
wxpython-users mailing list
wxpython-users@lists.wxwidgets.org
http://lists.wxwidgets.org/mailman/listinfo/wxpython-users

You’re (currently) creating pival inside an if clause, inside a for loop, inside a method. Chances are that you were trying to refer to it before creating it.

Try adding "pival=‘’ " just inside the class but outside any methods, or "self.pival = ‘’ " (better) in your init() method.

www.fsrtechnologies.com

···

On Feb 9, 2009 2:42 PM, “Judith Flores” juryef@yahoo.com wrote:

Thank you very much Che,

 I actually had tried self.pival, but then I get an "AttributeError" saying the MyFrame doesn't have attibute 'pival'. Why is that?

Thank you,

Judith

----- Original Message ----
From: C M cmpython@gmail.com
To: wxpython-users@lists.wxwidgets.o…

Thank you Marc!

···

From: Marc Tompkins marc.tompkins@gmail.com
To: wxpython-users@lists.wxwidgets.org
Sent: Monday, February 9, 2009 2:50:41 PM
Subject: Re: [wxpython-users] Global variables

You’re (currently) creating pival inside an if clause, inside a for loop, inside a method. Chances are that you were trying to refer to it before creating it.

Try adding "pival=‘’ " just inside the class but outside any methods, or "self.pival = ‘’ " (better) in your init() method.

www.fsrtechnologies.com

On Feb 9, 2009 2:42 PM, “Judith Flores” juryef@yahoo.com wrote:

Thank you very much Che,

 I actually had tried self.pival, but then I get an "AttributeError" saying the MyFrame doesn't have attibute 'pival'. Why is that?

Thank you,

Judith

----- Original Message ----
From: C M cmpython@gmail.com
To: wxpython-users@lists.wxwidgets.o…

Judith Flores wrote:

Thank you very much Che,

     I actually had tried self.pival, but then I get an "AttributeError" saying the MyFrame doesn't have attibute 'pival'. Why is that?
  
You have to be consistent. Here's what you had, condensed:

    class MyFrame( wx.Frame ):
        def opendir(self, event):
            ...
            pival = elem[3]

    print pival

By the time you get to the "print" statement, you don't actually have
any "MyFrame" objects. You've just declared the class. None of the
code in "class MyFrame" has run yet, so the statement that creates
"pival" has not run. There is no variable called "pival", so the print
statement will fail.

Beyond that, this is trying to use "pival" as a global variable, but the
code as written creates "pival" as a variable local to that function.
When the function ends, the data goes away. It *IS* possible to create
pival as a global, but because it is so dangerous, you have to
specifically tell Python that you want to change a global. You COULD say:

    class MyFrame( wx.Frame ):
        def opendir(self, event):
            global pival
            ...
            pival = elem[3]

That would work, although you still couldn't print "pival" until the
opendir function has actually run.

The better solution, suggested by several people, is to make "pival" a
member of the class, like this:
    class MyFrame( wx.Frame ):
        def opendir(self, event):
            ...
            self.pival = elem[3]

Now, anyone who has created a MyFrame object can access this variable:

    myframe = MyFrame( None, -1, "" )
    ....
    print myframe.pival

However, as I said before, "pival" won't exist until after the "opendir"
function runs. This brings up another problem. You create the MyFrame
object in MyApp:
    class MyApp(wx.App):
        def onInit(self):
            myframe = MyFrame( None, -1, "" )
            myframe.CenterOnScreen()
            myframe.Show()
            return True

The problem here is that "myframe" is, again, a variable that is local
to the function. When the function ends, that name goes away, so you no
longer have any way to find the object. So, let's change this to keep
the MyFrame object around:

    class MyApp(wx.App):
        def OnInit(self):
            self.myframe = MyFrame( None, -1, "" )
            self.myframe.CenterOnScreen()
            self.myframe.Show()
            return True

Now, you have created your application as a global:

    app = MyApp(0)

So, if you really needed to access the "pival" value in some related
code that was not part of the GUI, you could say:

    print app.myframe.pival

Because the "app" object now contains a member called "myframe", which
is a MyFrame object. And, after "opendir" has run, that MyFrame object
will contain a member called "pival".

But, repeating myself, don't expect to find "pival" until after
"opendir" has run. It won't exist. You could set
    self.pival = -1
inside of MyFrame.__init__ if you wanted to be able to query the value
at any time.

···

--
Tim Roberts, timr@probo.com
Providenza & Boekelheide, Inc.

Is opendir() ever being called? It looks like you’re binding it to some menu item, but you edited the menu out of your posting.
Try this - change the definition to “def opendir(self, event=None):” - this makes “event” an optional parameter; you’re not using it anyway - and then, as a test, add this line: “app.myframe.opendir()” just before the print.

www.fsrtechnologies.com

···

On Feb 9, 2009 4:34 PM, “Judith Flores” juryef@yahoo.com wrote:

Hi Marc,

I tried both of your suggestions, but self.tpval doesn’t ‘adopt’ the value that is within the loops, it remain empty “”.

Judith


From: Marc Tompkins
marc.tompkins@gmail.com

To: wxpython-users@lists.wxwidgets.org

Sent: Monday, February 9, 2009 2:50:41 PM

Subject: Re: [wxpython-users] Global variables

You’re (currently) creating pival inside an if clause, inside a for loop, inside a method. Chances…

Judith, as part of the general topic here, you might find this section
from Dive Into Python helpful, on locals and globals (basically,
Python namespaces):

···

On Mon, Feb 9, 2009 at 5:41 PM, Judith Flores <juryef@yahoo.com> wrote:

Thank you very much Che,

    I actually had tried self.pival, but then I get an "AttributeError" saying the MyFrame doesn't have attibute 'pival'. Why is that?

Thank you,

Judith

Thank you Che, I will read into that.

···

----- Original Message ----
From: C M <cmpython@gmail.com>
To: wxpython-users@lists.wxwidgets.org
Sent: Monday, February 9, 2009 5:22:35 PM
Subject: Re: [wxpython-users] Global variables

On Mon, Feb 9, 2009 at 5:41 PM, Judith Flores <juryef@yahoo.com> wrote:

Thank you very much Che,

    I actually had tried self.pival, but then I get an "AttributeError" saying the MyFrame doesn't have attibute 'pival'. Why is that?

Thank you,

Judith

Judith, as part of the general topic here, you might find this section
from Dive Into Python helpful, on locals and globals (basically,
Python namespaces):

_______________________________________________
wxpython-users mailing list
wxpython-users@lists.wxwidgets.org
http://lists.wxwidgets.org/mailman/listinfo/wxpython-users