Skip to Content
Modern Python Standard Library Cookbook
book

Modern Python Standard Library Cookbook

by Alessandro Molina
August 2018
Intermediate to advanced
366 pages
10h 14m
English
Packt Publishing
Content preview from Modern Python Standard Library Cookbook

Dictionary with fallback

When working with configuration values, it's common to look them up in multiple places—maybe we load them from a configuration file—but we can override them with an environment variable or a command-line option, and in case the option is not provided, we can have a default value.

This can easily lead to long chains of if statements like these:

value = command_line_options.get('optname')
if value is None:
    value = os.environ.get('optname')
if value is None:
    value = config_file_options.get('optname')
if value is None:
    value = 'default-value'

This is annoying, and while for a single value it might be just annoying, it will tend to grow into a huge, confusing list of conditions as more options get added.

Command-line options ...

Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

Advanced Python Development: Using Powerful Language Features in Real-World Applications

Advanced Python Development: Using Powerful Language Features in Real-World Applications

Matthew Wilkes

Publisher Resources

ISBN: 9781788830829Supplemental Content