CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/pypi-pylatex

A comprehensive Python library for programmatically creating and compiling LaTeX documents and snippets.

Pending

Quality

Pending

Does it follow best practices?

Impact

Pending

No eval scenarios have been run

Overview
Eval results
Files

base-classes.mddocs/

Base Classes and Object Model

Fundamental base classes that provide the foundation for all PyLaTeX objects, including the core inheritance hierarchies and common functionality. Understanding these base classes is essential for extending PyLaTeX or creating custom LaTeX elements.

Capabilities

Core Base Class

The foundational class for all LaTeX objects in PyLaTeX, providing common functionality for code generation and package management.

class LatexObject:
    def __init__(self):
        """Base class for all LaTeX objects."""
    
    def dumps(self):
        """
        Return LaTeX representation as string.
        
        Returns:
        - str: LaTeX code for this object
        """
    
    def dump(self, file_w):
        """
        Write LaTeX representation to file.
        
        Parameters:
        - file_w: file-like object to write to
        """
    
    def generate_tex(self, filepath):
        """
        Generate standalone .tex file.
        
        Parameters:
        - filepath: str, output file path
        """
    
    def dumps_packages(self):
        """
        Get required packages as LaTeX string.
        
        Returns:
        - str: LaTeX package declarations
        """
    
    def dumps_as_content(self):
        """
        String representation with paragraph formatting.
        
        Returns:
        - str: formatted content
        """

Container Base Class

Base class for LaTeX objects that can contain other objects, providing list-like functionality and content management.

class Container(LatexObject):
    def __init__(self, *, data=None):
        """
        Container for other LaTeX objects.
        
        Parameters:
        - data: list or single object, initial content
        """
    
    def create(self, child):
        """
        Context manager for adding child objects.
        
        Parameters:
        - child: LatexObject to add and return
        
        Returns:
        - child object for use in with statement
        """
    
    def dumps_content(self, **kwargs):
        """
        Represent container contents as LaTeX.
        
        Returns:
        - str: LaTeX code for all contained objects
        """
    
    # List-like methods
    def append(self, item): ...
    def extend(self, items): ...
    def insert(self, index, item): ...
    def remove(self, item): ...
    def pop(self, index=-1): ...
    def clear(self): ...
    def index(self, item): ...
    def count(self, item): ...

Usage example:

from pylatex.base_classes import Container
from pylatex import Section

# Using create() context manager
container = Container()
with container.create(Section('Title')) as section:
    section.append('Content inside the section')

# Direct manipulation
container.append('Some text')
container.extend(['More text', 'Even more text'])

Environment Base Class

Base class for LaTeX environments that use \begin{} and \end{} delimiters.

class Environment(Container):
    def __init__(self, *, options=None, arguments=None, 
                 start_arguments=None, **kwargs):
        """
        LaTeX environment with begin/end delimiters.
        
        Parameters:
        - options: Options in square brackets
        - arguments: Arguments in curly braces
        - start_arguments: Arguments only for \\begin command
        """
    
    # Properties
    omit_if_empty = False  # Skip output if environment is empty
    content_separator = "%\n"  # Separator between content items

Command Base Classes

Base classes for LaTeX commands with various argument and option handling patterns.

class CommandBase(LatexObject):
    def __init__(self, arguments=None, options=None, *, 
                 extra_arguments=None):
        """
        Base class for LaTeX commands.
        
        Parameters:
        - arguments: Command arguments
        - options: Command options
        - extra_arguments: Additional arguments
        """

class Command(CommandBase):
    def __init__(self, command=None, arguments=None, options=None, *, 
                 extra_arguments=None, packages=None):
        """
        Generic LaTeX command for one-off usage.
        
        Parameters:
        - command: str, LaTeX command name
        - arguments: Command arguments
        - options: Command options  
        - extra_arguments: Additional arguments
        - packages: Required packages
        """

class UnsafeCommand(Command):
    """Command that doesn't escape arguments/options by default."""
    escape = False

Usage examples:

from pylatex.base_classes import Command, UnsafeCommand

# Generic command
cmd = Command('textbf', arguments='bold text')
# Generates: \textbf{bold text}

