### Example documentation source file Source: https://github.com/simplistix/sybil/blob/master/docs/quickstart.rst An example of a reStructuredText (RST) file demonstrating how code examples can be included and tested using Sybil. This file serves as a template for documentation that contains testable code snippets. ```rest This is an example documentation file. .. code-block:: python def hello_world(): print("Hello, world!") hello_world() This is a doctest example: .. doctest:: >>> 1 + 1 2 ``` -------------------------------- ### Set up Virtual Environment and Install Project Dependencies Source: https://github.com/simplistix/sybil/blob/master/docs/development.rst This snippet shows how to create a Python virtual environment, activate it, and install the project along with its test and documentation dependencies in editable mode. This is the recommended setup for development. ```bash python3 -m venv ~/virtualenvs/sybil source ~/virtualenvs/sybil/bin/activate pip install -U pip setuptools pip install -U -e .[test,docs] ``` -------------------------------- ### Configure pytest conftest.py for Sybil Source: https://github.com/simplistix/sybil/blob/master/docs/quickstart.rst Example configuration file for conftest.py that integrates Sybil with pytest. This setup enables Sybil to check Python code-block and doctest examples within the project's source code and Sphinx documentation. ```python # content of examples/quickstart/conftest.py pytest_plugins = "sybil" ``` -------------------------------- ### Build Sphinx Documentation Source: https://github.com/simplistix/sybil/blob/master/docs/development.rst This command sequence builds the HTML documentation for the project using Sphinx. It requires navigating to the 'docs' directory and then executing the 'make html' command. Ensure you have Sphinx installed via the setup instructions. ```bash cd docs make html ``` -------------------------------- ### Python REPL DocTest Example Source: https://github.com/simplistix/sybil/blob/master/tests/samples/myst-doctest-use-rest.md A standard Python REPL example demonstrating simple arithmetic operations. This serves as a basic DocTest case. ```python >>> x = 1+1 >>> x 2 ``` -------------------------------- ### Python REPL DocTest Example Source: https://github.com/simplistix/sybil/blob/master/tests/samples/myst-doctest.md Demonstrates a basic Python REPL session used for DocTesting. This example shows simple variable assignment and retrieval. ```python >>> x = 1+1 >>> x 2 ``` -------------------------------- ### Python Assertion Example Source: https://github.com/simplistix/sybil/blob/master/tests/functional/markdown/python.md A basic Python example demonstrating an assertion. This snippet is intended for simple verification of conditions. It requires no external libraries. ```python assert 1 + 1 == 2 ``` -------------------------------- ### Configure Sybil for Linting and Checking Examples Source: https://github.com/simplistix/sybil/blob/master/docs/patterns.rst This conftest.py configuration demonstrates how to use two instances of Sybil for comprehensive example validation: one for linting and another for checking correctness. This approach ensures that examples are not only functional but also adhere to linting standards. ```python from sybil import Sybil from sybil.parsers.rest import ( # noqa DocTestDirectiveParser, skip_directives, ) pytest_collect_file = Sybil( parsers=[ DocTestDirectiveParser(skip_directives=skip_directives) ], patterns=['docs/**/*.rst'], ).pytest_collect_file ``` -------------------------------- ### Python Example with Blank Lines in Invisible Block Source: https://github.com/simplistix/sybil/blob/master/tests/functional/markdown/python.md This Python example is presented within an invisible code block and includes blank lines before and after the code. It serves to show how whitespace is handled in these hidden blocks. ```python blank line above ^^ blank line below: ``` -------------------------------- ### Python Function Call Example Source: https://github.com/simplistix/sybil/blob/master/docs/examples/markdown/skip.md Demonstrates how to call a Python function named 'foo' with specified arguments. This is a pseudo-code example illustrating the usage pattern. ```python foo('baz', 'bob', ...) ``` -------------------------------- ### Future Python Release Pseudo-code Example Source: https://github.com/simplistix/sybil/blob/master/docs/examples/markdown/skip.md Illustrates pseudo-code intended for a future release (v5) of the framework. It shows how to instantiate a helper object and use its describe method. ```python >>> helper = Framework().make_helper() >>> helper.describe(...) ``` -------------------------------- ### Execute Bash Command Example Source: https://github.com/simplistix/sybil/blob/master/docs/rest.rst A simple bash command example that echoes 'hi there' and shows the expected output. This is typically used in conjunction with a parser that can execute and verify bash commands. ```bash $ echo hi there hi there ``` -------------------------------- ### Configure Sybil for MyST Docs and Python Source Examples Source: https://github.com/simplistix/sybil/blob/master/docs/patterns.rst This Python configuration for conftest.py sets up Sybil to process examples from MyST (Markdown) documentation and Python source files. It's designed for projects using MyST for their documentation, ensuring code examples are validated. ```python from sybil import Sybil from sybil.parsers.rest import CommentedMapParser pytest_collect_file = Sybil( parsers=[ CommentedMapParser(), ], patterns=['docs/**/*.md'], ).pytest_collect_file ``` -------------------------------- ### Configure Python Doctest Parser in Markdown Source: https://github.com/simplistix/sybil/blob/master/docs/markdown.rst Configures Sybil to use the PythonCodeBlockParser for doctest examples within Python fenced code blocks in Markdown files. This setup enables the checking of doctest examples. ```python from sybil import Sybil from sybil.parsers.markdown import PythonCodeBlockParser sybil = Sybil(parsers=[PythonCodeBlockParser()]) ``` -------------------------------- ### Configure Sybil for Restructured Text Docs and Python Source Examples Source: https://github.com/simplistix/sybil/blob/master/docs/patterns.rst This Python configuration for conftest.py ensures that examples embedded within Restructured Text documentation and Python source files are correctly parsed and validated by Sybil. It assumes a standard project structure with 'docs' and 'src' directories. ```python from sybil import Sybil from sybil.parsers.rest import CommentedMapParser pytest_collect_file = Sybil( parsers=[ CommentedMapParser(), ], patterns=['docs/**/*.rst'], ).pytest_collect_file ``` -------------------------------- ### Configure PythonCodeBlockParser in Python Source: https://github.com/simplistix/sybil/blob/master/docs/rest.rst This Python configuration demonstrates the setup for the PythonCodeBlockParser, designed to check examples within Sphinx's Python code-block directives in RST files. It requires importing Sybil and the PythonCodeBlockParser. ```python from sybil import Sybil from sybil.parsers.rest import PythonCodeBlockParser sybil = Sybil(parsers=[PythonCodeBlockParser()]) ``` -------------------------------- ### Install Sybil with Pytest Extra Source: https://github.com/simplistix/sybil/blob/master/docs/integration.rst Install Sybil with the 'pytest' extra to ensure a compatible version of pytest is available. This command-line instruction is used to set up the necessary dependencies for pytest integration. ```bash pip install sybil[pytest] ``` -------------------------------- ### Python Exception Handling Example Source: https://github.com/simplistix/sybil/blob/master/tests/functional/markdown/python.md A Python code snippet demonstrating how to raise an exception. This is useful for illustrating error handling scenarios or testing exception catching mechanisms. It does not require any specific input. ```python raise Exception('boom!') ``` -------------------------------- ### Evaluation Classes and Data Source: https://github.com/simplistix/sybil/blob/master/docs/api.rst Documentation for evaluation-related components, including examples, exceptions, and specific evaluators. ```APIDOC ## sybil.Example ### Description Represents an example in evaluation. ### Module Member sybil.Example ### Members - __init__ - ... (other members) ``` ```APIDOC ## sybil.example.NotEvaluated ### Description Exception raised when an example is not evaluated. ### Class sybil.example.NotEvaluated ### Members - __init__ ``` ```APIDOC ## sybil.typing.Evaluator ### Description Type alias for Evaluator. ### Data sybil.typing.Evaluator ``` ```APIDOC ## sybil.evaluators.doctest.NUMBER ### Description Represents a number in doctest evaluation. ### Data sybil.evaluators.doctest.NUMBER ### Annotation ... ``` ```APIDOC ## sybil.evaluators.doctest.DocTestEvaluator ### Description Evaluator for doctests. ### Class sybil.evaluators.doctest.DocTestEvaluator ### Members - __init__ - ... (other members) ``` ```APIDOC ## sybil.evaluators.python.PythonEvaluator ### Description Evaluator for Python code. ### Class sybil.evaluators.python.PythonEvaluator ### Members - __init__ - ... (other members) ``` -------------------------------- ### Configure Sybil with Markdown and Skip Parsers in Python Source: https://github.com/simplistix/sybil/blob/master/docs/markdown.rst This Python code configures Sybil to use both Markdown code block parsing and a SkipParser. The SkipParser allows selective skipping of examples based on conditions within the markdown file. This setup is useful for managing test cases that are not yet ready or require specific conditions. ```python from sybil import Sybil from sybil.parsers.markdown import PythonCodeBlockParser, SkipParser sybil = Sybil(parsers=[PythonCodeBlockParser(), SkipParser()]) ``` -------------------------------- ### Future Python Release Helper Function Pseudo-code Source: https://github.com/simplistix/sybil/blob/master/docs/examples/rest/skip.rst This is a pseudo-code example illustrating the intended usage of a helper function in a future release (v5) of the framework. It shows instantiation of a framework and obtaining a helper object for further operations. This code is not functional in the current version. ```pseudo-code helper = Framework().make_helper() helper.describe(...) ``` -------------------------------- ### Python DocTest with Sphinx doctest role and Exception Source: https://github.com/simplistix/sybil/blob/master/tests/samples/myst-doctest-use-rest.md An example utilizing the Sphinx `doctest` role to showcase a Python DocTest that includes raising and catching an exception. The traceback is shown as expected. ```python >>> y = 2 >>> raise Exception('uh oh') Traceback (most recent call last): ... Exception: uh oh ``` -------------------------------- ### Disable pytest doctest plugin Source: https://github.com/simplistix/sybil/blob/master/docs/quickstart.rst Configuration to disable pytest's built-in doctest plugin. This prevents conflicts when Sybil is used for testing doctest examples, ensuring Sybil's doctest functionality is prioritized. ```ini [pytest] doctest_plugins = disable ``` -------------------------------- ### MyST code-block Python DocTest Example Source: https://github.com/simplistix/sybil/blob/master/tests/samples/myst-doctest.md Illustrates using the MyST `code-block` directive to specify Python code for DocTesting. This allows for cleaner integration of code examples within documentation. ```python >>> x += 1; x 3 ``` -------------------------------- ### Sphinx doctest Directive with Exception Example Source: https://github.com/simplistix/sybil/blob/master/tests/samples/myst-doctest.md Provides an example of using the Sphinx `doctest` directive to demonstrate a Python code snippet that intentionally raises an exception. This tests the handling of tracebacks in documentation. ```python >>> y = 2 >>> raise Exception('uh oh') Traceback (most recent call last): ...\nException: uh oh ``` -------------------------------- ### Sphinx eval-rst doctest Directive Example Source: https://github.com/simplistix/sybil/blob/master/tests/samples/myst-doctest.md Shows how to embed a DocTest example using Sphinx's `eval-rst` directive combined with the `doctest::` directive. This method is useful for integrating doctest directly into reStructuredText. ```python >>> 1 + 1 3 ``` -------------------------------- ### Python Code Block Example Source: https://github.com/simplistix/sybil/blob/master/tests/samples/myst-lexers.md A basic Python code block demonstrating simple arithmetic. This is a standard fenced code block. ```python >>> 1+1 2 ``` -------------------------------- ### Python Invisible Code Block Example 1 Source: https://github.com/simplistix/sybil/blob/master/tests/functional/myst/python.md An example of an invisible Python code block using a '%' prefix. This type of block is typically not rendered in the final output but can be processed by specific tools or extensions. ```python # ...etc... ``` -------------------------------- ### Python Function and Assertion with Invisible Block Source: https://github.com/simplistix/sybil/blob/master/tests/functional/markdown/python.md An example using an invisible Python code block. It defines a function 'foo' and asserts its return value against a constant. This method is useful for hiding code that might clutter the main documentation flow. ```python def foo(): return 42 meaning_of_life = 42 assert foo() == meaning_of_life ``` -------------------------------- ### Sphinx doctest Directive Mismatch Example Source: https://github.com/simplistix/sybil/blob/master/tests/samples/myst-doctest.md Demonstrates a DocTest example using the Sphinx `doctest` directive where a normal pass is followed by an expected mismatch. This highlights how DocTest can catch inconsistencies. ```python >>> y == 2 True >>> y 3 ``` -------------------------------- ### MyST Directive Example Source: https://github.com/simplistix/sybil/blob/master/tests/samples/myst-lexers.md A MyST directive with arguments and YAML front matter. This demonstrates a custom directive named 'directivename'. ```myst ```{directivename} arguments --- key1: val1 key2: val2 --- This is directive content ``` ``` -------------------------------- ### Python Code Block Example Source: https://github.com/simplistix/sybil/blob/master/tests/samples/lexing-directives.txt Demonstrates a simple Python code block using the 'code-block' directive. This is useful for embedding and formatting code snippets within documentation. It relies on the reStructuredText parser to render correctly. ```rst .. code-block:: python run.append(1) ``` -------------------------------- ### Python DocTest with MyST Role Source: https://github.com/simplistix/sybil/blob/master/tests/samples/myst-doctest-use-rest.md An example of a Python DocTest using the MyST `code-block` directive for syntax highlighting and execution. It shows incrementing a variable. ```python >>> x += 1; x 3 ``` -------------------------------- ### Configure Sybil for Skipping Examples Source: https://github.com/simplistix/sybil/blob/master/docs/myst.rst This configuration demonstrates setting up Sybil with SkipParser to selectively skip examples in Markdown files. It includes both unconditional skips and conditional skips based on namespace variables. ```python from sybil import Sybil from sybil.parsers.myst import PythonCodeBlockParser, SkipParser sybil = Sybil(parsers=[PythonCodeBlockParser(), SkipParser()]) ``` -------------------------------- ### Python Doctest Examples with MyST Doctest Directives Source: https://github.com/simplistix/sybil/blob/master/docs/myst.rst Configures Sybil to specifically parse Python doctest examples embedded within MyST's 'doctest' directives. This is useful when examples are explicitly marked using the '.. doctest::' syntax. ```python from sybil import Sybil from sybil.parsers.myst import DocTestDirectiveParser sybil = Sybil(parsers=[DocTestDirectiveParser()]) ``` -------------------------------- ### Python Doctest Examples with MyST Code Blocks Source: https://github.com/simplistix/sybil/blob/master/docs/myst.rst Configures Sybil to parse Python doctest examples found in MyST fenced code blocks. This parser is suitable for standard Python code blocks that contain doctest-formatted examples. ```python from sybil import Sybil from sybil.parsers.myst import PythonCodeBlockParser sybil = Sybil(parsers=[PythonCodeBlockParser()]) ``` -------------------------------- ### Python 3 Specific Functionality Source: https://github.com/simplistix/sybil/blob/master/docs/examples/markdown/skip.md Shows an example that is only compatible with Python 3 or later. It demonstrates the representation of bytes literals in Python 3. ```python >>> repr(b'foo') "b'foo'" ``` -------------------------------- ### Implement and Use NamedValue Protocol in Python Source: https://github.com/simplistix/sybil/blob/master/tests/samples/protocol-typing.rst Provides a Python class 'NamedValueClass1' that implements the 'NamedValue' protocol by having 'name' and 'value' attributes. It includes an example of instantiating this class and verifying its compatibility with the 'NamedValue' protocol using 'isinstance'. ```python class NamedValueClass1: def __init__(self, name: str, value: float): self.name = name self.value = value v = NamedValueClass1("foo", 1.0) >>> isinstance(v, NamedValue) True ``` -------------------------------- ### ReST Note Admonition Example Source: https://github.com/simplistix/sybil/blob/master/tests/samples/lexing-nested-directives.txt Demonstrates the basic syntax for a reStructuredText note admonition, including multi-line text and nested admonitions. This directive is useful for highlighting important information. ```rst .. note:: This is a note admonition. This is the second line of the first paragraph. .. admonition:: And, by the way... You can make up your own admonition too. ``` -------------------------------- ### Configure DocTestParser in Python Source: https://github.com/simplistix/sybil/blob/master/docs/rest.rst This configuration demonstrates how to instantiate and use the DocTestParser for processing classic doctest examples within a Restructured Text document. It requires importing Sybil and the DocTestParser. ```python from sybil import Sybil from sybil.parsers.rest import DocTestParser sybil = Sybil(parsers=[DocTestParser()]) ``` -------------------------------- ### Python DocTest with Sphinx eval-rst and doctest roles Source: https://github.com/simplistix/sybil/blob/master/tests/samples/myst-doctest-use-rest.md Demonstrates using Sphinx's `eval-rst` role combined with the `doctest::` directive for executing doctests within reStructuredText. This example intentionally shows an incorrect result. ```python >>> 1 + 1 3 ``` -------------------------------- ### Configure Python Doctest Parser with NUMBER flag Source: https://github.com/simplistix/sybil/blob/master/docs/markdown.rst Configures Sybil to use the PythonCodeBlockParser with the NUMBER option flag for doctest examples in Markdown. This is useful for handling floating-point numbers in examples without precision errors. ```python from sybil import Sybil from sybil.evaluators.doctest import NUMBER from sybil.parsers.markdown import PythonCodeBlockParser sybil = Sybil(parsers=[PythonCodeBlockParser(doctest_optionflags=NUMBER)]) ``` -------------------------------- ### Python: Initialize and Append to List (Invisible) Source: https://github.com/simplistix/sybil/blob/master/tests/functional/skips/skip.rst Initializes an empty list and appends elements, but the code itself is marked as 'invisible', meaning it's present but not executed directly in the output context. This is useful for setup or internal logic. ```python run = [] ``` -------------------------------- ### Configure DocTestDirectiveParser in Python Source: https://github.com/simplistix/sybil/blob/master/docs/rest.rst This Python configuration shows how to use the DocTestDirectiveParser, which specifically targets examples within doctest directives in RST files, ignoring other doctest examples. It involves importing Sybil and the DocTestDirectiveParser. ```python from sybil import Sybil from sybil.parsers.rest import DocTestDirectiveParser sybil = Sybil(parsers=[DocTestDirectiveParser()]) ``` -------------------------------- ### Initialize Variable in Python (Invisible) Source: https://github.com/simplistix/sybil/blob/master/tests/samples/codeblock.txt An invisible Python code block, likely used for setup or internal checks within documentation. It demonstrates initializing a variable 'z'. ```python z += 1 ``` -------------------------------- ### ReST Doctest Examples within MyST Eval-RST Directives Source: https://github.com/simplistix/sybil/blob/master/docs/myst.rst Configures Sybil to parse standard ReST doctest examples when they are embedded within MyST's 'eval-rst' directives. This allows for the validation of traditional ReST doctests in a MyST context. ```python from sybil import Sybil from sybil.parsers.rest import DocTestDirectiveParser as ReSTDocTestDirectiveParser sybil = Sybil(parsers=[ReSTDocTestDirectiveParser()]) ``` -------------------------------- ### Implement Bash Block Parser from Scratch Source: https://github.com/simplistix/sybil/blob/master/docs/parsers.rst This Python code demonstrates how to implement a Sybil parser from scratch to handle bash code blocks. It defines regular expressions to identify the start and end of bash code blocks and includes an evaluator function for comparing command output. The parsed version is a tuple of the command to execute and the expected output. ```python from subprocess import check_output import re, textwrap from sybil import Sybil, Region from sybil.parsers.abstract.lexers import BlockLexer BASHBLOCK_START = re.compile(r'^\.\.\s*code-block::\s*bash') BASHBLOCK_END = r'(\n\Z|\n(?=\S))' def evaluate_bash_block(example): command, expected = example.parsed ``` -------------------------------- ### Invisible Python Code Block Source: https://github.com/simplistix/sybil/blob/master/tests/samples/myst-lexers.md An example of an 'invisible' Python code block using a comment-based directive. These blocks are not rendered directly but can be processed by tools. ```python % invisible-code-block: python % b = 5 % % ...etc... ``` -------------------------------- ### Configure Sybil with DocTestParser and ClearNamespaceParser (Python) Source: https://github.com/simplistix/sybil/blob/master/docs/rest.rst This configuration initializes Sybil with DocTestParser and ClearNamespaceParser. ClearNamespaceParser is used to isolate the testing of examples within a single source file by clearing the document's namespace. It requires the 'sybil' library and specific parsers. ```python from sybil import Sybil from sybil.parsers.rest import DocTestParser, ClearNamespaceParser sybil = Sybil(parsers=[DocTestParser(), ClearNamespaceParser()]) ``` -------------------------------- ### Create Custom BashCodeBlockParser Source: https://github.com/simplistix/sybil/blob/master/docs/myst.rst This example shows how to create a custom parser class, BashCodeBlockParser, by subclassing CodeBlockParser. This allows for tailored evaluation of bash code blocks directly within Sybil. ```python from subprocess import check_output from textwrap import dedent from sybil import Sybil from sybil.parsers.myst import CodeBlockParser class BashCodeBlockParser(CodeBlockParser): language = 'bash' def evaluate(self, example): command, expected = dedent(example.parsed).strip().split('\n') actual = check_output(command[2:].split()).strip().decode('ascii') assert actual == expected, repr(actual) + ' != ' + repr(expected) sybil = Sybil([BashCodeBlockParser()]) ``` -------------------------------- ### Variable Definition in Python Source: https://github.com/simplistix/sybil/blob/master/tests/samples/codeblock.txt A straightforward Python code snippet that defines a variable named 'define_this' and assigns it the integer value 1. This is a basic variable assignment example. ```python define_this = 1 ``` -------------------------------- ### Initialize Sybil with Bash Code Block Parser in Python Source: https://github.com/simplistix/sybil/blob/master/docs/markdown.rst This Python code initializes Sybil with a BashCodeBlockParser. This configuration is used to parse and test code examples written in Bash within markdown files. It's a foundational step for setting up Sybil to handle Bash scripts. ```python sybil = Sybil([BashCodeBlockParser()]) ``` -------------------------------- ### RST Figure with Reference Source: https://github.com/simplistix/sybil/blob/master/tests/samples/myst-lexing-directives.md An example of embedding an RST figure with specified dimensions and a name for referencing. It also shows how to create internal and external references within the RST content. ```rst .. figure:: img/fun-fish.png :width: 100px :name: rst-fun-fish Party time! A reference from inside: :ref:`rst-fun-fish` A reference from outside: :ref:`syntax/directives/parsing` ``` -------------------------------- ### Initialize Sybil with Parsers (Python) Source: https://github.com/simplistix/sybil/blob/master/docs/myst.rst Initializes the Sybil object with a list of parsers, including PythonCodeBlockParser and ClearNamespaceParser. This setup is crucial for Sybil's functionality in processing different types of content. ```python sybil = Sybil(parsers=[PythonCodeBlockParser(), ClearNamespaceParser()]) ``` -------------------------------- ### Render PyPI Description to HTML Source: https://github.com/simplistix/sybil/blob/master/docs/development.rst This command renders the long description intended for PyPI into an HTML file for preview. It uses `setup.py --long-description` and pipes the output to `rst2html.py`. The resulting `desc.html` should be checked in a browser. ```bash python setup.py --long-description | rst2html.py > desc.html ``` -------------------------------- ### Configure Sybil with Python and Clear Namespace Parsers in Python Source: https://github.com/simplistix/sybil/blob/master/docs/markdown.rst This Python code demonstrates configuring Sybil with a Python code block parser and a ClearNamespaceParser. The ClearNamespaceParser is used to isolate the testing of examples within a single source file by clearing the document's namespace before each test. This ensures that tests do not interfere with each other. ```python from sybil import Sybil from sybil.parsers.markdown import PythonCodeBlockParser, ClearNamespaceParser sybil = Sybil(parsers=[PythonCodeBlockParser(), ClearNamespaceParser()]) ``` -------------------------------- ### ReST Image Directive Examples Source: https://github.com/simplistix/sybil/blob/master/tests/samples/lexing-nested-directives.txt Illustrates the use of the reStructuredText image directive for embedding images. Shows both a simple image inclusion and an image with various attributes like height, width, scale, alt text, and alignment. The directive requires the image file path as an argument. ```rst .. image:: picture.png .. image:: picture.jpeg :height: 100px :width: 200 px :scale: 50 % :alt: alternate text :align: right ``` -------------------------------- ### Python Class with Slots (With Variables) Source: https://github.com/simplistix/sybil/blob/master/tests/samples/codeblock.txt This Python code defines a class 'YesVars' utilizing `__slots__` for memory efficiency. It declares an instance variable 'x', similar to the 'NoVars' example but implying variable usage. ```python class YesVars: __slots__ = ['x'] ``` -------------------------------- ### Python Class with Slots (No Variables) Source: https://github.com/simplistix/sybil/blob/master/tests/samples/codeblock.txt A Python class definition using `__slots__` to optimize memory by pre-declaring instance variables. This example defines a class 'NoVars' with a slot 'x'. ```python class NoVars: __slots__ = ['x'] ``` -------------------------------- ### HTML Comment Invisible Python Code Block Source: https://github.com/simplistix/sybil/blob/master/tests/samples/myst-lexers.md An example of an 'invisible' Python code block enclosed within an HTML comment. This method is useful for hiding code from rendering. ```python ``` -------------------------------- ### Configure Sybil with DocTestParser and SkipParser (Python) Source: https://github.com/simplistix/sybil/blob/master/docs/rest.rst This configuration sets up Sybil to use both DocTestParser and SkipParser. SkipParser allows specific examples to be ignored based on provided reasons, useful for managing incomplete or temporarily non-functional tests. It requires the 'sybil' library and specific parsers from 'sybil.parsers.rest'. ```python from sybil import Sybil from sybil.parsers.rest import DocTestParser, SkipParser sybil = Sybil(parsers=[DocTestParser(), SkipParser()]) ``` -------------------------------- ### Python: Append to List (Skipped) Source: https://github.com/simplistix/sybil/blob/master/tests/functional/skips/skip.rst Appends an element to a list. This code block is within a 'skip: start' and 'skip: end' directive pair and is therefore excluded. ```python run.append(3) ``` -------------------------------- ### Configure DocTestParser with NUMBER option flag Source: https://github.com/simplistix/sybil/blob/master/docs/rest.rst This Python configuration illustrates setting up the DocTestParser with the NUMBER option flag. This is useful for handling floating-point numbers in doctest examples, mitigating precision errors during evaluation. It requires importing Sybil, DocTestParser, and the NUMBER option flag. ```python from sybil import Sybil from sybil.parsers.rest import DocTestParser from sybil.evaluators.doctest import NUMBER sybil = Sybil(parsers=[DocTestParser(optionflags=NUMBER)]) ``` -------------------------------- ### Python: Append to List (Skipped) Source: https://github.com/simplistix/sybil/blob/master/tests/functional/skips/skip.rst Appends an element to a list. This code block is also within a 'skip: start' and 'skip: end' directive pair and is therefore excluded. ```python run.append(4) ``` -------------------------------- ### Render README to HTML Source: https://github.com/simplistix/sybil/blob/master/docs/development.rst This command renders the `README.rst` file into an HTML file for preview, simulating how it might appear on platforms like GitHub. It reads the README content and pipes it to `rst2html.py`. The resulting `readme.html` should be checked in a browser. ```bash cat README.rst | rst2html.py > readme.html ``` -------------------------------- ### ReST Topic Directive Example Source: https://github.com/simplistix/sybil/blob/master/tests/samples/lexing-nested-directives.txt Demonstrates the reStructuredText topic directive, which allows for creating distinct sections with a title and an indented body. The body content is interpreted as standard body elements, useful for grouping related information. ```rst .. topic:: Topic Title Subsequent indented lines comprise the body of the topic, and are interpreted as body elements. ``` -------------------------------- ### Configure Sybil for Clearing Namespace Source: https://github.com/simplistix/sybil/blob/master/docs/myst.rst This snippet illustrates how to configure Sybil with ClearNamespaceParser to isolate example testing within a single source file by clearing the document's namespace before each test. This prevents state leakage between tests. ```python from sybil import Sybil from sybil.parsers.myst import PythonCodeBlockParser, ClearNamespaceParser ``` -------------------------------- ### Capture Code Blocks with CaptureParser in Python Source: https://github.com/simplistix/sybil/blob/master/docs/rest.rst This snippet demonstrates using CaptureParser to capture the raw content of a code block and store it in the Sybil Document's namespace. This is useful for referencing code content in subsequent examples. It requires the Sybil library. ```python from sybil import Sybil from sybil.parsers.rest import CaptureParser sybil = Sybil(parsers=[CaptureParser()]) ``` -------------------------------- ### Hello World in Lolcode Source: https://github.com/simplistix/sybil/blob/master/tests/samples/codeblock.txt A 'Hello World' program written in the Lolcode programming language. It demonstrates basic output and program structure in Lolcode. ```lolcode HAI CAN HAS STDIO? VISIBLE "HAI WORLD!" KTHXBYE ``` -------------------------------- ### Check File Path with Sybil (Python) Source: https://github.com/simplistix/sybil/blob/master/docs/myst.rst Uses the check_path helper function to verify the expected outcome when Sybil processes a specific file. This is useful for testing Sybil's parsing and analysis capabilities on example files. ```python from tests.helpers import check_path check_path('examples/myst/clear.md', sybil, expected=4) ``` -------------------------------- ### Python Doctest with Floating Point Tolerance (MyST Code Blocks) Source: https://github.com/simplistix/sybil/blob/master/docs/myst.rst Configures Sybil to parse Python doctest examples in MyST code blocks, with special handling for floating-point numbers to ignore precision errors. Uses the NUMBER option flag for robust comparison. ```python from sybil import Sybil from sybil.evaluators.doctest import NUMBER from sybil.parsers.myst import PythonCodeBlockParser sybil = Sybil(parsers=[PythonCodeBlockParser(doctest_optionflags=NUMBER)]) ``` -------------------------------- ### Create Custom BashCodeBlockParser in Python Source: https://github.com/simplistix/sybil/blob/master/docs/rest.rst This snippet shows how to create a custom parser by subclassing CodeBlockParser. The BashCodeBlockParser overrides the evaluate method to provide specific logic for handling bash code examples, including command execution and output verification. ```python from subprocess import check_output from textwrap import dedent from sybil import Sybil from sybil.parsers.codeblock import CodeBlockParser class BashCodeBlockParser(CodeBlockParser): language = 'bash' def evaluate(self, example): command, expected = dedent(example.parsed).strip().split('\n') actual = check_output(command[2:].split()).strip().decode('ascii') assert actual == expected, repr(actual) + ' != ' + repr(expected) sybil = Sybil([BashCodeBlockParser()]) ``` -------------------------------- ### Evaluate Bash Commands from ReST Code Blocks Source: https://github.com/simplistix/sybil/blob/master/docs/parsers.rst This Python code defines an evaluator function to process bash commands found within ReStructured Text code blocks. It uses `subprocess.check_output` to execute the command and asserts that the actual output matches the expected output. This snippet assumes the parsed example is a tuple containing the command and expected output. ```python from subprocess import check_output from typing import Iterable from sybil import Sybil, Document, Region, Example from sybil.parsers.rest.lexers import DirectiveLexer from subprocess import check_output def evaluate_bash_block(example: Example): command, expected = example.parsed actual = check_output(command).strip().decode('ascii') assert actual == expected, repr(actual) + ' != ' + repr(expected) def parse_bash_blocks(document: Document) -> Iterable[Region]: lexer = DirectiveLexer(directive='code-block', arguments='bash') for lexed in lexer(document): command, output = lexed.lexemes['source'].strip().split('\n') assert command.startswith('$ ') parsed = command[2:].split(), output yield Region(lexed.start, lexed.end, parsed, evaluate_bash_block) sybil = Sybil(parsers=[parse_bash_blocks], pattern='*.rst') ``` -------------------------------- ### Define and Use a Function in Python Source: https://github.com/simplistix/sybil/blob/master/docs/examples/quickstart/example.rst This Python code defines a function `prefix_and_print` that takes a byte string message, decodes it to ASCII, and prints it with a 'prefix:'. It shows basic function definition and string manipulation. ```python import sys def prefix_and_print(message): print('prefix:', message.decode('ascii')) ``` -------------------------------- ### Check File Path with HTML Comments (Python) Source: https://github.com/simplistix/sybil/blob/master/docs/myst.rst Demonstrates checking a file that includes HTML-style comments using Sybil. This example, utilizing the literalinclude directive, verifies Sybil's ability to handle reStructuredText with embedded HTML comments. ```python from tests.helpers import check_path check_path('examples/myst/clear-html-comment.md', sybil, expected=4) ``` -------------------------------- ### ReST Figure Directive Example Source: https://github.com/simplistix/sybil/blob/master/tests/samples/lexing-nested-directives.txt Shows how to use the reStructuredText figure directive to include an image with a caption. The directive supports attributes like scale and alt text, and the subsequent indented text serves as the figure's caption. This is useful for providing context to images. ```rst .. figure:: picture.png :scale: 50 % :alt: map to buried treasure This is the caption of the figure (a simple paragraph). ``` -------------------------------- ### Run Project Tests Source: https://github.com/simplistix/sybil/blob/master/docs/development.rst After setting up the development environment and activating the virtualenv, this command executes the project's test suite using pytest. Ensure you are in the activated virtual environment before running. ```bash pytest ``` -------------------------------- ### Python: Sybil Instantiation with Encoding Source: https://github.com/simplistix/sybil/blob/master/CHANGELOG.rst This code demonstrates how to instantiate the `Sybil` class and override the default UTF-8 encoding for documentation source files. This is useful when dealing with files in different encodings. ```python from sybil import Sybil # Default encoding is UTF-8 sybil_default = Sybil() # Override encoding for specific files sybil_latin1 = Sybil(encoding='latin-1') # Specify multiple patterns to include and exclude sybil_filtered = Sybil(patterns=['*.py'], exclude=['test_*.py']) ``` -------------------------------- ### Region and Lexeme Classes Source: https://github.com/simplistix/sybil/blob/master/docs/api.rst Documentation for Region and Lexeme classes, detailing their members and inheritance. ```APIDOC ## sybil.Region ### Description Represents a region within a document, with accessible members. ### Class sybil.Region ### Members - __init__ - ... (other members) ``` ```APIDOC ## sybil.Lexeme ### Description Represents a lexeme, with accessible members and inheritance information. ### Class sybil.Lexeme ### Members - __init__ - ... (other members) ### Inheritance - ... (inherited members) ``` -------------------------------- ### Lexing Data and Exceptions Source: https://github.com/simplistix/sybil/blob/master/docs/api.rst Documentation for lexer types and lexing-related exceptions. ```APIDOC ## sybil.typing.Lexer ### Description Type alias for Lexer. ### Data sybil.typing.Lexer ``` ```APIDOC ## sybil.typing.LexemeMapping ### Description Type alias for LexemeMapping. ### Data sybil.typing.LexemeMapping ``` ```APIDOC ## sybil.parsers.abstract.lexers.BlockLexer ### Description Abstract base class for block lexers. ### Class sybil.parsers.abstract.lexers.BlockLexer ### Members - __init__ - ... (other members) ``` ```APIDOC ## sybil.parsers.abstract.lexers.LexingException ### Description Exception raised during lexing. ### Class sybil.parsers.abstract.lexers.LexingException ### Members - __init__ ``` -------------------------------- ### ReST Parsing and Lexing Classes Source: https://github.com/simplistix/sybil/blob/master/docs/api.rst Documentation for ReST-specific lexers and parsers. ```APIDOC ## sybil.parsers.rest.lexers.DirectiveLexer ### Description Lexer for ReST directives. ### Class sybil.parsers.rest.lexers.DirectiveLexer ### Members - __init__ - ... (other members) ``` ```APIDOC ## sybil.parsers.rest.lexers.DirectiveInCommentLexer ### Description Lexer for directives within ReST comments. ### Class sybil.parsers.rest.lexers.DirectiveInCommentLexer ### Members - __init__ - ... (other members) ``` ```APIDOC ## sybil.parsers.rest.CaptureParser ### Description Parser for capturing content in ReST. ### Class sybil.parsers.rest.CaptureParser ### Members - __init__ - ... (other members) ``` ```APIDOC ## sybil.parsers.rest.CodeBlockParser ### Description Parser for code blocks in ReST. ### Class sybil.parsers.rest.CodeBlockParser ### Members - __init__ - ... (other members) ### Inherited Members - pad ``` ```APIDOC ## sybil.parsers.rest.PythonCodeBlockParser ### Description Parser for Python code blocks in ReST. ### Class sybil.parsers.rest.PythonCodeBlockParser ### Members - __init__ - ... (other members) ``` ```APIDOC ## sybil.parsers.rest.DocTestParser ### Description Parser for doctests in ReST. ### Class sybil.parsers.rest.DocTestParser ### Members - __init__ - ... (other members) ``` ```APIDOC ## sybil.parsers.rest.DocTestDirectiveParser ### Description Parser for doctest directives in ReST. ### Class sybil.parsers.rest.DocTestDirectiveParser ### Members - __init__ - ... (other members) ``` ```APIDOC ## sybil.parsers.rest.SkipParser ### Description Parser for skipping content in ReST. ### Class sybil.parsers.rest.SkipParser ### Members - __init__ - ... (other members) ``` ```APIDOC ## sybil.parsers.rest.ClearNamespaceParser ### Description Parser for clearing namespaces in ReST. ### Class sybil.parsers.rest.ClearNamespaceParser ### Members - __init__ - ... (other members) ``` -------------------------------- ### Unittest Integration for Sybil Source: https://github.com/simplistix/sybil/blob/master/docs/integration.rst Python code for integrating Sybil with unittest. This code should be placed in a test module (e.g., 'test_docs.py') and utilizes the 'load_tests' protocol for unittest discovery. It specifies the path to documentation files and allows for setup/teardown callables. ```python from sybil import Sybil from sybil.parsers.rest import DocumentParser def load_tests(loader, pattern, seer): return Sybil( parsers=(DocumentParser(),), patterns=('*.rst',), path='docs', ).unittest() ``` -------------------------------- ### Parsing Data and Abstract Parsers Source: https://github.com/simplistix/sybil/blob/master/docs/api.rst Documentation for parser types and abstract parser classes. ```APIDOC ## sybil.typing.Parser ### Description Type alias for Parser. ### Data sybil.typing.Parser ``` ```APIDOC ## sybil.parsers.abstract.codeblock.AbstractCodeBlockParser ### Description Abstract base class for code block parsers. ### Class sybil.parsers.abstract.codeblock.AbstractCodeBlockParser ### Members - __init__ - ... (other members) ``` ```APIDOC ## sybil.parsers.abstract.doctest.DocTestStringParser ### Description Parser for doctest strings. ### Class sybil.parsers.abstract.doctest.DocTestStringParser ### Members - __init__ - __call__ - evaluator ``` ```APIDOC ## sybil.parsers.abstract.skip.AbstractSkipParser ### Description Abstract base class for skip parsers. ### Class sybil.parsers.abstract.skip.AbstractSkipParser ### Members - __init__ - ... (other members) ``` ```APIDOC ## sybil.parsers.abstract.clear.AbstractClearNamespaceParser ### Description Abstract base class for clear namespace parsers. ### Class sybil.parsers.abstract.clear.AbstractClearNamespaceParser ### Members - __init__ - ... (other members) ``` -------------------------------- ### Document Classes Source: https://github.com/simplistix/sybil/blob/master/docs/api.rst Documentation for Document classes, including base Document, PythonDocument, and PythonDocStringDocument, detailing their members. ```APIDOC ## sybil.Document ### Description Base class for documents, with accessible members. ### Class sybil.Document ### Members - __init__ - ... (other members) ``` ```APIDOC ## sybil.document.PythonDocument ### Description Represents a Python document, with accessible members. ### Class sybil.document.PythonDocument ### Members - __init__ - ... (other members) ``` ```APIDOC ## sybil.document.PythonDocStringDocument ### Description Represents a Python docstring document, with accessible members. ### Class sybil.document.PythonDocStringDocument ### Members - __init__ - ... (other members) ``` -------------------------------- ### bytewax.connectors.demo.RandomMetricSource Source: https://github.com/simplistix/sybil/blob/master/tests/samples/myst-complicated-nesting.md A source that generates random metrics at a specified interval. ```APIDOC ## Class: RandomMetricSource ### Description A source that simulates the generation of random metrics. It produces a stream of key-value pairs where the key is a metric name and the value is a random float. ### Initialization ```python RandomMetricSource( metric_name: str, interval: datetime.timedelta = timedelta(seconds=0.7), count: int = sys.maxsize, next_random: typing.Callable[[], float] = lambda: random.randrange(0, 10) ) ``` #### Parameters * **metric_name** (str) - Required - The name of the metric to generate. * **interval** (datetime.timedelta) - Optional - The time interval between generating new metric values. Defaults to 0.7 seconds. * **count** (int) - Optional - The maximum number of metrics to generate. Defaults to `sys.maxsize` (effectively infinite). * **next_random** (typing.Callable[[], float]) - Optional - A function that returns the next random float value. Defaults to generating a random integer between 0 and 10. ### Methods #### `list_parts()` ##### Description Returns a list of available partitions for this source. ##### Returns * `typing.List[str]` - A list of partition identifiers. #### `build_part(now: datetime.datetime, for_part: str, resume_state: typing.Optional[bytewax.connectors.demo._RandomMetricState])` ##### Description Builds and returns a part of the source for a specific partition, potentially resuming from a given state. ##### Parameters * **now** (datetime.datetime) - The current datetime. * **for_part** (str) - The identifier of the partition to build. * **resume_state** (typing.Optional[bytewax.connectors.demo._RandomMetricState]) - The state to resume from, if any. ##### Returns * An iterator yielding tuples of (str, float) representing the metric name and its random value. ``` -------------------------------- ### Sybil Classes Source: https://github.com/simplistix/sybil/blob/master/docs/api.rst Documentation for the Sybil class and its collection, detailing members and special methods. ```APIDOC ## sybil.Sybil ### Description Represents a Sybil, with accessible members and special methods like __add__. ### Class sybil.Sybil ### Members - __init__ - __add__ - ... (other members) ### Special Members - __add__ ``` ```APIDOC ## sybil.sybil.SybilCollection ### Description Manages a collection of Sybils, providing access to various members. ### Class sybil.sybil.SybilCollection ### Members - __init__ - ... (other members) ``` -------------------------------- ### RandomMetricSource Class for Demo Data Source: https://github.com/simplistix/sybil/blob/master/tests/samples/myst-complicated-nesting.md The `RandomMetricSource` class is a `FixedPartitionedSource` that generates streams of random metrics. It can be configured with a metric name, generation interval, total count, and a function for generating random values. It supports partitioning and resuming from a previous state. ```python from datetime import timedelta import sys import random import typing from bytewax.inputs import FixedPartitionedSource class RandomMetricSource(FixedPartitionedSource[typing.Tuple[str, float], _RandomMetricState]): def __init__(self, metric_name: str, interval: timedelta = timedelta(seconds=0.7), count: int = sys.maxsize, next_random: typing.Callable[[], float] = lambda: random.randrange(0, 10)): self.metric_name = metric_name self.interval = interval self.count = count self.next_random = next_random def list_parts(self) -> typing.List[str]: # Implementation for listing partitions pass def build_part(self, now: datetime.datetime, for_part: str, resume_state: typing.Optional[_RandomMetricState]): # Implementation for building a partition pass ```