Here are some scenarios and tips for using the Chainmap class:
Simulates python 's internal seizure of named variables in a chain of mappings:
#python 3.4
Import Builtins
Import Collections
Pylookup = collections. Chainmap (Locals (), Globals (), VARs (Builtins))
Print (Pylookup)
In this example, the local scope naming, global scope naming, and built-in scope naming are chained together, the lookup will be local, then global, and finally the built-in scope.
Let the command line parameters take precedence over the operating system environment variable parameter, and the operating system environment variable parameter takes precedence over the default value example:
#python 3.4
Import Collections
Import OS, Argparse
Defaults = {' Color ': ' Red ', ' user ': ' Guest '}
Parser = Argparse. Argumentparser ()
Parser.add_argument ('-u ', '--user ')
Parser.add_argument ('-C ', '--color ')
namespace = Parser.parse_args ()
Command_line_args = {k:v for k, V in VARs (namespace). Items () if v}
Combined = collections. Chainmap (Command_line_args, Os.environ, defaults)
Print (combined[' color ')
Print (combined[' user ')
The resulting output is as follows:
Red
Guest
In this case, be aware of this line of code:
Collections. Chainmap (Command_line_args, Os.environ, defaults)
The front dictionary is the first to search, the last is the last search.
Cai Junsheng qq:9073204 Shenzhen
Examples and techniques of 5.3.1.1 Chainmap