0

I'm relatively new to Python, so please forgive my ignorance.

I have two functions acting on a single variable var:

var = 8

def func1():
    print(var)

def func2():
    var += 1
    print(var)

func2 will not function unless I define var as a global variable:

def func2():
    global var
    var += 1
    print(var)

What is the functionality that allows me to call global variables (as in func1) but does not allow me to redefine global variables without explicitly calling them first (as in func2)?

Yehuda
  • 1,787
  • 2
  • 15
  • 49
  • I hope this is only for educational purposes, otherwise, you are in for a very undefined behavior. – DeepSpace Apr 26 '20 at 16:27
  • Anyway, does this answer you question? https://stackoverflow.com/questions/49715854/python-global-variables-not-defined – DeepSpace Apr 26 '20 at 16:29
  • @DeepSpace: I see no `undefined behaviour` here. (Is there *any* undefined behaviour in python?) – quamrana Apr 26 '20 at 16:30
  • I don't see you *calling* any variables. Did you mean access values? – quamrana Apr 26 '20 at 16:31
  • @quamrana well, good luck trying to debug this through a huge code base and trying to understand why `func1`'s outputs change between calls for "no apparent reason", especially if not single-threaded. – DeepSpace Apr 26 '20 at 16:35
  • @DeepSpace, sorry, I come from a C++ background where (perversely) `undefined behaviour` has a precise definition. Anyway in the case of the snippets, that is what unit tests are for. – quamrana Apr 26 '20 at 16:38

1 Answers1

0

The Programming FAQ explains the reasoning:

In Python, variables that are only referenced inside a function are implicitly global. If a variable is assigned a value anywhere within the function’s body, it’s assumed to be a local unless explicitly declared as global.

Though a bit surprising at first, a moment’s consideration explains this. On one hand, requiring global for assigned variables provides a bar against unintended side-effects. On the other hand, if global was required for all global references, you’d be using global all the time. You’d have to declare as global every reference to a built-in function or to a component of an imported module. This clutter would defeat the usefulness of the global declaration for identifying side-effects.

Thierry Lathuille
  • 23,663
  • 10
  • 44
  • 50