PythonKSS API

The core API

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

Bases: object

Parses one or more directories of style files.

Examples

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()
    print('*' * 70)
    print(section.reference, section.title)
    print('*' * 70)
    print()

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

    if section.description:
        print()
        print(section.description_html)

    if section.has_examples() or section.has_markups():
        print()
        print('Usage:')
        print('=' * 70)
        print()
        for example in section.examples:
            if example.title:
                print('-- ', example.title, ' --')
            print(example.html)
        for markup in section.markups:
            if markup.title:
                print('-- ', markup.title, ' --')
            print(markup.html)
Parameters:
  • *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:

    filename_patterns=[
        '*mytheme/*',
        '*external_theme/essentials/*',
        '*external_theme/advanced/menu.scss',
        '*external_theme/advanced/navbar.scss',
    ]
    

    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()[source]

Find files in paths which match valid extensions.

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

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

get_sections(referenceprefix=None)[source]

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
iter_sorted_sections(referenceprefix=None)[source]

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

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

Get sections organized in pythonkss.sectiontree.SectionTree.

Returns:The built tree.
Return type:pythonkss.sectiontree.SectionTree
get_section_by_reference(reference)[source]

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(**kwargs)[source]

Parse the section.

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

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

title

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

description

Get the description as plain text.

description_html

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

examples

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

has_examples()[source]

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

has_multiple_examples()[source]

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

reference

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>.

raw_reference

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_-]+.

raw_reference_segment_list

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.

reference_segment_list

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.

iter_reference_segments_expanded()[source]

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
sortkey

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.

Parameters:
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:).

text

The markup text (the lines below Example:)

filename

The filename. Can be None.

title

The title for the markup block. Can be None.

Parameters:
  • 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.
syntax

Get syntax identifier.

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

Format the text as HTML with syntax hilighting.

type

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

height

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.

reference

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

segment_text

The text after the last . in the reference.

section

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

root

The root of the tree. A SectionTree object.

level

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

children

A dict mapping segment_text to SectionTreeNode objects.

dotted_numbered_path

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".

title

Get the section title, falling back to segment_text capitalized.

sortkey

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().

sorted_children

Get children sorted by sortkey().

collect_descendants_sorted(result)[source]

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.
sorted_all_descendants_flat()[source]

Get a flat list of all descendants in sorted order.

Uses collect_descendants_sorted() to build the list.

prettyformat(indent_level=False)[source]

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_tree()[source]

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.

Note

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_node_by_reference(reference)[source]

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_html(html)[source]

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.

Parameters:
  • 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()[source]

Parse the file and collect comment blocks in a list.

Returns:Comment blocks list.
Return type:list
blocks

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

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