#!/usr/bin/python3 # -*- coding: utf-8 -*- """ Namespaces implementation """ # Global namespace implementation print(__builtins__["globals"]()) print(globals()) print(type(globals())) print(dir(globals())) x = "thing" print(globals()) print(x) print(globals()["x"]) print(x is globals()["x"]) globals()["y"] = 100 print(y) # Local namespace def f(x: float, y: float) -> None: s = "foo" print(locals()) f(10.0, 0.5) """ globals() returns an actual reference to the dictionary that contains the global namespace. That means if you call globals(), save the return value, and subsequently define additional variables, then those new variables will show up in the dictionary that the saved return value points to: """ g = globals() print(g) x = "foo" y = 29 print(g is globals()) def f2() -> None: """ locals() behaves in the same way: """ s = "foo" loc = locals() print(loc) x = 20 print(loc) loc["s"] = "bar" print(s) print(loc is locals()) f2()