Nick Bonne Nick Bonne - 2 months ago 5
Python Question

I think I'm misunderstanding how variables from other functions can be called

I'll try with words first. Using Python 3, and I have a main function that sets arg as a variable. When the main() is run, it calls a copy function which calls other functions. After these other functions run, copy() needs that arg variable set by main() at the beginning to finish and allow the main() to complete.

From what I understand, the arg variable is local to main(). Calling arg from outside the function returns a NameError.

I am looking at this thinking "I should be able to call the arg variable from copy() because I am running main() which is calling copy().

I keep arriving at a NameError. The final function I call before I want the main function to end wants to know what arg holds but doesn't recognize arg as defined.

Assuming all other necessary stuff is working, what must one do to get the copy() to recognize arg as defined.

...


def copy():
x = destination()
if os.path.isdir(x):
y = backup_destination()
if not os.path.isdir(y):
shutil.copytree(arg.source, backup_destination)
shutil.rmtree(x)
shutil.copytree(arg.source, x)


def main():
parser = argparse.ArgumentParser()
parser.add_argument('-s', '--source', type = str)
arg = parser.parse_args()

if os.path.isdir(arg.source):
copy()

...


if __name__ == '__main__':
main()

Answer

The variable is local to the main function, to use it in copy you have to pass it as an argument, or make it a global variable. try to avoid the latter at all costs except you're sure that you need it, using global variables can lead to a lot of problems that are hard to debug, because a function that you forgot about altered the variable.

def copy(arg):
    x = destination()
    if os.path.isdir(x):
        y = backup_destination()
        if not os.path.isdir(y):
            shutil.copytree(arg.source, backup_destination)
            shutil.rmtree(x)
            shutil.copytree(arg.source, x)


def main():
    parser = argparse.ArgumentParser()
    parser.add_argument('-s', '--source', type = str)
    arg = parser.parse_args()

    if os.path.isdir(arg.source):
       copy(arg)


if __name__ == '__main__':
    main()

Read this for more information on variable scopes in python.

Comments