Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Access to variables from outside function

Tags:

python

I am fairly new to Python, but a bit more experienced in C++, which is why the below code example puzzles me a bit.

def foo():
    y = x
    print y

x = 5
foo()

Running this code prints the value 5. How can the value of variable x be known inside foo()? The above code would not run in C++, it would if we had done:

#include <iostream>

int x = 5;
void foo()
{
    std::cout << "x = " << x << std::endl;
}

int main()
{
    foo();
    return 0;
}

Because here x is a variable in the global scope which is declared (and defined) prior to foo(). Is it working in Python because x gets added to the global symbol table?

Thanks for any help!

like image 531
jensa Avatar asked Oct 28 '14 08:10

jensa


1 Answers

Everything at global scope is visible from inside functions for reading. That's how it must be: there is no distinction in Python between names that point to variables and names that point to functions, so if this didn't work you wouldn't even be able to call functions.

But if you wanted to modify x, you'd need the global keyword.

As to why it works when the variable is defined after the function: Python doesn't attempt to resolve references at compile time, it does when the function is called: because everything in python is dynamic, there's no way of telling ahead of time if a variable is defined.

like image 109
Daniel Roseman Avatar answered Sep 23 '22 15:09

Daniel Roseman