# Custom command with options
cmd = Command('includegraphics', 
              arguments='image.png',
              options=['width=0.5\\textwidth', 'center'])
# Generates: \includegraphics[width=0.5\textwidth,center]{image.png}

# Unsafe command (no escaping)
unsafe_cmd = UnsafeCommand('raw', arguments='$x^2$')

Container Command

Command that contains data, combining command functionality with container capabilities.

class ContainerCommand(Container):
    def __init__(self, arguments=None, options=None, *, data=None, **kwargs):
        """
        Command that contains data: \\CommandName{data}.
        
        Parameters:
        - arguments: Command arguments
        - options: Command options
        - data: Container content
        """

Float Base Class

Base class for floating environments like figures and tables.

class Float(Environment):
    def __init__(self, *, position=None, **kwargs):
        """
        Base class for floating environments.
        
        Parameters:
        - position: str, float position specifier ('h', 't', 'b', 'p', '!')
        """
    
    def add_caption(self, caption):
        """
        Add caption to float.
        
        Parameters:
        - caption: str or LatexObject, caption content
        """

Parameter Classes

Classes for handling LaTeX command options and arguments with different formatting requirements.

class Options:
    def __init__(self, *args, **kwargs):
        """
        LaTeX command options in square brackets [option1,option2].
        """

class SpecialOptions(Options):
    """Options separated by '][' instead of ',' -> [option1][option2]"""

class Arguments:
    def __init__(self, *args, **kwargs):
        """
        LaTeX command arguments in curly braces {arg1}{arg2}.
        """

class SpecialArguments(Arguments):
    """Arguments separated by ',' instead of '}{' -> {arg1,arg2}"""

Object Hierarchy

The PyLaTeX object hierarchy follows this structure:

LatexObject (base)
├── CommandBase
│   ├── Command
│   │   └── UnsafeCommand
│   └── Various command classes (Package, etc.)
├── Container
│   ├── Environment
│   │   ├── Document
│   │   ├── Section
│   │   ├── Figure (Float)
│   │   └── Various environments
│   └── ContainerCommand
│       └── TextColor, etc.
└── Fragment (special container)

Extending PyLaTeX

Create custom LaTeX elements by inheriting from appropriate base classes:

from pylatex.base_classes import Environment, Command

class CustomEnvironment(Environment):
    """Custom LaTeX environment."""
    
    _latex_name = "myenvironment"  # LaTeX environment name
    packages = [Package('mypackage')]  # Required packages
    
    def __init__(self, title, **kwargs):
        super().__init__(arguments=title, **kwargs)

class CustomCommand(Command):
    """Custom LaTeX command."""
    
    def __init__(self, text):
        super().__init__('mycommand', arguments=text)

Common Patterns

Context Manager Usage

Many PyLaTeX objects support context manager syntax for cleaner code:

from pylatex import Document, Section

doc = Document()

with doc.create(Section('Introduction')) as intro:
    intro.append('This is automatically added to the section')
    with intro.create(Subsection('Background')) as bg:
        bg.append('Nested content')

Package Management

Objects automatically manage their package dependencies:

from pylatex.math import Matrix
from pylatex import Document

doc = Document()
matrix = Matrix([[1, 2], [3, 4]])
doc.append(matrix)

# 'amsmath' package is automatically added to doc.packages
print([p.name for p in doc.packages])  # Includes 'amsmath'

Escaping Control

Control LaTeX character escaping on a per-object basis:

from pylatex.base_classes import Command
from pylatex.utils import NoEscape

# Escaped by default
cmd1 = Command('textbf', arguments='Text with $pecial chars')

# No escaping
cmd2 = Command('textbf', arguments=NoEscape('Text with $pecial chars'))

# Object-level escaping control
class MyCommand(Command):
    escape = False  # Never escape arguments

Install with Tessl CLI

npx tessl i tessl/pypi-pylatex

docs

base-classes.md

configuration.md

document.md

figures.md

index.md

layout.md

lists.md

math.md

quantities.md

references.md

sectioning.md

tables.md

text-formatting.md

tikz.md

utilities.md

tile.json