The core API

class pythonkss.parser.Parser(*paths, **kwargs)[source]

Bases: object

Parses one or more directories of style files.


Parse a directory and print a styleguide (nice getting started exmaple for generating your own styleguide):

parser = pythonkss.Parser('/path/to/my/styles/')
for section in parser.iter_sorted_sections():
    print('*' * 70)
    print(section.reference, section.title)
    print('*' * 70)

    for modifier in section.modifiers:
        print('-- ',, ' --')

    if section.description:

    if section.has_examples() or section.has_markups():
        print('=' * 70)
        for example in section.examples:
            if example.title:
                print('-- ', example.title, ' --')
        for markup in section.markups:
            if markup.title:
                print('-- ', markup.title, ' --')
  • *paths – One or more directories to search for style files.
  • extensions – List of file extensions to search for. Optional - defaults to ['.less', '.css', '.sass', '.scss'].
  • filename_patterns

    Optional list of fnmatch.fnmatchcase() patterns for files to include in the styleguide.

    If this is not provided, all files in the directories specified in *paths is included.

    If this is provided, it must be a list/iterable of fnmatch.fnmatchcase() patterns. All file-paths matching any of the patterns in the list is included. Example:


    The check agains filename_patterns is performed after the check for filename extensions (see extensions kwarg). So if a filename does not match the required extensions, putting it in filename_patterns does not help at all.

  • variables (dict) – Dict that maps variables to values. Variables can be used anywhere in the comments, and they are applied before any other parsing of the comments.
  • variablepattern

    The pattern used to insert variables. Defaults to {{% {variable} %}}, which means that you would insert a variable added as $my-variable via the variables parameter with something like this:

    /* My title
    The value of $my-variable is {% $my-variable %}.
    Styleguide 1.1

Find files in paths which match valid extensions.

Returns:An iterable yielding file paths.
Return type:iterator

A dict of sections with reference() as key and :meth:`~pythonkss.section.Section objects as value.


Get sections, optionally only sections with reference() starting with referenceprefix.

Parameters:referenceprefix – If this is provided, only sections with reference() starting with referenceprefix is included.
Returns:A list of sections.
Return type:list

Iterate sections sorted by pythonkss.section.Section.reference().

Parameters:referenceprefix – See get_sections().
Returns:Iterable of pythonkss.section.Section objects.
Return type:generator

Get sections organized in pythonkss.sectiontree.SectionTree.

Returns:The built tree.
Return type:pythonkss.sectiontree.SectionTree

Get a section by its pythonkss.section.Section.reference().

Raises:KeyError – If no section with the provided reference exists.
class pythonkss.section.Section(comment=None, filepath=None)[source]

Bases: object

A section in the documentation.


Parse the section.

Parameters:**kwargs – Forwarded to SectionParser.parse().

Get the title (the first line of the comment).


Get the title (the first line of the comment).


Get the description as plain text.


Get the description() converted to markdown using pythonkss.markdownformatter.MarkdownFormatter.


Get all Example: sections as a list of pythonkss.example.Example objects.


Returns True if the section has at least one Example: section.


Returns True if the section more than one Example: section.


Get the reference.

This is the part after Styleguide at the end of the comment. If the reference format is <number>:<text>, this is only the <text>.


Get the raw reference.

This is the part after Styleguide at the end of the comment.

How a reference is parsed:

  • Split the reference into segments by ".".

  • All the segments except the last refer to the parent.

  • The part after the last "." is in one of the following formats:
    • [a-z0-9_-]+
    • <number>:<[a-z0-9_-]+>
  • All segments except the last can only contain [a-z0-9_-]+.


Get raw_reference() as a list of segments.

Just a shortcut for raw_reference.split('.'), but slightly faster because the list is created when the section is parsed.


Get reference() as a list of segments.

Just a shortcut for reference.split('.'), but slightly faster because the list is created when the section is parsed.


Iterate over reference_segment_list(), and return the reference of each segment.

So if the reference() is a.b.c, this will yield:

  • a
  • a.b
  • a.b.c

Get the sortkey for this reference within the parent section.

Parses the last segment of the reference, and extracts a sort key. Extracted as follows:

  • If the segment is a number, return the number.
  • If the segment starts with <number>:, return the number.
  • Otherwise, return None.

See reference() for information about what we mean by “segment”.

Some examples (reference -> sortkey):

  • 1 -> 1
  • 4.3 -> 3
  • 4.5.2 -> 2
  • 4.myapp-lists -> None
  • 4.12:myapp-lists -> 12
add_example(text, **kwargs)[source]

Add a example block to the section.

class pythonkss.example.Example(text, filename=None, argumentstring=None)[source]

Bases: object

Represents a Example part in a pythonkss.section.Section (the part that starts with Example:).


The markup text (the lines below Example:)


The filename. Can be None.


The title for the markup block. Can be None.

  • text – The text in the lines below Example:.
  • filename – The filename that the markup belongs to. Optional.
  • argumentstring – An optional argumentstring in the following format: [(<arguments>)] [<title>], where (<arguments>) are arguments on formatted as key: value. The only argument supported by this class is syntax, but the subclasses for supported arguments.

Get syntax identifier.

Returns:Returns syntax if set, falling back to “html”.
Return type:str

Format the text as HTML with syntax hilighting.


Get the value of the type option, or "embedded" if it is not specified.


Get the value of the height option, or None if it is not specified.

class pythonkss.sectiontree.SectionTreeNode(segment_text=None, reference=None, level=-1, root=None)[source]

Bases: object

A node in the SectionTree.


The reference of the section. This is set even if we have no section.


The text after the last . in the reference.


A pythonkss.section.Section if any is available at this location in the tree. If not, this is None.


The root of the tree. A SectionTree object.


The level in the tree starting at 0 for the topmost nodes in the tree. The root (SectionTree object) is level -1.


A dict mapping segment_text to SectionTreeNode objects.


Get the dotted numbered path for this node in sorted order.

I.E.: If the node is sorted at the third child of the second sorted toplevel node, this will be "2.3".


Get the section title, falling back to segment_text capitalized.


Get the sort key for the node within its parent.

If this node has no section, or if the sortkey of the section is None, we return the segment_text prefixed with "9999". If the section has a sortkey, we will return that prefixed with zeroes.

Will always return a sortable string, so this is well suited for usage in the key function for sorted().


Get children sorted by sortkey().


Add all descendants in the provided result list in sorted order.

This runs recursively, and adds each direct child and all its descendants before adding the next child (and all its descendants).

Parameters:result – A list.

Get a flat list of all descendants in sorted order.

Uses collect_descendants_sorted() to build the list.


Pretty-format the node.

Parameters:indent_level – If this is True, the string includes level * 4 spaces of indentation.
Returns:Pretty formatted information about the node on a single line.
Return type:str

Prettyprint all the descendants of this node.

class pythonkss.sectiontree.SectionTree(sections)[source]

Bases: pythonkss.sectiontree.SectionTreeNode

Builds a tree of sections.

Includes virtual sections - I.E.: if we have the lists.numbered reference, but we do not have the lists reference, the lists reference will still be a node in the tree. It will just have Node.section set to None.


This extends SectionTreeNode. This means that the tree is just the root node with a different constructor and some extra functionality.

Parameters:sections – An iterable of pythonkss.section.Section. Must be sorted by pythonkss.section.Section.reference.

Get a TreeNode by its reference.

The node can be anywhere in the tree.

Parameters:reference – The Section reference.

Utilities used by the core API

class pythonkss.markdownformatter.MarkdownFormatter(markdowntext)[source]

Bases: object

Markdown formatter used for descriptions and examples.

classmethod to_html(markdowntext)[source]

Convert the provided markdowntext to HTML.

Parameters:markdowntext (str) – Markdown formatted text.
Returns:The resulting HTML.
Return type:str

Postprocess the HTML. Converts <h1>, <h2> and <h3> to <h3>, <h4> and <h5>.

class pythonkss.comment.CommentParser(filename, variablemap=None)[source]

Bases: object

The comment parser.

Takes a filename, and parses it into a list of comment blocks.

Used by pythonkss.parser.Parser.

  • filename – The path to a style file.
  • variablemap (dict) – Maps variable substitution strings to values. We replace all occurrences of each key with the value in all parsed comments.

Parse the file and collect comment blocks in a list.

Returns:Comment blocks list.
Return type:list

Property that returns a list of comment blocks in the file.

Parses the file using parse() the first time it is called.