CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/pypi-prettyprinter

Syntax-highlighting, declarative and composable pretty printer for Python 3.5+

Pending
Overview
Eval results
Files

comments.mddocs/

Comments and Annotations

Functions for adding comments and annotations to pretty printed output. The comment system enables adding explanatory text and metadata to formatted output while maintaining proper layout and formatting.

Capabilities

Value Comments

Add comments to Python values that will be rendered alongside the value in the pretty printed output.

def comment(value, comment_text):
    """
    Annotate a value or Doc with a comment.
    
    Parameters:
    - value: Python value or Doc to annotate
    - comment_text (str): Comment text to display
    
    Returns:
    - Annotated value or Doc with comment metadata
    
    Notes:
    - Comments are rendered next to the value in output
    - Layout algorithm handles comment placement automatically
    - Works with both Python values and Doc objects
    """

Trailing Comments

Add trailing comments that appear after the last element in collections or function arguments, forcing multiline layout.

def trailing_comment(value, comment_text):
    """
    Annotate a value with trailing comment text.
    
    Parameters:
    - value: Python value to annotate
    - comment_text (str): Comment text for trailing position
    
    Returns:
    - Annotated value with trailing comment metadata
    
    Notes:
    - Forces multiline layout as Python doesn't support inline comments
    - Comment appears after last element in collections
    - Particularly useful for indicating truncated or additional content
    """

Usage Examples

Basic Value Comments

from prettyprinter import pprint, comment, trailing_comment

# Simple value comments
data = {
    'version': comment('1.2.3', 'current release'),
    'debug': comment(True, 'development mode'),
    'max_connections': comment(100, 'production limit')
}

pprint(data)
# Output:
# {
#     'version': '1.2.3',  # current release
#     'debug': True,  # development mode  
#     'max_connections': 100  # production limit
# }

Collection Comments

from prettyprinter import pprint, comment, trailing_comment

# List with comments
numbers = [
    comment(42, 'the answer'),
    comment(3.14159, 'pi approximation'),
    comment(2.71828, 'e approximation')
]

pprint(numbers)
# Output:
# [
#     42,  # the answer
#     3.14159,  # pi approximation
#     2.71828  # e approximation
# ]

# Trailing comment for truncated data
large_dataset = trailing_comment(
    list(range(10)), 
    '...and 990 more items'
)

pprint(large_dataset)
# Output:
# [
#     0,
#     1,
#     2,
#     3,
#     4,
#     5,
#     6,
#     7,
#     8,
#     9,
#     # ...and 990 more items
# ]

Dictionary Comments

from prettyprinter import pprint, comment

# Comments on keys and values
config = {
    comment('database_url', 'primary connection'): comment(
        'postgresql://localhost/myapp', 
        'local development'
    ),
    comment('redis_url', 'cache connection'): 'redis://localhost:6379',
    'timeout': comment(30, 'seconds')
}

pprint(config, width=60)
# Output with comments on both keys and values

Comments in Custom Pretty Printers

from prettyprinter import register_pretty, pretty_call, comment
import datetime

class DatabaseConnection:
    def __init__(self, host, port, database, connected=False):
        self.host = host
        self.port = port  
        self.database = database
        self.connected = connected
        self.last_used = datetime.datetime.now() if connected else None

@register_pretty(DatabaseConnection)
def pretty_db_connection(conn, ctx):
    # Add status comments
    if conn.connected:
        status_comment = f'connected since {conn.last_used.strftime("%H:%M")}'
        return comment(
            pretty_call(ctx, DatabaseConnection, 
                       conn.host, conn.port, conn.database,
                       connected=conn.connected),
            status_comment
        )
    else:
        return comment(
            pretty_call(ctx, DatabaseConnection,
                       conn.host, conn.port, conn.database),
            'disconnected'
        )

# Usage
conn = DatabaseConnection('localhost', 5432, 'myapp', connected=True)
pprint(conn)
# DatabaseConnection('localhost', 5432, 'myapp', connected=True)  # connected since 14:30

