dict2css

A μ-library for constructing cascading style sheets from Python dictionaries.

Docs

Documentation Build Status Docs Check Status

Tests

Linux Test Status Windows Test Status macOS Test Status Coverage

PyPI

PyPI - Package Version PyPI - Supported Python Versions PyPI - Supported Implementations PyPI - Wheel

Anaconda

Conda - Package Version Conda - Platform

Activity

GitHub last commit GitHub commits since tagged version Maintenance PyPI - Downloads

QA

CodeFactor Grade Flake8 Status mypy status

Other

License GitHub top language Requirements Status

dict2css provides an API similar to the json and toml modules, with dump() and load() functions. The dump() function takes a mapping of CSS selectors to mappings of CSS properties. Each property value may, optionally, be a two-element tuple containing the value and the string “important”. The load() function returns a mapping with the same structure.

Installation

python3 -m pip install dict2css --user

Contents

dict2css

A μ-library for constructing cascasing style sheets from Python dictionaries.

See also

css-parser, which this library builds upon.

Data:

IMPORTANT

The string 'important'.

Style

Type annotation representing a style for make_style() and dumps().

Functions:

dumps(styles, *[, indent, …])

Construct a cascading style sheet from a dictionary.

dump(styles, fp, *[, indent, …])

Construct a style sheet from a dictionary and write it to fp.

loads(styles)

Parse a style sheet and return its dictionary representation.

load(fp)

Parse a cascading style sheet from the given file and return its dictionary representation.

make_style(selector, styles)

Create a CSS Style Rule from a dictionary.

Classes:

StyleSheet()

Represents a CSS style sheet.

IMPORTANT = 'important'

Type:    str

The string 'important'.

Style

Type annotation representing a style for make_style() and dumps().

The keys are CSS properties.

The values can be either:

  • A str, float or None, giving the value of the property.

  • A tuple of the property’s value (as above) and the priority such as IMPORTANT (which sets !important on the property).

Alias of Mapping[str, Union[Sequence, str, int, None]]

dumps(styles, *, indent='\t', trailing_semicolon=False, indent_closing_brace=False, minify=False)[source]

Construct a cascading style sheet from a dictionary.

styles is a mapping of CSS selector strings to styles, which map property names to their values:

styles = {".wy-nav-content": {"max-width": (px(1200), IMPORTANT)}}
print(dumps(styles))
.wy-nav-content {
    max-width: 1200px !important
}

See the Style object for more information on the layout.

The keys can also be media at-rules, with the values mappings of property names to their values:

styles = {
    "@media screen and (min-width: 870px)": {
        ".wy-nav-content": {"max-width": (px(1200), IMPORTANT)},
        },
    }
print(dumps(styles))
@media screen and (min-width: 870px) {
    .wy-nav-content {
        max-width: 1200px !important
    }
}
Parameters
  • styles (Mapping[str, Union[Mapping[str, Union[Sequence, str, int, None]], Mapping]]) – A mapping of CSS selectors to styles.

  • indent (str) – The indent to use, such as a tab (\t), two spaces or four spaces. Default '\t'.

  • trailing_semicolon (bool) – Whether to add a semicolon to the end of the final property. Default False.

  • indent_closing_brace (bool) – Default False.

  • minify (bool) – Minify the CSS. Overrides all other options. Default False.

Return type

str

Returns

The style sheet as a string.

Changed in version 0.2.0: Added support for media at-rules.

dump(styles, fp, *, indent='\t', trailing_semicolon=False, indent_closing_brace=False, minify=False)[source]

Construct a style sheet from a dictionary and write it to fp.

styles = {".wy-nav-content": {"max-width": (px(1200), IMPORTANT)}}
dump(styles, ...)
.wy-nav-content {
    max-width: 1200px !important
}

See the Style object for more information on the layout.

The keys can also be media at-rules, with the values mappings of property names to their values:

styles = {
    "@media screen and (min-width: 870px)": {
        ".wy-nav-content": {"max-width": (px(1200), IMPORTANT)},
        },
    }
dump(styles, ...)
@media screen and (min-width: 870px) {
    .wy-nav-content {
        max-width: 1200px !important
    }
}
Parameters
  • styles (Mapping[str, Union[Mapping[str, Union[Sequence, str, int, None]], Mapping]]) – A mapping of CSS selectors to styles.

  • fp (Union[str, Path, PathLike, IO]) – An open file handle, or the filename of a file to write to.

  • indent (str) – The indent to use, such as a tab (\t), two spaces or four spaces. Default '\t'.

  • trailing_semicolon (bool) – Whether to add a semicolon to the end of the final property. Default False.

  • indent_closing_brace (bool) – Default False.

  • minify (bool) – Minify the CSS. Overrides all other options. Default False.

Changed in version 0.2.0:
loads(styles)[source]

