We're sorry but this app doesn't work properly without JavaScript enabled. Please enable it to continue.

This lesson's interactive features are locked, please to keep using them

Closure Practice

Doc2Doc should be able to add CSS styling to an HTML file. CSS uses selectors to identify the HTML element to add the style property. Styles are essentially a chain of keys and values.

p {
  color: red;
}
  • Selector: p (targets all <p> elements)
  • Property: color
  • Value: red

Assignment

Complete the css_styles function. It accepts a nested dictionary (initial_styles) as input, and returns a function (add_style).

  1. Because we're dealing with nested dictionaries here, the .copy() method will produce a shallow copy: the outer dict is a new object, but mutating inner dicts will still affect the original one. So, you should import copy and use copy.deepcopy() instead.

For example:

from collections.abc import Callable

initial_styles: dict[str, dict[str, str]] = {
    "body": {"background-color": "white", "color": "black"},
    "h1": {"font-size": "16px", "padding": "10px"},
}

add_style: Callable[[str, str, str], dict[str, dict[str, str]]] = css_styles(
    initial_styles
)

new_styles: dict[str, dict[str, str]] = add_style("p", "color", "grey")

# {
#    "body": {
#        "background-color": "white",
#        "color": "black"
#    },
#    "h1": {
#        "font-size": "16px",
#        "padding": "10px"
#    },
#    "p": {
#        "color": "grey",
#    }
# }

Tip

Remember, you can assign a value to a dictionary within a dictionary like so:

parent_dictionary[nested_dictionary_key][key] = value