#!/usr/bin/python3 # -*- coding: utf-8 -*- """ Modifying stuff out of your scope is generally a bad idea. The use of the global keyword is usually indicative of poor programming, though very rarely it may be the best solution (not in this class). """ # global x1 = "global" def f1() -> None: """Modifies global scoped variable""" global x1 x1 = "changedlocal" print(x1) f1() print(x1) # is the same as: x2 = "global2" def f2() -> None: """Modifies global scoped variable""" globals()["x2"] = "changedlocal" print(x2) f2() print(x2) def f3() -> None: """ Want to modify enclosing scope? Don't do this; it just modifies the global, and would even create a global if it did not exist. global specifically accesses the global namespace. """ x3 = "enclosing" def g3() -> None: global x3 x3 = "changedlocal" g3() print(x3) f3() print(x3) def f4() -> None: """Instead, do this to modify the enclosing scope.""" x4 = "enclosing" def g4() -> None: nonlocal x4 x4 = "changedlocal" g4() print(x4) f4() print("print(x4) is an error")