0

This executes without error:

def myfunction():
    global a_dict
    a_dict['s'] = 'whatevs'
    b_dict['s'] = 'lalala'
    a_dict = b_dict

a_dict = {'s':[], 'm':[]}
b_dict = {'s':[], 'm':[]}
myfunction()

Why does this not throw an error without also adding global b_dict to the function - as I'm writing to both dictionaries?

It sure does if I comment out the global a_dict ("'a_dict' referenced before assignment") - as I would expect.

mkrieger1
  • 14,486
  • 4
  • 43
  • 54

2 Answers2

1

You only need global foo when you want to assign to the global name foo. You are not assigning to b_dict; you are assigning to one of its keys, equivalent to b_dict.__setitem__('s', 'lalala'). Both uses of b_dict treat it as a free variable, since there is no local variable named b_dict defined.

The value of a free variable is taken from the closest enclosing scope (in this case, the global scope) where it is defined.

chepner
  • 446,329
  • 63
  • 468
  • 610
0

The fact of declaring a variable as global in a function allows you to use a variable outside that function. If there is no variable b declared inside it, Python is going to assume it is a global variable declared before the function call.

Janska
  • 11
  • 2