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>Each function runs in a different frame. Try printing <code>locals()</code> in each of your functions to see the local variables.</p>

<p>There are 2 ways to access args:</p>

<p>First, the <strong>normal and correct way to do things</strong>: Give it to <code>copy()</code> as an argument:</p>

<pre><code>def copy(arg):
    ...
def main():
    copy(arg)
</code></pre>

<p>Second, the bad way to do things: Analyze the top frame using <code>sys._getframe(1)</code>:</p>

<pre><code>def copy():
    args = sys._getframe(1).f_locals["args"]
    print(args())

def main():
    args = 1234
    copy()

&gt;&gt;&gt; main()
1234
</code></pre>

<p>Regarding getting a variable from a different scope, I believe you're mistaken with this code:</p>

<pre><code>def main():
    arg = 1234
    def code():
        print(arg)
    code()
</code></pre>

<p>In here, since the function was defined inside another function, it gets access to it's local variables.</p>

python python-3.x