Parse a style sheet and return its dictionary representation.

New in version 0.2.0.

Parameters

styles (str)

Return type

MutableMapping[str, MutableMapping[str, Any]]

Returns

The style sheet as a dictionary.

load(fp)[source]

Parse a cascading style sheet from the given file and return its dictionary representation.

New in version 0.2.0.

Parameters

fp (Union[str, Path, PathLike, IO]) – An open file handle, or the filename of a file to write to.

Return type

MutableMapping[str, MutableMapping[str, Any]]

Returns

The style sheet as a dictionary.

class StyleSheet[source]

Represents a CSS style sheet.

Methods:

add(rule)

Add the rule to the style sheet.

add_style(selector, styles)

Add a style to the style sheet.

add_media_styles(media_query, styles)

Add a set of styles for a media query to the style sheet.

tostring()

Returns the style sheet as a string.

add(rule)[source]

Add the rule to the style sheet.

Parameters

rule (css_parser.css.CSSRule)

Return type

int

add_style(selector, styles)[source]

Add a style to the style sheet.

Parameters
add_media_styles(media_query, styles)[source]

Add a set of styles for a media query to the style sheet.

New in version 0.2.0.

Parameters
tostring()[source]

Returns the style sheet as a string.

Return type

str

make_style(selector, styles)[source]

Create a CSS Style Rule from a dictionary.

Parameters
Return type

css_parser.css.CSSStyleRule

dict2css.helpers

Helper functions.

New in version 0.2.0.

Functions:

em(val)

Helper function to format a number as a value in em.

px(val)

Helper function to format a number as a value in pixels.

rem(val)

Helper function to format a number as a value in rem.

em(val)[source]

Helper function to format a number as a value in em.

Parameters

val (Union[int, float, str])

Return type

str

px(val)[source]

Helper function to format a number as a value in pixels.

Parameters

val (Union[int, float, str])

Return type

str

rem(val)[source]

Helper function to format a number as a value in rem.

Parameters

val (Union[int, float, str])

Return type

str

dict2css.serializer

Serializer for cascading style sheets.

New in version 0.2.0.

Classes:

CSSSerializer(*[, indent, …])

Serializes a StyleSheet and its parts.

class CSSSerializer(*, indent='\t', trailing_semicolon=False, indent_closing_brace=False, minify=False)[source]

Serializes a StyleSheet and its parts.

This controls the formatting of the style sheet.

Parameters
  • indent (str) – The indent to use, such as a tab (\t), two spaces or four spaces. Default '\t'.

  • trailing_semicolon (bool) – Whether to add a semicolon to the end of the final property. Default False.

  • indent_closing_brace (bool) – Default False.

  • minify (bool) – Minify the CSS. Overrides all other options. Default False.

Methods:

reset_style()

Reset the serializer to its default style.

use()

Contextmanager to use this serializer for the scope of the with block.

reset_style()[source]

Reset the serializer to its default style.

use()[source]

Contextmanager to use this serializer for the scope of the with block.

Return type

Iterator

Changelog

0.2.2

Changed the build backend from setuptools to whey.

0.2.1

Import Iterator from typing rather than from collections.

0.2.0

dict2css.dumps()

Added support for media at-rules.

dict2css.dump()

0.1.0

Initial release.

Downloading source code

The dict2css source code is available on GitHub, and can be accessed from the following URL: https://github.com/sphinx-toolbox/dict2css

If you have git installed, you can clone the repository with the following command:

git clone https://github.com/sphinx-toolbox/dict2css
Cloning into 'dict2css'...
remote: Enumerating objects: 47, done.
remote: Counting objects: 100% (47/47), done.
remote: Compressing objects: 100% (41/41), done.
remote: Total 173 (delta 16), reused 17 (delta 6), pack-reused 126
Receiving objects: 100% (173/173), 126.56 KiB | 678.00 KiB/s, done.
Resolving deltas: 100% (66/66), done.
Alternatively, the code can be downloaded in a ‘zip’ file by clicking:
Clone or download –> Download Zip
Downloading a 'zip' file of the source code.

Downloading a ‘zip’ file of the source code

Building from source

The recommended way to build dict2css is to use tox:

tox -e build

The source and wheel distributions will be in the directory dist.

If you wish, you may also use pep517.build or another PEP 517-compatible build tool.

License

dict2css is licensed under the MIT License

A short and simple permissive license with conditions only requiring preservation of copyright and license notices. Licensed works, modifications, and larger works may be distributed under different terms and without source code.

Permissions Conditions Limitations
  • Commercial use
  • Modification
  • Distribution
  • Private use
  • Liability
  • Warranty

Copyright (c) 2021 Dominic Davis-Foster

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE
OR OTHER DEALINGS IN THE SOFTWARE.

View the Function Index or browse the Source Code.

Browse the GitHub Repository