0

I have noticed a behavior of Python functions that I cannot fit into my naive understanding of local vs. global scope. For example, this

x = 1
y = 1
def f():
    print(x+y)
f()

appears to be valid Python code, as it does not produce an error message and the function is executed. But it seems to break the rules, since x and y are neither global variables nor are they arguments to f() nor are they defined within the local scope of f(), still f() can access those variables. Can someone explain to me what is happening here?

Chris Albert
  • 2,462
  • 8
  • 27
  • 31
  • 1
    A variable which is defined in the main body of a file is called a global variable. – Jean-Baptiste Yunès Apr 09 '20 at 13:45
  • 2
    As long as there is no assignment to a variable inside a function and its not a function argument, any variable is assumed to be global. See e.g. https://stackoverflow.com/questions/10360229/python-why-is-global-needed-only-on-assignment-and-not-on-reads – user2390182 Apr 09 '20 at 13:45
  • You might want to read about the LEGB rule. – T139 Apr 09 '20 at 13:46
  • To add to the other good comments explaining this, directly from the Python docs FAQs (https://docs.python.org/3/faq/programming.html#what-are-the-rules-for-local-and-global-variables-in-python): "In Python, variables that are only _referenced_ inside a function are implicitly global." – scissorhands Apr 09 '20 at 13:50

0 Answers0