I think I'm misunderstanding how variables from other functions can be called
<p>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. </p>

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

<p>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().</p>

<p>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.</p>

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

<pre><code>...


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()
</code></pre>

<p>The variable is local to the <code>main</code> function, to use it in <code>copy</code> 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.</p>

<pre><code>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()
</code></pre>

<p>Read <a href="http://python-textbok.readthedocs.io/en/latest/Variables_and_Scope.html" rel="nofollow">this</a> for more information on variable scopes in python.</p>

python python-3.x