user2675041
user2675041

Reputation: 115

Value of variable changes when used outside of the function it is assigned in

I have created a function which gets the directory path of a file as follows:

def discoverLocation(self):
    self.txtBox.insert(1.0, askdirectory())
    if(self.txtBox.get(1.0) != 0):
        global path
        path = self.txtBox.get(1.0,END)
        print "path is "  + path

The output of this function works as intended, meaning outputting "path is 'directory of file'"

However when I use this 'path' variable from outside this function, the variable seems to change.

This is the code:

def __init__(self, parent):
    path = StringVar()
    print path


    dirs = os.listdir(path)
    for file in dirs:
        totalFiles += 1

The value of path over here is not the same path as before, it is displaying the name 'PY_VAR0'.

I want to use the same value given from the discoverLocation(self) method in the def_init_(self,parent) method.

Upvotes: 0

Views: 90

Answers (2)

Tom Dalton
Tom Dalton

Reputation: 6190

You need to do 2 things:

  1. Return the value of path from your discoverLocation, rather than trying to make it global e.g.:

    class MyClass(object):
        def discoverLocation(self):
            self.txtBox.insert(1.0, askdirectory())
            if(self.txtBox.get(1.0) != 0):
                path = self.txtBox.get(1.0,END)
                print "path is "  + path
                return path
            return None
    
  2. Use that path in the main function e.g.:

    def __init__(self, parent):
        path = self.discoverLocation()
        print path
        dirs = os.listdir(path)
        for file in dirs:
           totalFiles += 1
    

You'll also need to decide what to do if the path isn't found - e.g. if discoverLocation() returns None

Upvotes: 1

Daniel Roseman
Daniel Roseman

Reputation: 599600

You seem to have missed the fundamental point of classes: they store information in their instance attributes. You don't want to create a global variable, you want to create an instance attribute. You do that by referring to it via self.

So, in __init__:

def __init__(self, parent):
    self.path = StringVar()

and you can now refer to self.path in discoverLocation.

Upvotes: 2

Related Questions