Status and State Comments

from prettyprinter import pprint, comment, trailing_comment

class Task:
    def __init__(self, name, status='pending', priority=1):
        self.name = name
        self.status = status
        self.priority = priority

# Add status-based comments
def commented_task(task):
    status_comments = {
        'pending': 'awaiting execution',
        'running': 'in progress', 
        'completed': 'finished successfully',
        'failed': 'execution failed'
    }
    
    return comment(task, status_comments.get(task.status, 'unknown status'))

tasks = [
    commented_task(Task('backup_database', 'completed')),
    commented_task(Task('send_emails', 'running')),
    commented_task(Task('cleanup_logs', 'pending'))
]

pprint(tasks)

Debug Information Comments

from prettyprinter import pprint, comment
import sys

class DebugInfo:
    def __init__(self, obj):
        self.obj = obj
        self.type_name = type(obj).__name__
        self.memory_size = sys.getsizeof(obj)
        self.object_id = id(obj)

def with_debug_info(obj):
    """Add debug information as comments."""
    debug = DebugInfo(obj)
    return comment(
        obj, 
        f'{debug.type_name} id={debug.object_id} size={debug.memory_size}b'
    )

# Debug output with memory and type info
data = with_debug_info([1, 2, 3, 4, 5])
pprint(data)
# [1, 2, 3, 4, 5]  # list id=140123456789 size=104b

Conditional Comments

from prettyprinter import pprint, comment
import os

def conditional_comment(value, condition, comment_text):
    """Add comment only if condition is true."""
    if condition:
        return comment(value, comment_text)
    return value

# Environment-based comments
config = {
    'debug': conditional_comment(
        True, 
        os.getenv('ENV') == 'development',
        'development only'
    ),
    'api_key': conditional_comment(
        'sk-1234...', 
        os.getenv('SHOW_SECRETS') == 'true',
        'sensitive data'
    )
}

pprint(config)

Multi-line Comments

from prettyprinter import pprint, comment

# Long comments are automatically wrapped
data = comment(
    {'complex': 'configuration'},
    'This is a very long comment that describes complex configuration '
    'options and will be automatically wrapped to multiple lines when '
    'it exceeds the available width constraints during layout'
)

pprint(data, width=50)
# Output with properly wrapped multi-line comment

Nested Comment Structures

from prettyprinter import pprint, comment

# Comments within nested structures
project = {
    'name': 'myproject',
    'version': comment('2.1.0', 'latest stable'),
    'dependencies': {
        comment('requests', 'HTTP library'): comment('>=2.25.0', 'min version'),
        comment('numpy', 'numerical computing'): '>=1.20.0',
        'pytest': comment('>=6.0.0', 'testing framework')
    },
    'config': comment(
        {
            'timeout': 30,
            'retries': comment(3, 'max attempts'),
            'batch_size': comment(1000, 'optimized for memory')
        },
        'runtime configuration'
    )
}

pprint(project, width=70)
# Nested structure with comments at multiple levels

Comment Formatting Control

from prettyprinter.doc import comment_doc, commentdoc
from prettyprinter import register_pretty

class AnnotatedValue:
    def __init__(self, value, notes):
        self.value = value
        self.notes = notes

@register_pretty(AnnotatedValue)
def pretty_annotated_value(av, ctx):
    # Custom comment formatting using low-level functions
    value_doc = str(av.value)
    
    # Create multi-line comment
    comment_doc = commentdoc(' | '.join(av.notes))
    
    return comment_doc(value_doc, comment_doc)

# Usage with custom comment formatting
annotated = AnnotatedValue(
    42,
    ['the answer', 'to everything', 'according to Douglas Adams']
)
pprint(annotated)

Install with Tessl CLI

npx tessl i tessl/pypi-prettyprinter

docs

comments.md

configuration.md

core-printing.md

document-system.md

extras.md

index.md

registration.md

tile.json