Examples and techniques of 5.3.1.1 Chainmap

Source: Internet
Author: User
Tags vars

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

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.