This can be useful in declarative python. For example, below, FooDef and BarDef are the classes used to define a series of data structures that are then used by some package as its input or its configuration. This allows you a lot of flexibility in what is your input, and you do not need to write a parser.
# FooDef, BarDef are classes Foo_one = FooDef("This one", opt1 = False, valence = 3 ) Foo_two = FooDef("The other one", valence = 6, parent = Foo_one ) namelist = [] for i in range(6): namelist.append("nm%03d"%i) Foo_other = FooDef("a third one", string_list = namelist ) Bar_thing = BarDef( (Foo_one, Foo_two), method = 'depth-first')
Note that this configuration file uses a loop to create a list of names that are part of the Foo_other configuration. So, this configuration language comes with a very powerful “preprocessor” with an available runtime library. If you want to, say, find a complex log or extract things from a zip file and base64, decode them as part of generating your configuration (this approach is not recommended, of course, for cases where the input may be from an unreliable source ...)
The package reads the configuration using something like the following:
conf_globals = {}
So, finally, to the point, globals() is useful when using such a package if you want to carefully measure a number of definitions:
for idx in range(20): varname = "Foo_%02d" % i globals()[varname]= FooDef("one of several", id_code = i+1, scale_ratio = 2**i)
It is equivalent to writing
Foo_00 = FooDef("one of several", id_code = 1, scale_ratio=1) Foo_01 = FooDef("one of several", id_code = 2, scale_ratio=2) Foo_02 = FooDef("one of several", id_code = 3, scale_ratio=4) ... 17 more ...
An example of a package that gets its input by collecting a bunch of definitions from a python module is PLY (Python-lex-yacc) http://www.dabeaz.com/ply/ - in this case, the objects are mostly function objects, but the metadata from function objects (their names, docs, and order of definition) are also part of the input. This is not such a good example of using globals() . In addition, it is imported using the "configuration" - the latter is a regular python script, and not vice versa.
I used "declarative python" in several of the projects I was working on, and was able to use globals() when writing configurations for them. You, of course, could argue that this was due to a lack of a way to develop a "language" configuration. Using globals() in this way does not give very clear results; simply results that might be easier to maintain than writing dozens of nearly identical statements.
You can also use it to provide the values of the variables in the configuration file according to their names:
This method can be useful for any python module that defines a lot of tables and structures to make it easier to add elements to data without having to maintain links.