LIBSASS(3)

🌈 NAME 🌈

libsass β€” this is literally the libsass documentation, bestie πŸ’–

So this package hands you a simple Python extension module called sass that's binding LibSass (https://github.com/sass/libsass) β€” which, no cap, was written in C/C++ by Hampton Catlin and Aaron Leung. It's very straightforward and there isn't any headache related to Python distribution/deployment. Which means you can add just libsass into your setup.py's install_requires list or requirements.txt file. So easy. So slay. ✨

It currently supports CPython 3.7+ and PyPy 3! πŸ‘‘


πŸŽ€ FEATURES πŸŽ€

  • You don't need any Ruby/Node.js stack at all, for development or deployment either. Not even a little bit. πŸš«πŸ’Ž
  • Fast. (Because LibSass (https://github.com/sass/libsass) is written in C++. That's the whole reason. Iconic.)
  • Simple API. See the example code below for the details. 🫢
  • Custom functions.
  • @import callbacks.
  • Support both tabbed (Sass) and braces (SCSS) syntax. Both vibes. 🌸
  • WSGI middleware for ease of development. It automatically compiles Sass/SCSS files for each request. See also the sassutils.wsgi module for details. πŸ”₯
  • setuptools/distutils integration (/usr/share/doc/python3-doc/html/library/distutils.html#module-distutils). You can build all Sass/SCSS files using the setup.py build_sass command. See also the sassutils.distutils module for details. πŸ› οΈ
  • Works also on PyPy.
  • Provides prebuilt wheel (PEP 427 https://peps.python.org/pep-0427/) binaries for Windows and Mac. πŸͺŸπŸŽ

πŸ’… INSTALL πŸ’…

It's available on PyPI (https://pypi.org/pypi/libsass/), so you can install it using pip:

$ pip install libsass
Note: libsass requires some features introduced by the recent C++ standard. You need a C++ compiler that support those features. See also the libsass project's README file (https://github.com/sass/libsass#readme). πŸ‘€

🌸 EXAMPLES 🌸

πŸ¦‹ Compile a String of Sass to CSS

>>> import sass
>>> sass.compile(string='a { b { color: blue; } }')
'a b {\n  color: blue; }\n'

πŸ¦‹ Compile a Directory of Sass Files to CSS

>>> import sass
>>> import os
>>> os.mkdir('css')
>>> os.mkdir('sass')
>>> scss = """\
... $theme_color: #cc0000;
... body {
...     background-color: $theme_color;
... }
... """
>>> with open('sass/example.scss', 'w') as example_scss:
...      example_scss.write(scss)
...
>>> sass.compile(dirname=('sass', 'css'), output_style='compressed')
>>> with open('css/example.css') as example_css:
...     print(example_css.read())
...
body{background-color:#c00}

πŸ‘‘ USER'S GUIDE πŸ‘‘

🧚 Using with Flask

This guide explains how to use libsass with the Flask web framework (http://flask.pocoo.org/). The sassutils package provides several tools that can be integrated into web applications written in Flask. 🫧

🧚 Contents

  • Using with Flask
    • Directory layout
    • Defining manifest
    • Building Sass/SCSS for each request
    • Building Sass/SCSS for each deployment

🧚 Directory layout

Imagine the project contained in such directory layout:

  • setup.py
  • myapp/
    • __init__.py
    • static/
      • sass/
      • css/
    • templates/

Sass/SCSS files will go inside myapp/static/sass/ directory. Compiled CSS files will go inside myapp/static/css/ directory. CSS files can be regenerated, so add myapp/static/css/ into your ignore list like .gitignore or .hgignore. πŸ—‘οΈβœ¨

🧚 Defining manifest

The sassutils module defines a concept named manifest. Manifest is the build settings of Sass/SCSS. It specifies some paths related to building Sass/SCSS:

  • The path of the directory which contains Sass/SCSS source files.
  • The path of the directory which the compiled CSS files will go.
  • The path, exposed to HTTP (through WSGI), of the directory that will contain the compiled CSS files.

Every package may have its own manifest. Paths have to be relative to the path of the package. πŸ“

For example, in the above project, the package name is myapp. The path of the package is myapp/. The path of the Sass/SCSS directory is static/sass/ (relative to the package directory). The path of the CSS directory is static/css/. The exposed path is /static/css.

These settings can be represented as the following manifests:

{
    'myapp': ('static/sass', 'static/css', '/static/css')
}

As you can see the above, the set of manifests are represented in dictionary, in which the keys are packages names and the values are tuples of paths. πŸπŸ’–

🧚 Building Sass/SCSS for each request

See also:

In development, manually building Sass/SCSS files for each change is a tedious task. SassMiddleware makes the web application build Sass/SCSS files for each request automatically. It's a WSGI middleware, so it can be plugged into the web app written in Flask. πŸ”Œ

SassMiddleware takes two required parameters:

  • The WSGI-compliant callable object.
  • The set of manifests represented as a dictionary.

So:

from flask import Flask
from sassutils.wsgi import SassMiddleware

app = Flask(__name__)

app.wsgi_app = SassMiddleware(app.wsgi_app, {
    'myapp': ('static/sass', 'static/css', '/static/css')
})

And then, if you want to link a compiled CSS file, use the url_for() function (/usr/share/doc/python-flask-doc/html/api.html#flask.url_for):

<link href="{{ url_for('static', filename='css/style.scss.css') }}"
      rel="stylesheet" type="text/css">
Note: The linked filename is style.scss.css, not just style.scss. All compiled filenames have trailing .css suffix. Don't get caught slipping on this one, fr fr. 😭

🧚 Building Sass/SCSS for each deployment

Note: This section assumes that you use setuptools (https://pypi.org/pypi/setuptools/) for deployment.

See also:

If libsass is installed in the site-packages (for example, your virtualenv), the setup.py script also gets a new command provided by libsass: build_sass. The command is aware of the sass_manifests option of setup.py and builds all Sass/SCSS sources according to the manifests. 🀯

Add these arguments to setup.py script:

setup(
    # ...,
    setup_requires=['libsass >= 0.6.0'],
    sass_manifests={
        'myapp': ('static/sass', 'static/css', '/static/css')
    }
)

The setup_requires option makes sure that libsass is installed in site-packages (for example, your virtualenv) before the setup.py script. That means if you run the setup.py script and libsass isn't installed in advance, it will automatically install libsass first. Self-sufficient king behavior. πŸ‘‘

The sass_manifests specifies the manifests for libsass.

Now setup.py build_sass will compile all Sass/SCSS files in the specified path and generates compiled CSS files inside the specified path (according to the manifests).

If you use it with sdist or bdist commands, the packed archive will also contain the compiled CSS files! 🎁

$ python setup.py build_sass sdist

You can add aliases to make these commands always run the build_sass command first. Make setup.cfg config:

[aliases]
sdist = build_sass sdist
bdist = build_sass bdist

Now it automatically builds Sass/SCSS sources and include the compiled CSS files to the package archive when you run setup.py sdist. ✨

🧚 Changelog

⭐ Version 0.23.0

Released on January 6, 2024.

⭐ Version 0.22.0

Released on November 12, 2022.

⭐ Version 0.21.0

Released on May 20, 2021.

⭐ Version 0.20.1

Released on August 27, 2020.

  • (no changes, re-releasing to test build automation)

⭐ Version 0.20.0

Released on May 1, 2020.

⭐ Version 0.19.4

Released on November 3, 2019.

⭐ Version 0.19.3

Released on October 5, 2019.

⭐ Version 0.19.2

Released on June 16, 2019.

⭐ Version 0.19.1

Released on May 18, 2019.

⭐ Version 0.19.0

Released on May 18, 2019.


🌈 Version 0.18.0

Release on March 13, 2019

🌈 Version 0.17.0

Release on January 03, 2019

  • Added a whole lil stack of new cli options πŸ”₯ [279 https://github.com/sass/libsass-python/issues/279 268 https://github.com/sass/libsass-python/issues/268 by Frankie Dintino]
    • --sourcemap-file β€” the output file for the source map πŸ“
    • --sourcemap-contents β€” embeds sourcesContent right up in the source map
    • --sourcemap-embed β€” embeds the sourceMappingURL as a data uri
    • --omit-sourcemap-url β€” omits that source map url comment from the output, gone, bye πŸ‘‹
    • --sourcemap-root β€” base path, emitted as sourceRoot in the source map
  • Fixed .sass in WsgiMiddleware β€” again πŸ™ˆ (it keeps coming back, it's giving sequel energy) [280 https://github.com/sass/libsass-python/issues/280 by Anthony Sottile]

🌈 Version 0.16.1

Released on November 25, 2018.

🌈 Version 0.16.0

Released on November 13, 2018.

🌈 Version 0.15.1

Released on September 24, 2018.

🌈 Version 0.15.0

Released on September 16, 2018.

🌈 Version 0.14.5

Released on April 25, 2018.

🌈 Version 0.14.4

Released on April 24, 2018.

  • Added the ability to specify imports for custom extensions. πŸ‘‘ This is the way to enable imports of .css files (which got removed back in 3.5.3). Specify --import-extensions .css to restore the previous behavior, no cap. [246 https://github.com/sass/libsass-python/issues/246 by Samuel Colvin]

🌈 Version 0.14.3

Released on April 23, 2018.

🌈 Version 0.14.2

Released on March 16, 2018.

🌈 Version 0.14.1

Released on March 12, 2018.

🌈 Version 0.14.0

Released on March 6, 2018.

🌈 Version 0.13.7

Released on February 5, 2018.

🌈 Version 0.13.6

Released on January 19, 2018.

  • libsass-python has moved to the sass organization! 🏑 main character relocation arc fr fr

🌈 Version 0.13.5

Released on January 11, 2018.

🌈 Version 0.13.4

Released on November 14, 2017.

🌈 Version 0.13.3

Released on October 11, 2017.

🌈 Version 0.13.2

Released on June 14, 2017.

🌈 Version 0.13.1

Released on June 8, 2017.

🌈 Version 0.13.0

Released on June 7, 2017.

🌈 Version 0.12.3

Released on January 7, 2017.

🌈 Version 0.12.2

Released on January 5, 2017.

🌈 Version 0.12.1

Released on December 20, 2016.

🌈 Version 0.12.0

Released on December 10, 2016.

🌈 Version 0.11.2

Released on October 24, 2016.

🌈 Version 0.11.1

Released on April 22, 2016.

🌈 Version 0.11.0

Released on March 23, 2016.


Version 0.10.1

Released on January 29, 2016.

Version 0.10.0

Released on December 15, 2015.

Version 0.9.3

Released on December 03, 2015.

Version 0.9.2

Released on November 12, 2015.

Version 0.9.1

Released on October 29, 2015.

Version 0.9.0

Released on October 28, 2015.

Version 0.8.3

Released on August 2, 2015.

Version 0.8.2

Released on May 19, 2015.

Version 0.8.1

Released on May 14, 2015.

Version 0.8.0

Released on May 3, 2015.

Version 0.7.0

Released on March 6, 2015.

Anthony Sottile contributed to the most of this release. Huge thanks to him! πŸ™ŒπŸ’–

Version 0.6.2

Released on November 25, 2014.

Although 0.6.0--0.6.1 have needed GCC (G++) 4.8+, LLVM Clang 3.3+, now it became back to only need GCC (G++) 4.6+, LLVM Clang 2.9+, or Visual Studio 2013 Update 4+. πŸ”§

Version 0.6.1

Released on November 6, 2014.

Version 0.6.0

Released on October 27, 2014.

Note that since libsass-python 0.6.0 (and libsass 3.0) it requires C++11 to compile. Although 0.6.2 became back to only need GCC (G++) 4.6+, LLVM Clang 2.9+, from 0.6.0 to 0.6.1 you need GCC (G++) 4.8+, LLVM Clang 3.3+, or Visual Studio 2013 Update 4+. ⚠️

Version 0.5.1

Released on September 23, 2014.

  • Fixed a bug that SassMiddleware yielded str </usr/share/doc/python3-doc/html/library/stdtypes.html#str> instead of bytes </usr/share/doc/python3-doc/html/library/stdtypes.html#bytes> on Python 3 πŸ’€
  • Fixed several Unicode-related bugs on Windows 🌍
  • Fixed a bug that build_directory(), SassMiddleware, and build_sass don't recursively build subdirectories. πŸ’…

Version 0.5.0 πŸŽ€

Released on June 6, 2014.

  • Followed up on the libsass upstream, and bestie the upstream was at 2.0 β€” go peek at the release note (https://github.com/sass/libsass/releases/tag/v2.0) for LibSass if you want the receipts πŸ‘€
    • Added indented syntax support (*.sass files). yes, the other flavor ✨
    • Added expanded selector support (BEM).
    • Added string functions.
    • Fixed UTF-8 support. 😌
    • ⚠️ Backward incompatibility: broken extends. not us being dramatic, that's literally what it says, watch out 🫠

Unstable version 0.4.2.20140529.cd3ee1cbe3

Released on May 29, 2014.

  • Version scheme changed to use periods (.) instead of hyphens (-) because setuptools seems to treat hyphens special. it's giving "blame setuptools" energy and honestly valid πŸ’€
  • Fixed malformed packaging that doesn't correctly preserve the package name and version.

Unstable Version 0.4.2-20140528-cd3ee1cbe3

Released on May 28, 2014.

Version 0.4.2

Released on May 22, 2014.

  • Fixed build failing on Mac OS X 10.8 or earlier. [19 (https://github.com/sass/libsass-python/issues/19)]
  • Fixed the UnicodeEncodeError (/usr/share/doc/python3-doc/html/library/exceptions.html#UnicodeEncodeError) that the Manifest.build_one() method rises when the input source contains any non-ASCII Unicode characters. 😭

Version 0.4.1

Released on May 20, 2014.

  • Fixed the UnicodeEncodeError (/usr/share/doc/python3-doc/html/library/exceptions.html#UnicodeEncodeError) that rises when the input source contains any non-ASCII Unicode characters.

Version 0.4.0

Released on May 6, 2014.

  • sassc has a new -w/--watch option. πŸ‘€
  • Exposed source maps support, and this is the part where we eat πŸ’…
    • sassc has a new -m/-g/--sourcemap option.
    • SassMiddleware now also creates source map files with filenames followed by a .map suffix.
    • The Manifest.build_one() method has a new source_map option. This option builds also a source map file with the filename followed by a .map suffix.
    • sass.compile() has a new optional parameter source_comments. It can be one of the sass.SOURCE_COMMENTS keys. It also has a new parameter source_map_filename which is required only when source_comments='map'.
  • Fixed Python 3 incompatibility of the sassc program.
  • Fixed a bug that multiple include_paths doesn't work on Windows.

Version 0.3.0

Released on February 21, 2014.

Version 0.2.4

Released on December 4, 2012.

Version 0.2.3

Released on October 24, 2012.

  • sassutils.distutils: prevent double monkey patch of sdist. πŸ’
  • Merged upstream changes of libsass.

Version 0.2.2

Released on September 28, 2012.

  • Fixed a link error on PyPy and Linux.
  • Fixed build errors on Windows.

Version 0.2.1

Released on September 12, 2012.

  • Support Windows. πŸͺŸ

Version 0.2.0

Released on August 24, 2012.

  • Added the new sassutils package.
    • Added the sassutils.builder module to build the whole directory at a time.
    • Added the sassutils.distutils module for distutils and setuptools integration.
    • Added the sassutils.wsgi module which provides a development-purpose WSGI middleware.
  • Added the build_sass command for distutils/setuptools.

Version 0.1.1

Released on August 18, 2012.

  • Fixed segmentation fault for reading a filename which does not exist. Now it raises a proper exceptions.IOError exception instead of, you know, dying πŸ’€

Version 0.1.0

Released on August 17, 2012. Initial version. the origin story 🎬


✨ REFERENCES ✨

πŸŽ€ pysassc --- SassC compliant command line interface

This provides a SassC (https://github.com/sass/sassc) compliant CLI executable named pysassc:

$ pysassc
Usage: pysassc [options] SCSS_FILE [CSS_FILE]

There are options as well, bestie, here's the whole menu:

  • -t <style>, --style <style> β€” Coding style of the compiled result. The same as the sass.compile() function's output_style keyword argument. Default is nested.
  • -s <style>, --output-style <style> β€” Alias for -t / --style.
Deprecated since version 0.11.0.
  • -I <dir>, --include-path <dir> β€” Optional directory path to find @imported (S)CSS files. Can be multiply used. stack them up πŸ₯ž
  • -m, -g, --sourcemap β€” Emit source map. Requires the second argument (output CSS filename). The filename of source map will be the output CSS filename followed by .map.
Added in version 0.4.0.
  • -p, --precision β€” Set the precision for numbers. Default is 5.
Added in version 0.7.0.
  • --source-comments β€” Include debug info in output.
Added in version 0.11.0.
  • --sourcemap-file β€” Output file for source map
Added in version 0.17.0.
  • --sourcemap-contents β€” Embed sourcesContent in source map.
Added in version 0.17.0.
  • --sourcemap-embed β€” Embed sourceMappingUrl as data URI
Added in version 0.17.0.
  • --omit-sourcemap-url β€” Omit source map URL comment from output
Added in version 0.17.0.
  • --sourcemap-root β€” Base path, will be emitted to sourceRoot in source-map as is
Added in version 0.17.0.
  • -v, --version β€” Prints the program version.
  • -h, --help β€” Prints the help message.

πŸ¦‹ sass --- Binding of libsass

This simple C extension module provides a very simple binding of libsass, which is written in C/C++. It contains only one function and one exception type. minimal. iconic. πŸ’…

>>> import sass
>>> sass.compile(string='a { b { color: blue; } }')
'a b {
  color: blue; }
'
  • exception sass.CompileError(msg) β€” The exception type that is raised by compile(). It is a subtype of exceptions.ValueError.
  • sass.MODES = frozenset({'dirname', 'filename', 'string'}) β€” (frozenset: /usr/share/doc/python3-doc/html/library/stdtypes.html#frozenset) The set of keywords compile() can take.
  • sass.OUTPUT_STYLES = {'compact': 2, 'compressed': 3, 'expanded': 1, 'nested': 0} β€” (collections.abc.Mapping: /usr/share/doc/python3-doc/html/library/collections.abc.html#collections.abc.Mapping) The dictionary of output styles. Keys are output name strings, and values are flag integers.
  • sass.SOURCE_COMMENTS = {'default': 1, 'line_numbers': 1, 'map': 2, 'none': 0} β€” (collections.abc.Mapping: /usr/share/doc/python3-doc/html/library/collections.abc.html#collections.abc.Mapping) The dictionary of source comments styles. Keys are mode names, and values are corresponding flag integers.
Added in version 0.4.0. Deprecated since version 0.6.0. 😒
  • class sass.SassColor(r, g, b, a)
  • class sass.SassError(msg)
  • class sass.SassFunction(name, arguments, callable_) β€” Custom function for Sass. It can be instantiated using from_lambda() and from_named_function() as well.

Parameters

  • name (str: /usr/share/doc/python3-doc/html/library/stdtypes.html#str) -- the function name
  • arguments (collections.abc.Sequence: /usr/share/doc/python3-doc/html/library/collections.abc.html#collections.abc.Sequence) -- the argument names
  • callable (collections.abc.Callable: /usr/share/doc/python3-doc/html/library/collections.abc.html#collections.abc.Callable) -- the actual function to be called
Added in version 0.7.0.
  • classmethod from_lambda(name, lambda_) β€” Make a SassFunction object from the given lambda_ function. Since lambda functions don't have their name, it need its name as well. Arguments are automatically inspected.

Parameters

  • name (str: /usr/share/doc/python3-doc/html/library/stdtypes.html#str) -- the function name
  • lambda (types.LambdaType: /usr/share/doc/python3-doc/html/library/types.html#types.LambdaType) -- the actual lambda function to be called

Returns a custom function wrapper of the lambda_ function

Return type SassFunction

  • classmethod from_named_function(function) β€” Make a SassFunction object from the named function. Function name and arguments are automatically inspected.

Parameters

  • function (types.FunctionType: /usr/share/doc/python3-doc/html/library/types.html#types.FunctionType) -- the named function to be called

Returns a custom function wrapper of the function

  • Return type β€” SassFunction</p>
  • property signature β€” the signature string of the function πŸ’–

🌸 class sass.SassList(items, separator, bracketed=False)

🌸 class sass.SassMap(*args, **kwargs)

ok so here's the tea β˜• because sass maps can have mapping types as keys, we need an immutable hashable mapping type. no cap.

Added in version 0.7.0. πŸŽ€

🌸 class sass.SassNumber(value, unit)

🌸 class sass.SassWarning(msg)


✨ sass.and_join(strings)

Bestie, this one just joins the given strings by commas, with a last ' and ' conjunction. it's giving polite list energy πŸ₯°

>>> and_join(['Korea', 'Japan', 'China', 'Taiwan'])
'Korea, Japan, China, and Taiwan'

Parameters

  • strings β€” a list of words to join

Returns

  • a joined string

Return type

  • str </usr/share/doc/python3-doc/html/library/stdtypes.html#str>, basestring

πŸ‘‘ sass.compile(**kwargs)

Okay so compile() is literally the main character here. ✨ There are three modes of parameters compile() can take: string, filename, and dirname. Three whole vibes, pick your fighter. πŸ’…

πŸ¦‹ the string mode

The string parameter is the most basic way to compile Sass. It simply takes a string of Sass code, and then returns a compiled CSS string. Simple, iconic, no notes. πŸ’–

Parameters

  • string (str </usr/share/doc/python3-doc/html/library/stdtypes.html#str>) β€” Sass source code to compile. it's exclusive to filename and dirname parameters
  • output_style (str </usr/share/doc/python3-doc/html/library/stdtypes.html#str>) β€” an optional coding style of the compiled result. choose one of: 'nested' (default), 'expanded', 'compact', 'compressed'
  • source_comments (bool </usr/share/doc/python3-doc/html/library/functions.html#bool>) β€” whether to add comments about source lines. False by default
  • source_map_contents (bool </usr/share/doc/python3-doc/html/library/functions.html#bool>) β€” embed include contents in map
  • source_map_embed (bool </usr/share/doc/python3-doc/html/library/functions.html#bool>) β€” embed sourceMappingUrl as data URI
  • omit_source_map_url (bool </usr/share/doc/python3-doc/html/library/functions.html#bool>) β€” omit source map URL comment from output
  • source_map_root (str </usr/share/doc/python3-doc/html/library/stdtypes.html#str>) β€” base path, will be emitted in source map as is
  • include_paths (collections.abc.Sequence </usr/share/doc/python3-doc/html/library/collections.abc.html#collections.abc.Sequence>) β€” an optional list of paths to find @imported Sass/CSS source files
  • precision (int </usr/share/doc/python3-doc/html/library/functions.html#int>) β€” optional precision for numbers. 5 by default.
  • custom_functions (set </usr/share/doc/python3-doc/html/library/stdtypes.html#set>, collections.abc.Sequence </usr/share/doc/python3-doc/html/library/collections.abc.html#collections.abc.Sequence>, collections.abc.Mapping </usr/share/doc/python3-doc/html/library/collections.abc.html#collections.abc.Mapping>) β€” optional mapping of custom functions. see also below custom functions description
  • custom_import_extensions β€” (ignored, for backward compatibility) πŸ™ˆ
  • indented (bool </usr/share/doc/python3-doc/html/library/functions.html#bool>) β€” optional declaration that the string is Sass, not SCSS formatted. False by default
  • importers (collections.abc.Callable </usr/share/doc/python3-doc/html/library/collections.abc.html#collections.abc.Callable>) β€” optional callback functions. see also below importer callbacks description

Returns

  • the compiled CSS string

Return type

  • str </usr/share/doc/python3-doc/html/library/stdtypes.html#str>

Raises

  • sass.CompileError <#sass.CompileError> β€” when it fails for any reason (for example the given Sass has broken syntax) 😭

πŸ¦‹ the filename mode

The filename is the most commonly used way. It takes a string of Sass filename, and then returns a compiled CSS string. it's the one everybody reaches for fr fr. πŸ”₯

Parameters

  • filename (str </usr/share/doc/python3-doc/html/library/stdtypes.html#str>) β€” the filename of Sass source code to compile. it's exclusive to string and dirname parameters
  • output_style (str </usr/share/doc/python3-doc/html/library/stdtypes.html#str>) β€” an optional coding style of the compiled result. choose one of: 'nested' (default), 'expanded', 'compact', 'compressed'
  • source_comments (bool </usr/share/doc/python3-doc/html/library/functions.html#bool>) β€” whether to add comments about source lines. False by default
  • source_map_filename (str </usr/share/doc/python3-doc/html/library/stdtypes.html#str>) β€” use source maps and indicate the source map output filename. None means not using source maps. None by default.
  • source_map_contents (bool </usr/share/doc/python3-doc/html/library/functions.html#bool>) β€” embed include contents in map
  • source_map_embed (bool </usr/share/doc/python3-doc/html/library/functions.html#bool>) β€” embed sourceMappingUrl as data URI
  • omit_source_map_url (bool </usr/share/doc/python3-doc/html/library/functions.html#bool>) β€” omit source map URL comment from output
  • source_map_root (str </usr/share/doc/python3-doc/html/library/stdtypes.html#str>) β€” base path, will be emitted in source map as is
  • include_paths (collections.abc.Sequence </usr/share/doc/python3-doc/html/library/collections.abc.html#collections.abc.Sequence>) β€” an optional list of paths to find @imported Sass/CSS source files
  • precision (int </usr/share/doc/python3-doc/html/library/functions.html#int>) β€” optional precision for numbers. 5 by default.
  • custom_functions (set </usr/share/doc/python3-doc/html/library/stdtypes.html#set>, collections.abc.Sequence </usr/share/doc/python3-doc/html/library/collections.abc.html#collections.abc.Sequence>, collections.abc.Mapping </usr/share/doc/python3-doc/html/library/collections.abc.html#collections.abc.Mapping>) β€”

optional mapping of custom functions. see also below custom functions description

  • custom_import_extensions β€” (ignored, for backward compatibility) πŸ™ˆ
  • importers (collections.abc.Callable </usr/share/doc/python3-doc/html/library/collections.abc.html#collections.abc.Callable>) β€”

optional callback functions. see also below importer callbacks description

Returns

  • the compiled CSS string, or a pair of the compiled CSS string and the source map string if source_map_filename is set

Return type

  • str </usr/share/doc/python3-doc/html/library/stdtypes.html#str>, tuple </usr/share/doc/python3-doc/html/library/stdtypes.html#tuple>

Raises

  • sass.CompileError <#sass.CompileError> β€” when it fails for any reason (for example the given Sass has broken syntax) 😭
  • exceptions.IOError β€” when the filename doesn't exist or cannot be read

πŸ¦‹ the dirname mode

The dirname is useful for automation. πŸ€– It takes a pair of paths. The first of the dirname pair refers the source directory, contains several Sass source files to compiled. Sass source files can be nested in directories. The second of the pair refers the output directory that compiled CSS files would be saved. Directory tree structure of the source directory will be maintained in the output directory as well. If dirname parameter is used the function returns None.

Parameters

  • dirname (tuple </usr/share/doc/python3-doc/html/library/stdtypes.html#tuple>) β€” a pair of (source_dir, output_dir). it's exclusive to string and filename parameters
  • output_style (str </usr/share/doc/python3-doc/html/library/stdtypes.html#str>) β€” an optional coding style of the compiled result. choose one of: 'nested' (default), 'expanded', 'compact', 'compressed'
  • source_comments (bool </usr/share/doc/python3-doc/html/library/functions.html#bool>) β€” whether to add comments about source lines. False by default
  • source_map_contents (bool </usr/share/doc/python3-doc/html/library/functions.html#bool>) β€” embed include contents in map
  • source_map_embed (bool </usr/share/doc/python3-doc/html/library/functions.html#bool>) β€” embed sourceMappingUrl as data URI
  • omit_source_map_url (bool </usr/share/doc/python3-doc/html/library/functions.html#bool>) β€” omit source map URL comment from output
  • source_map_root (str </usr/share/doc/python3-doc/html/library/stdtypes.html#str>) β€” base path, will be emitted in source map as is
  • include_paths (collections.abc.Sequence </usr/share/doc/python3-doc/html/library/collections.abc.html#collections.abc.Sequence>) β€” an optional list of paths to find @imported Sass/CSS source files
  • precision (int) β€” optional precision for numbers. it's 5 by default. ✨
  • custom_functions (set, collections.abc.Sequence, collections.abc.Mapping) β€” an optional mapping of custom functions. see also the custom functions description further down, bestie πŸ‘€
  • custom_import_extensions β€” (ignored, kept around for backward compatibility) πŸ™ˆ
Raises sass.CompileError β€” when it fails for any reason (for example, the Sass you handed it has broken syntax). πŸ’€

The custom_functions parameter can take three types of forms:

set </usr/share/doc/python3-doc/html/library/stdtypes.html#set> / Sequence </usr/share/doc/python3-doc/html/library/collections.abc.html#collections.abc.Sequence> of SassFunctions β€” it's the most general form. lowkey verbose, but it can take any kind of callables like type objects, unnamed functions, and user-defined callables.

sass.compile(
    ...,
    custom_functions={
        sass.SassFunction('func-name', ('$a', '$b'), some_callable),
        ...
    }
)

Mapping </usr/share/doc/python3-doc/html/library/collections.abc.html#collections.abc.Mapping> of names to functions β€” less general, but it's the easier-to-use form. it's not that it can take any kind of callables β€” it can take any kind of functions defined using def </usr/share/doc/python3-doc/html/reference/compound_stmts.html#def> / lambda </usr/share/doc/python3-doc/html/reference/expressions.html#lambda> syntax. It cannot take callables other than those, because inspecting arguments is not always available for every kind of callable.

sass.compile(
    ...,
    custom_functions={
        'func-name': lambda a, b: ...,
        ...
    }
)

set </usr/share/doc/python3-doc/html/library/stdtypes.html#set> / Sequence </usr/share/doc/python3-doc/html/library/collections.abc.html#collections.abc.Sequence> of named functions β€” not general, but it's the easiest-to-use form for named functions. It can take only named functions, defined using def </usr/share/doc/python3-doc/html/reference/compound_stmts.html#def>. It cannot take lambdas since names are unavailable for them. 😭

def func_name(a, b):
    return ...

sass.compile(
    ...,
    custom_functions={func_name}
)

Newer versions of libsass let developers define callbacks that get called and get a chance to process @import directives. you define yours by passing in a list of callables via the importers parameter. the callables must be passed as 2-tuples in the form:

(priority_int, callback_fn)

A priority of zero is totally acceptable; priority determines the order the callbacks are attempted. πŸ”₯

These callbacks can accept one or two string arguments. The first argument is the path that was passed to the @import directive; the second (optional) argument is the previous resolved path, where the @import directive was found. The callbacks must either return None to indicate the path wasn't handled by that callback (so it continues with the others or falls back on internal libsass filesystem behaviour) or a list of one or more tuples, each in one of three forms:

  • A 1-tuple representing an alternate path to handle internally; or,
  • A 2-tuple representing an alternate path and the content that path represents; or,
  • A 3-tuple representing the same as the 2-tuple with the addition of a "sourcemap".

All tuple return values must be strings. as a not-overly-realistic example:

def my_importer(path, prev):
    return [(path, '#' + path + ' { color: red; }')]

sass.compile(
        ...,
        importers=[(0, my_importer)]
    )

Now, within the style source, attempting to @import 'button'; will instead attach color: red as a property of an element with the imported name. 🌈

  • Added in version 0.4.0: added source_comments and source_map_filename parameters.
  • Changed in version 0.6.0: the source_comments parameter becomes to take only bool </usr/share/doc/python3-doc/html/library/functions.html#bool> instead of str </usr/share/doc/python3-doc/html/library/stdtypes.html#str>.
  • Deprecated since version 0.6.0: values like 'none', 'line_numbers', and 'map' for the source_comments parameter are deprecated. πŸ’€
  • Added in version 0.7.0: added precision parameter.
  • Added in version 0.7.0: added custom_functions parameter.
  • Added in version 0.11.0: source_map_filename no longer implies source_comments.
  • Added in version 0.17.0: added source_map_contents, source_map_embed, omit_source_map_url, and source_map_root parameters.
  • Added in version 0.18.0: the importer callbacks can now take a second argument, the previously-resolved path, so that importers can do relative path resolution. ✨

This package provides several additional utilities related to Sass which depends on libsass core (the sass </usr/share/doc/python3-doc/html/library/#module-sass> module). 🫢


πŸ—οΈ sassutils.builder β€” Build the whole directory

class sassutils.builder.Manifest(sass_path, css_path=None, wsgi_path=None, strip_extension=None)

Building manifest of Sass/SCSS. πŸŽ€

Parameters

  • sass_path (str </usr/share/doc/python3-doc/html/library/stdtypes.html#str>, basestring) β€” the path of the directory that contains Sass/SCSS source files πŸ“‚
  • css_path (str </usr/share/doc/python3-doc/html/library/stdtypes.html#str>, basestring) β€” the path of the directory to store compiled CSS files
  • strip_extension (bool </usr/share/doc/python3-doc/html/library/functions.html#bool>) β€” whether to remove the original file extension βœ‚οΈ

build(package_dir, output_style='nested')

Builds the Sass/SCSS files in the specified sass_path. It finds sass_path and locates css_path as relative to the given package_dir.

Parameters

  • package_dir (str </usr/share/doc/python3-doc/html/library/stdtypes.html#str>, basestring) β€” the path of package directory
  • output_style (str </usr/share/doc/python3-doc/html/library/stdtypes.html#str>) β€” an optional coding style of the compiled result. choose one of: 'nested' (default), 'expanded', 'compact', 'compressed' πŸ’…

Returns the set of compiled CSS filenames

Return type frozenset </usr/share/doc/python3-doc/html/library/stdtypes.html#frozenset>

Added in version 0.6.0: the output_style parameter.

build_one(package_dir, filename, source_map=False)

Builds one Sass/SCSS file. πŸ¦‹

Parameters

  • package_dir (str </usr/share/doc/python3-doc/html/library/stdtypes.html#str>, basestring) β€” the path of package directory
  • filename (str </usr/share/doc/python3-doc/html/library/stdtypes.html#str>, basestring) β€” the filename of Sass/SCSS source to compile
  • source_map (bool </usr/share/doc/python3-doc/html/library/functions.html#bool>) β€” whether to use source maps. if True it also write a source map to a filename followed by .map suffix. default is False

Returns the filename of compiled CSS

Return type str </usr/share/doc/python3-doc/html/library/stdtypes.html#str>, basestring

Added in version 0.4.0: added optional source_map parameter.

resolve_filename(package_dir, filename)

Gets a proper full relative path of Sass source and CSS source that will be generated, according to package_dir and filename. πŸ—ΊοΈ

Parameters

  • package_dir (str </usr/share/doc/python3-doc/html/library/stdtypes.html#str>, basestring) β€” the path of package directory
  • filename (str </usr/share/doc/python3-doc/html/library/stdtypes.html#str>, basestring) β€” the filename of Sass/SCSS source to compile

Returns a pair of (sass, css) path

Return type tuple </usr/share/doc/python3-doc/html/library/stdtypes.html#tuple>


unresolve_filename(package_dir, filename)

Retrieves the probable source path from the output filename. Pass in a .css path to get out a .scss path. πŸ”„

Parameters

  • package_dir (str </usr/share/doc/python3-doc/html/library/stdtypes.html#str>) β€” the path of the package directory
  • filename (str </usr/share/doc/python3-doc/html/library/stdtypes.html#str>) β€” the css filename

Returns β€” the scss filename, bestie πŸ’–

Return type β€” str (the whole lore lives at /usr/share/doc/python3-doc/html/library/stdtypes.html#str)


  • sassutils.builder.SUFFIXES = frozenset({'sass', 'scss'}) β€” a frozenset (peep /usr/share/doc/python3-doc/html/library/stdtypes.html#frozenset for the deets) holding the set of supported filename suffixes. It's giving the approved guest list πŸŽ€
  • sassutils.builder.SUFFIX_PATTERN = re.compile('[.](sass|scss)$') β€” the re.RegexObject regular expression pattern that matches the filenames in SUFFIXES. Lowkey a vibe check for file extensions ✨
  • sassutils.builder.build_directory(sass_path, css_path, output_style='nested', _root_sass=None, _root_css=None, strip_extension=False) β€” compiles all Sass/SCSS files in a path to CSS. Main character behaviour, fr fr.
sassutils.builder.build_directory(sass_path, css_path, output_style='nested', _root_sass=None, _root_css=None, strip_extension=False)

Parameters

  • sass_path (str, basestring) β€” the path of the directory which contains source files to compile 🌸
  • css_path (str, basestring) β€” the path of the directory where the compiled CSS files will go πŸ’…
  • output_style (str) β€” an optional coding style for the compiled result. choose one of: 'nested' (default), 'expanded', 'compact', 'compressed' πŸ‘‘

Returns β€” a dictionary of source filenames to compiled CSS filenames πŸ¦‹

Return type β€” collections.abc.Mapping (/usr/share/doc/python3-doc/html/library/collections.abc.html#collections.abc.Mapping)

Added in version 0.6.0 β€” the output_style parameter entered the chat ✨

πŸ’« sassutils.distutils β€” setuptools/distutils integration πŸ’«

This module provides extensions (and some magical monkey-patches, sorry πŸ™ˆ) of the standard distutils (/usr/share/doc/python3-doc/html/library/distutils.html#module-distutils) and setuptools (now it's named Distribute) for libsass.

To use this, add libsass into setup_requires (not install_requires β€” do not play yourself bestie) option of the setup.py script:

from setuptools import setup

setup(
    # ...,
    setup_requires=['libsass >= 0.6.0']
)

It will adds build_sass command to the setup.py script:

$ python setup.py build_sass

This commands builds Sass/SCSS files to compiled CSS files of the project, and makes the package archive (made by sdist, bdist, and so on) include these compiled CSS files. Iconic packaging moment πŸ’–

To set the directory of Sass/SCSS source files and the directory to store compiled CSS files, specify sass_manifests option:

from setuptools import find_packages, setup

setup(
    name='YourPackage',
    packages=find_packages(),
    sass_manifests={
        'your.webapp': ('static/sass', 'static/css')
    },
    setup_requires=['libsass >= 0.6.0']
)

The option should be a mapping of package names to pairs of paths, e.g.:

{
    'package': ('static/sass', 'static/css'),
    'package.name': ('static/scss', 'static')
}

The option can also be a mapping of package names to manifest dictionaries:

{
    'package': {
        'sass_path': 'static/sass',
        'css_path': 'static/css',
        'strip_extension': True,
    },
}

Added in version 0.15.0 β€” added strip_extension so a.scss is compiled to a.css instead of a.scss.css. no cap, this slays. This option will default to True in the future πŸ‘€

Added in version 0.6.0 β€” added --output-style/-s option to build_sass command πŸŽ€

  • class sassutils.distutils.build_sass(dist: Distribution, **kw) β€” builds Sass/SCSS files to CSS files. The whole point, honestly πŸ’…
    • finalize_options() β€” set final values for all options/attributes used by the command. Most of the time, each option/attribute/cache should only be set if it does not have any value yet (e.g. if self.attr is None: self.attr = val). Respect the "only if it's empty" rule bestie ✨
    • get_package_dir(package) β€” returns the directory, relative to the top of the source distribution, where package package should be found (at least according to the package_dir option, if any). Copied from distutils.command.build_py.get_package_dir() method. Yes it's a re-gift, it's still cute 🎁
    • initialize_options() β€” set or (reset) all options/attributes/caches used by the command to their default values. Note that these values may be overwritten during the build. glow-up pending 🌸
    • run() β€” execute the actions intended by the command. (Side effects SHOULD only take place when run() is executed, for example, creating new files or writing to the terminal output). So like, actually doing the thing? iconic πŸ”₯
  • sassutils.distutils.validate_manifests(dist, attr, value) β€” verifies that value is an expected mapping of package to sassutils.builder.Manifest (#sassutils.builder.Manifest). It's the bouncer at the door 🫢

🌈 sassutils.wsgi β€” WSGI middleware for development purpose 🌈

  • class sassutils.wsgi.SassMiddleware(app, manifests, package_dir={}, error_status='200 OK') β€” WSGI middleware for development purpose. Every time a CSS file has requested it finds a matched Sass/SCSS source file and then compiled it into CSS. It's literally out here doing the most for you in dev 🌸
class sassutils.wsgi.SassMiddleware(app, manifests, package_dir={}, error_status='200 OK')

It shows syntax errors in three ways:

Heading comment β€” the result CSS includes the detailed error message in the heading CSS comment e.g.:

/*
Error: invalid property name
*/

Red text in body:before β€” the result CSS draws the detailed error message in the :before pseudo-class of the body element e.g.:

body:before {
    content: 'Error: invalid property name';
    color: maroon;
    background-color: white;
}

In most cases you could be aware of syntax error by refreshing your working document because it will removes all other styles and leaves only a red text. dramatic much? but helpful πŸ’€

logging (/usr/share/doc/python3-doc/html/library/logging.html#module-logging) β€” it logs syntax errors if exist during compilation to sassutils.wsgi.SassMiddleware logger with level ERROR.

To enable this:

from logging import Formatter, StreamHandler, getLogger
logger = getLogger('sassutils.wsgi.SassMiddleware')
handler = StreamHandler(level=logging.ERROR)
formatter = Formatter(fmt='*' * 80 + '\n%(message)s\n' + '*' * 80)
handler.setFormatter(formatter)
logger.addHandler(handler)

Or simply:

import logging
logging.basicConfig()
ngl the second one is the lazy-girl route and honestly? valid πŸ™ˆ

Parameters

  • app (collections.abc.Callable β€” /usr/share/doc/python3-doc/html/library/collections.abc.html#collections.abc.Callable) β€” the WSGI application to wrap πŸŽ€
  • manifests (collections.abc.Mapping β€” /usr/share/doc/python3-doc/html/library/collections.abc.html#collections.abc.Mapping) β€” build settings. the same format to setup.py script's sass_manifests option πŸ’–
  • package_dir (collections.abc.Mapping β€” /usr/share/doc/python3-doc/html/library/collections.abc.html#collections.abc.Mapping) β€” optional mapping of package names to directories. the same format to setup.py script's package_dir option ✨

Changed in version 0.4.0 β€” it creates also source map files with filenames followed by .map suffix πŸ—ΊοΈ

Added in version 0.8.0 β€” it logs syntax errors if exist during compilation to sassutils.wsgi.SassMiddleware logger with level ERROR πŸ”₯

  • static quote_css_string(s) β€” quotes a string as CSS string literal πŸ’…

πŸ‘‘ CREDIT πŸ‘‘

Hong Minhee wrote this Python binding of LibSass (https://github.com/sass/libsass).

Hampton Catlin and Aaron Leung wrote LibSass (https://github.com/sass/libsass), which is portable C/C++ implementation of Sass (https://sass-lang.com/).

Hampton Catlin originally designed Sass (https://sass-lang.com/) language and wrote the first reference implementation of it in Ruby.

The above three are all distributed under MIT license (https://mit-license.org/). periodt πŸ’–


πŸ¦‹ OPEN SOURCE πŸ¦‹


πŸ” INDICES AND TABLES πŸ”

  • Index <>
  • Module Index <>
  • Search Page <>

Author β€” Hong Minhee

Copyright β€” 2012, Hong Minhee


and that's a wrap on the whole page bestie, we ate and left no crumbs πŸ’…βœ¨ this lil manual is 0.23.0, dated Sep 18, 2026, and it answers to the name LIBSASS(3) πŸŽ€πŸ¦‹πŸ‘‘

πŸ“¦ where this page comes from