0

Why is it possible to affect global variable in success function and it is not in failure function? It seems like it doesn't make any sense. Python is dynamically typed.

global_list = [1,2,3]

def failure_function():
    global_list = 'Test'

def success_function():
    global_list[0] = 7

print('global_list before everything is', global_list) #[1, 2, 3]
failure_function()
print('global_list after failure function is', global_list) #[1, 2, 3]
success_function()
print('global_list after success function is', global_list) #[7, 2, 3]
Bobby
  • 534
  • 3
  • 7
  • 21
  • 2
    Because the second one doesn't *assign* to that name, so a local variable isn't created. – jonrsharpe Nov 03 '18 at 19:00
  • 2
    One uses a mutator method on the object referred to by the *global variable* `global_list`, the other simply assigns `'Test'` to a *local variable*, `global_list`. – juanpa.arrivillaga Nov 03 '18 at 19:02
  • But i read that to access global variable inside of function, you need to type keyword 'global' like "global global_list", then you can access it. But it seems to be possible even this way. Am I getting this wrong? – Bobby Nov 03 '18 at 19:03
  • 2
    I'm sure this is a duplicate, just not "of what". But if you're used to languages like C++, Python is very different: variable names don't produce memory slots into which assignments copy values. Instead, variable names merely produce scoped *bindings* of values, and assigning to a variable name means, loosely, "declare a new variable at this function's scope, then make this assignment bind it". – torek Nov 03 '18 at 19:05
  • 2
    However, when you write `global_list[0]` you're not *assigning to* a variable, you're *using* a variable. Specifically, you're using `global_list` to find `global_list[0]`. Then you bind a value there, without declaring anything. So `success_function` doesn't declare a local `global_list` variable, but `failure_function` *does*. – torek Nov 03 '18 at 19:06
  • 1
    Using `global` (or `nonlocal`) as a declaration within a function definition avoids the automagic local declaration, so those will allow you to modify the global variable's binding. The "binding" notion comes up as yet another difference from C++-like languages later. – torek Nov 03 '18 at 19:09
  • 1
    @Bobby yes, that is incorrect. You can access global variables inside functions without the `global` keyword. However, if you assign to that name *anywhere* in the function, the compiler marks it as local, and thus, to *assign* to a global variable, you need the `global` keyword, or else all assignments are to local variables. – juanpa.arrivillaga Nov 03 '18 at 19:12
  • Thanks everyone, now I understand what's going on. – Bobby Nov 03 '18 at 19:37

0 Answers0