liveBook · Manning

Configuration

As explained in Practices of the Python Pro

Configuration is a set of values or steps that specifies how a software component or operation should behave.

Configuration is information that tells a program how to behave. A dictionary can hold choices and outcomes separately from the code that uses them, much like a menu separates available options from the process of taking an order. This makes behavior easier to read, change, and extend than a growing chain of conditional statements. section 7.1.2

A practical configuration pattern helps you:

  • Map an input value directly to an outcome, such as a choice letter to a message. section 7.1.2
  • Extract response formats into a dictionary and use a default when a request is unknown. section 9.2.1
  • Add a new behavior by adding a mapping, rather than adding another conditional branch. section 7.1.2 section 9.2.2

Mapping choices to messages

Instead of writing several conditional branches, keep the choices in data:\n\nchoices = {'A': 'apples', 'B': 'bats'}\nprint(f'{choice} is for {choices[choice]}')\n\nThe program now has one stable execution step and a configuration mapping that can grow independently. section 7.1.2

Listing 9.3. An endpoint with extracted configuration
...

def random_food(request):
    food = random.choice(FOODS)

    formats = {                                               #1
        'application/json': json.dumps({'food': food}),
        'application/xml': f'<response><food>{food}</food></response>',
    }

    return formats.get(request.headers.get('Accept'), food)   #2

Compare an endpoint that stores JSON and XML response behavior in a dictionary, then selects the matching format or returns a default. section 9.2.1

How Practices of the Python Pro covers it

How deep it goes
Explains dictionary mappings, fallbacks, readability, complexity, and extensibility through worked Python examples.
Examples
Uses choice-to-message mappings, HTTP response formats, JSON and XML serializers, and Plotly graph configuration.
What it assumes
Assumes Python conditionals and functions, then builds toward dictionaries, mappings, and separated responsibilities.
What you can do after
Apply it via Python dictionaries to replace growing conditionals and select response formats with fallbacks.
How it connects
Connects configuration with conditional logic, dictionaries, loose coupling, declarative programming, and separation of concerns.

Also explained in

Compare how 23 books explain configuration →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Practices of the Python Pro. The section links point to the parts of the book it draws on.