-2

I have this code:

global dir_name
dir_name = ''

def generateDirectoryName(newpath, x=0):
    while True:
        dir_name = (newpath + ('_' + str(x) if x != 0 else '')).strip()
        if not os.path.exists(dir_name):
            os.mkdir(dir_name)
            #1
            #print(dir_name)
            return dir_name
        else:
            x = x + 1


def createDirectory():
    generateDirectoryName(newpath)


def main():
    cwd = os.getcwd()
    createDirectory()

#2
print(dir_name)

main()

#3
print(dir_name)

When I try the code, the two prints at the end (labelled with comments 2 and 3 don't appear to have any effect. However, if I uncomment the print inside the function (at comment 1), it will show the dir_name value. Why does this happen - why can't I access dir_name outside the function? How can I fix the problem?

Karl Knechtel
  • 62,466
  • 11
  • 102
  • 153
JM1
  • 1,595
  • 5
  • 19
  • 41
  • 2
    You don't declare a variable global in the global scope, you use it _inside_ a function to tell Python you want to use the global version of that variable and not shadow it within a function. So the print statment at #1 gets the correct, _local_ `dir_name`, but the other two get the global, empty one. – B Remmelzwaal May 08 '23 at 14:26
  • 1
    Your first line within the function and before the while loop should be `global dir_name`. The global declaration that you have currently written does nothing – Ben Grossmann May 08 '23 at 14:29
  • You should place `global dir_name` at the top of your `generateDirectoryName` function. – B Remmelzwaal May 08 '23 at 14:35
  • Thanks to you both! When I set the global dir_name in the function above the while, it still doesn't print at #'s 2 or 3. It gives me an error: NameError: name 'dir_name' is not defined – JM1 May 08 '23 at 14:35
  • @JM1 How exactly have you implemented it? Seems to work fine for me. Your code should look like what Usman answered. – B Remmelzwaal May 08 '23 at 14:36
  • I posted an update after comments section that shows you what I tried. Thank you for your help. – JM1 May 08 '23 at 14:38
  • Usman's answer worked. Thank you both for your help! – JM1 May 08 '23 at 14:42
  • Based on Usman's answer, I didn't have the variable dir_name = '' defined before the function after moving global = dir_name inside the function , that appears to be why it didn't work. – JM1 May 08 '23 at 14:45
  • You may be new to Python, but you are not at all new to Stack Overflow. As a refresher, though: please do not "update" questions to show how you fixed the problem, do not tell us about your level of expertise (or anything else that is not about **the question** in the question); try to explain clearly and ask directly; [try to](https://meta.stackoverflow.com/questions/261592) look for [existing answers](https://stackoverflow.com/search?q=is%3Aquestion+%5Bpython%5D+global) first; don't post "Thanks" comments; and above all keep in mind that this is **not a discussion forum**. – Karl Knechtel May 08 '23 at 14:49

1 Answers1

1

dir_name is a local variable in your function. In order to change it to global you have to use global dir_name inside the function. As far as printing goes, dir_name is actually getting printed at 2 and 3 but is just an empty string. Also, you dont have to return dir_name as you're not assigning the return value of generateDirectoryName(newpath, x=0) to anything in createDirectory. Here is an updated version of your code:

dir_name = ''

def generateDirectoryName(newpath, x=0):
    global dir_name
    while True:
        dir_name = (newpath + ('_' + str(x) if x != 0 else '')).strip()
        if not os.path.exists(dir_name):
            os.mkdir(dir_name)
           #1
            #print(dir_name)
            return
        else:
            x = x + 1


def createDirectory():
    generateDirectoryName(newpath)


def main():
    cwd = os.getcwd()
    createDirectory()

#2 (This will still print an empty string)
print(dir_name)

main()

#3 (This will print whatever is printed in #1)
print(dir_name)
Usman
  • 44
  • 2