### Usage Example for isasyncgenfunction Source: https://github.com/cool-rr/pysnooper/blob/master/_autodocs/api-reference/pycompat.md Demonstrates how to use the isasyncgenfunction utility to check both asynchronous and regular generator functions. ```Python from pysnooper.pycompat import isasyncgenfunction async def my_async_gen(): yield 1 def my_regular_gen(): yield 1 print(isasyncgenfunction(my_async_gen)) # True (Python 3.6+) print(isasyncgenfunction(my_regular_gen)) # False ``` -------------------------------- ### Install PySnooper using Pip Source: https://github.com/cool-rr/pysnooper/blob/master/README.md Install PySnooper using the pip package manager. This is the recommended method for most users. ```console $ pip install pysnooper ``` -------------------------------- ### Usage Example for iscoroutinefunction Source: https://github.com/cool-rr/pysnooper/blob/master/_autodocs/api-reference/pycompat.md Demonstrates how to use the iscoroutinefunction utility to check both asynchronous and regular functions. ```Python from pysnooper.pycompat import iscoroutinefunction async def my_async_func(): pass def my_regular_func(): pass print(iscoroutinefunction(my_async_func)) # True (Python 3.5+) print(iscoroutinefunction(my_regular_func)) # False ``` -------------------------------- ### Usage Example for text_type Source: https://github.com/cool-rr/pysnooper/blob/master/_autodocs/api-reference/pycompat.md Shows how to use the `text_type` alias for converting objects to text strings, maintaining cross-version compatibility. ```python from pysnooper.pycompat import text_type def convert_to_text(obj): return text_type(obj) ``` -------------------------------- ### Install PySnooper on Fedora Linux Source: https://github.com/cool-rr/pysnooper/blob/master/README.md Install PySnooper on Fedora Linux using the `dnf` package manager. This is specific to Fedora users. ```console $ dnf install python3-pysnooper ``` -------------------------------- ### Enable tracing programmatically Source: https://github.com/cool-rr/pysnooper/blob/master/_autodocs/api-reference/tracer.md This internal example shows how to manually set the trace function using sys.settrace. This is typically handled automatically by pysnooper. ```python # This is called automatically by Python's tracing mechanism sys.settrace(tracer.trace) ``` -------------------------------- ### Install PySnooper on Arch Linux Source: https://github.com/cool-rr/pysnooper/blob/master/README.md Install PySnooper on Arch Linux using the `yay` AUR helper. This is specific to Arch Linux users. ```console $ yay -S python-pysnooper ``` -------------------------------- ### Implement PathLike Protocol Source: https://github.com/cool-rr/pysnooper/blob/master/_autodocs/api-reference/pycompat.md This example demonstrates how to use the PathLike abstract base class for file system path objects. It shows how pathlib.Path is automatically recognized and how to use it with pysnooper.snoop. ```Python from pysnooper.pycompat import PathLike import pathlib import pysnooper # pathlib.Path is automatically a PathLike @pysnooper.snoop(pathlib.Path('/tmp/trace.log')) def func(): pass ``` -------------------------------- ### Usage Example for string_types Source: https://github.com/cool-rr/pysnooper/blob/master/_autodocs/api-reference/pycompat.md Demonstrates how to use the `string_types` alias to check if an object is a string, ensuring compatibility between Python 2 and 3. ```python from pysnooper.pycompat import string_types def is_string(obj): return isinstance(obj, string_types) ``` -------------------------------- ### Install PySnooper using Conda Source: https://github.com/cool-rr/pysnooper/blob/master/README.md Install PySnooper using the conda package manager from the conda-forge channel. This is an alternative installation method for users who prefer Conda. ```console $ conda install -c conda-forge pysnooper ``` -------------------------------- ### Automatic Variable Expansion Example Source: https://github.com/cool-rr/pysnooper/blob/master/_autodocs/api-reference/variables.md This example demonstrates how pysnooper's `watch_explode` can automatically detect and expand different data structures (dict, list, object) assigned to the same variable across function iterations. ```python import pysnooper @pysnooper.snoop(watch_explode=('result',)) def mixed_data(): # On first iteration, result is a dict -> Uses Keys result = {'name': 'Alice', 'age': 30} # Later, result is a list -> Uses Indices result = [1, 2, 3, 4, 5] # Later, result is an object -> Uses Attrs class Record: pass result = Record() result.value = 42 return result ``` -------------------------------- ### Examples of WritableStream Compatible Objects Source: https://github.com/cool-rr/pysnooper/blob/master/_autodocs/types.md Demonstrates various objects that can be used as output streams with PySnooper's snoop decorator, including standard output, standard error, StringIO, and file objects. ```python import sys import io # All of these work as output: @pysnooper.snoop(sys.stdout) @pysnooper.snoop(sys.stderr) @pysnooper.snoop(io.StringIO()) @pysnooper.snoop(open('file.log', 'w')) def func(): pass ``` -------------------------------- ### Basic PySnooper Usage Example Source: https://github.com/cool-rr/pysnooper/blob/master/_autodocs/START_HERE.md Demonstrates how to use the @pysnooper.snoop() decorator to trace function execution and variable changes. Output is sent to stderr. ```python import pysnooper @pysnooper.snoop() def calculate(x, y): result = x + y return result calculate(5, 3) # Output to stderr showing each line and variable changes ``` -------------------------------- ### Usage Example for binary_type Source: https://github.com/cool-rr/pysnooper/blob/master/_autodocs/api-reference/pycompat.md Illustrates using the `binary_type` alias to check if an object is a byte string, ensuring consistent behavior across Python versions. ```python from pysnooper.pycompat import binary_type def is_binary(obj): return isinstance(obj, binary_type) ``` -------------------------------- ### Usage Example for collections_abc Source: https://github.com/cool-rr/pysnooper/blob/master/_autodocs/api-reference/pycompat.md Demonstrates using the `collections_abc` alias to check for iterable, mapping, and sequence types, maintaining compatibility with older Python versions. ```python from pysnooper.pycompat import collections_abc def is_iterable(obj): return isinstance(obj, collections_abc.Iterable) def is_mapping(obj): return isinstance(obj, collections_abc.Mapping) def is_sequence(obj): return isinstance(obj, collections_abc.Sequence) ``` -------------------------------- ### Accessing PySnooper Version Information Source: https://github.com/cool-rr/pysnooper/blob/master/_autodocs/module-map.md Illustrates how to access the `__version__` string and `__version_info__` tuple from the PySnooper package. This is useful for checking the installed version or programmatically accessing version components. ```python import pysnooper print(pysnooper.__version__) # '1.2.3' print(pysnooper.__version_info__[0]) # 1 print(pysnooper.__version_info__.major) # 1 ``` -------------------------------- ### Instantiate Attrs Variable Watcher Source: https://github.com/cool-rr/pysnooper/blob/master/_autodocs/api-reference/variables.md Example of creating an instance of the `Attrs` variable watcher to inspect attributes of a module. This requires importing `Attrs` and `sys`, and obtaining the current frame. ```python from pysnooper.variables import Attrs import sys var = Attrs('sys') frame = sys._getframe() items = var.items(frame) # Returns: (('sys', ''), ('sys.version', '3.x.x ...'), ...) ``` -------------------------------- ### PySnooper Large Output with Prefix for Grepping Source: https://github.com/cool-rr/pysnooper/blob/master/_autodocs/configuration.md Add a custom prefix to every trace line for easier filtering and grepping in log files. This example logs to a file and prefixes lines with '[APP-TRACE] '. ```python @pysnooper.snoop( output='/tmp/app.log', prefix='[APP-TRACE] ', watch=('request_id', 'status'), ) def handle_request(request_id, request): # All lines prefixed: [APP-TRACE] ... # Easy to grep: grep "[APP-TRACE]" /tmp/app.log pass ``` -------------------------------- ### Basic PySnooper Tracing to stderr Source: https://github.com/cool-rr/pysnooper/blob/master/_autodocs/configuration.md A simple example of using the @pysnooper.snoop() decorator to trace function execution to standard error. ```python import pysnooper @pysnooper.snoop() def process_data(items): total = sum(items) return total ``` -------------------------------- ### Handle File Writing Errors with PySnooper Source: https://github.com/cool-rr/pysnooper/blob/master/_autodocs/errors.md Illustrates handling potential file writing errors when specifying a log file path for PySnooper. It shows an example that might raise a PermissionError and suggests using a writable directory like /tmp. ```python @pysnooper.snoop('/root/trace.log') # May raise PermissionError def func(): pass # Solution: use writable directory @pysnooper.snoop('/tmp/trace.log') def func(): pass ``` -------------------------------- ### Get Current Stack Frame Source: https://github.com/cool-rr/pysnooper/blob/master/_autodocs/types.md Demonstrates how to retrieve the current execution frame using sys._getframe(). Shows how to access frame attributes like filename, line number, and local variables. ```python import sys import inspect frame = sys._getframe() # Get current frame print(frame.f_code.co_filename) print(frame.f_lineno) print(frame.f_locals) ``` -------------------------------- ### Import PySnooper Top-Level Source: https://github.com/cool-rr/pysnooper/blob/master/_autodocs/module-map.md Import the entire pysnooper module to access its functions and classes using the module namespace. This is a common way to start using PySnooper. ```python import pysnooper tracer = pysnooper.snoop() attrs = pysnooper.Attrs('obj') ``` -------------------------------- ### PySnooper Tracer Return Value Examples Source: https://github.com/cool-rr/pysnooper/blob/master/_autodocs/types.md Demonstrates the usage of the `pysnooper.snoop()` decorator with different types of Python objects: regular functions, generator functions, and classes. ```python import pysnooper # Regular function @pysnooper.snoop() def regular_function(x: int) -> int: return x * 2 # Generator function @pysnooper.snoop() def generator_function(n: int): for i in range(n): yield i * 2 # Class methods @pysnooper.snoop() class MyClass: def method(self): pass ``` -------------------------------- ### PySnooper Fine-Grained Variable Watching Source: https://github.com/cool-rr/pysnooper/blob/master/_autodocs/configuration.md Precisely control which variables and their attributes/keys/indices are watched. This example watches specific attributes, excludes others, watches dictionary keys, and watches the last 10 items of a list. ```python import pysnooper @pysnooper.snoop(watch=( pysnooper.Attrs('self', exclude=('_cache', '__dict__')), pysnooper.Keys('config'), pysnooper.Indices('items')[-10:], # Last 10 items only )) def process(self, config, items): pass ``` -------------------------------- ### Path Handling with PySnooper Source: https://github.com/cool-rr/pysnooper/blob/master/_autodocs/api-reference/pycompat.md Demonstrates how to set up PySnooper tracing to accept either string paths or `pathlib.Path` objects for output. This ensures flexibility in specifying output locations. ```python from pysnooper.pycompat import PathLike import pysnooper def setup_tracer(output_path): # Accepts both str and pathlib.Path if isinstance(output_path, (str, PathLike)): return pysnooper.snoop(output=output_path) ``` -------------------------------- ### Output Parameter Type Definitions Source: https://github.com/cool-rr/pysnooper/blob/master/_autodocs/types.md Illustrates the various types accepted by the 'output' parameter in Tracer.__init__, including None, string paths, PathLike objects, callables, and WritableStream objects. ```python Union[ None, # stderr str, # file path PathLike, # pathlib.Path-like object Callable[[str], None], # callable receiving lines WritableStream # object with .write() method ] ``` -------------------------------- ### Import Utilities from PySnooper.utils Source: https://github.com/cool-rr/pysnooper/blob/master/_autodocs/START_HERE.md Import utility functions for string representation, truncation, exception formatting, and writable streams from the pysnooper.utils module. ```python from pysnooper.utils import get_shortish_repr, truncate, format_exception from pysnooper.utils import WritableStream ``` -------------------------------- ### PySnooper Version Information Source: https://github.com/cool-rr/pysnooper/blob/master/_autodocs/module-map.md Access the version number and version info tuple directly from the __init__.py file. ```python __version__ = '1.2.3' __version_info__ = VersionInfo(1, 2, 3) ``` -------------------------------- ### Direct Function Calls for Utility Functions Source: https://github.com/cool-rr/pysnooper/blob/master/_autodocs/module-map.md Demonstrates direct usage of utility functions from pysnooper.utils for formatting and truncating data. ```python from pysnooper.utils import get_shortish_repr, truncate, format_exception repr_str = get_shortish_repr(obj, max_length=100) short_str = truncate(long_string, 50) exc_str = format_exception(exc_type, exc_value) ``` -------------------------------- ### Format Regular Exception Source: https://github.com/cool-rr/pysnooper/blob/master/_autodocs/api-reference/utils.md Demonstrates how to format a standard Python exception using format_exception. This is useful for logging or displaying errors in a user-friendly manner. ```python from pysnooper.utils import format_exception import traceback try: x = 1 / 0 except Exception as e: exc_type, exc_value = type(e), e formatted = format_exception(exc_type, exc_value) print(formatted) # ZeroDivisionError: division by zero ``` -------------------------------- ### Using watch vs watch_explode Source: https://github.com/cool-rr/pysnooper/blob/master/_autodocs/api-reference/variables.md Compares the usage of `watch` for simple expressions and `watch_explode` for automatic variable expansion. `watch` monitors basic variables, while `watch_explode` intelligently expands complex objects. ```python import pysnooper @pysnooper.snoop(watch=('x', 'y')) # Simple expressions, no expansion def simple(): x = 1 y = 2 return x + y @pysnooper.snoop(watch_explode=('obj', 'data')) # Auto-expand def complex(): obj = MyClass() data = [1, 2, 3] return process(obj, data) ``` -------------------------------- ### Disable PySnooper with Environment Variable Source: https://github.com/cool-rr/pysnooper/blob/master/_autodocs/configuration.md Set the PYSNOOPER_DISABLED environment variable to disable PySnooper globally. This example shows disabling it before running a script and then re-enabling it. ```bash # Disable PySnooper at runtime export PYSNOOPER_DISABLED=1 python my_script.py # Re-enable unset PYSNOOPER_DISABLED ``` -------------------------------- ### truncate Source: https://github.com/cool-rr/pysnooper/blob/master/_autodocs/api-reference/utils.md Truncates a string to a maximum length, preserving the start and end with an ellipsis if necessary. It ensures that the truncated string does not exceed the specified maximum length. ```APIDOC ## Function: truncate ### Description Truncates a string to a maximum length, preserving start and end. If the string's length is less than or equal to `max_length`, it is returned unchanged. Otherwise, it is truncated with '...' in the middle. ### Signature ```python def truncate(string: str, max_length: int) -> str ``` ### Parameters #### Path Parameters - **string** (str) - Required - The string to truncate. - **max_length** (int) - Required - Maximum length of result. ### Returns `str` - The original string if <= max_length, otherwise truncated with "..." in the middle. ### Example ```python from pysnooper.utils import truncate s = "The quick brown fox jumps over the lazy dog" print(truncate(s, 20)) # The quic...lazy dog print(truncate(s, 30)) # The quick brown f...lazy dog print(truncate(s, 100)) # The quick brown fox jumps over the lazy dog (unchanged) ``` ``` -------------------------------- ### Tracer Constructor Source: https://github.com/cool-rr/pysnooper/blob/master/_autodocs/api-reference/tracer.md Initializes the Tracer class, which can be used as a decorator or context manager to control the tracing behavior. It accepts various parameters to customize output, watched variables, depth, and more. ```APIDOC ## Tracer Constructor ### Description Initializes the Tracer class, which can be used as a decorator or context manager to control the tracing behavior. It accepts various parameters to customize output, watched variables, depth, and more. ### Parameters #### Constructor Parameters - **output** (`str | PathLike | Callable | WritableStream | None`) - Optional - `None` - Where to write the trace output. If `None`, writes to stderr. If a string/PathLike, treated as a file path. If callable, called with each line of output. If a stream object with `.write()` method, output written there. - **watch** (`tuple[str | BaseVariable]`) - Optional - `()` - Tuple of variable names or expressions to watch. Will display their values whenever they change. Strings are wrapped in `CommonVariable`. - **watch_explode** (`tuple[str | BaseVariable]`) - Optional - `()` - Tuple of variable names or expressions to watch and automatically expand. Uses `Exploding` to determine expansion strategy (Attrs for objects, Keys for dicts, Indices for sequences). - **depth** (`int`) - Optional - `1` - How many levels deep to trace into called functions. Minimum value is 1. - **prefix** (`str`) - Optional - `''` - String prefix to add to the beginning of every output line for easier grepping. - **overwrite** (`bool`) - Optional - `False` - If `True` and output is a file path, overwrite the file instead of appending. Only valid when output is a file path. - **thread_info** (`bool`) - Optional - `False` - If `True`, include thread ID and name in the output for multi-threaded applications. Not compatible with `normalize=True`. - **custom_repr** (`tuple[tuple[type | Callable, Callable]]`) - Optional - `()` - Custom repr functions for specific types or conditions. Each tuple contains (condition, action). Condition is a type or callable predicate, action is a callable that returns the repr string. - **max_variable_length** (`int | None`) - Optional - `100` - Maximum characters to display for variable values. If `None`, never truncate. Truncation is applied symmetrically (show start and end). - **normalize** (`bool`) - Optional - `False` - If `True`, strip machine-dependent data (paths, memory addresses, timestamps) for comparing traces across runs. Cannot be combined with `thread_info=True`. - **relative_time** (`bool`) - Optional - `False` - If `True`, show timestamps relative to function start time instead of wall-clock time. - **color** (`bool`) - Optional - `Automatic` - Enable ANSI color codes in output. Defaults to `True` on Linux, macOS, Cygwin; `False` on Windows. Only applies when output is stderr. ### Returns `Tracer` instance ``` -------------------------------- ### Relative Timestamps Source: https://github.com/cool-rr/pysnooper/blob/master/ADVANCED_USAGE.md Use `relative_time=True` to display timestamps relative to the start of the snooped function. This simplifies analyzing the timing of events within a single execution. ```python @pysnooper.snoop(relative_time=True) def function_with_relative_time(): pass ``` -------------------------------- ### PySnooper Deep Call Tracing Source: https://github.com/cool-rr/pysnooper/blob/master/_autodocs/configuration.md Control the maximum depth of nested function calls that PySnooper will trace. This example limits tracing to 3 levels deep. ```python # Trace 3 levels of function calls @pysnooper.snoop(depth=3) def outer(): def middle(): def inner(): x = 1 return x return inner() return middle() return inner() ``` -------------------------------- ### Time Formatting and Parsing Source: https://github.com/cool-rr/pysnooper/blob/master/_autodocs/api-reference/pycompat.md Shows how to parse a string representation of a time duration into a `timedelta` object and format it back into a string. Useful for log analysis and time calculations. ```python from pysnooper.pycompat import timedelta_format, timedelta_parse import datetime # In a log analysis tool elapsed_str = '00:02:34.123456' elapsed = timedelta_parse(elapsed_str) # Add 10 seconds new_elapsed = elapsed + datetime.timedelta(seconds=10) new_str = timedelta_format(new_elapsed) print(new_str) # '00:02:44.123456' ``` -------------------------------- ### Compatibility Source: https://github.com/cool-rr/pysnooper/blob/master/_autodocs/START_HERE.md Compatibility components for different Python versions, available from `pysnooper.pycompat`. ```APIDOC ## Compatibility Import these from `pysnooper.pycompat`: - `ABC`: Abstract Base Classes. - `PathLike`: Protocol for path-like objects. - `PY2`: Boolean indicating if running on Python 2. - `PY3`: Boolean indicating if running on Python 3. - `timedelta_format`: Function to format timedelta objects. - `timedelta_parse`: Function to parse timedelta strings. ``` -------------------------------- ### Decorate Function for Debugging Source: https://github.com/cool-rr/pysnooper/blob/master/README.md Use the `@pysnooper.snoop()` decorator to log the execution flow and variable changes within a function. This is the simplest way to start using PySnooper. ```python import pysnooper @pysnooper.snoop() def number_to_bits(number): if number: bits = [] while number: number, remainder = divmod(number, 2) bits.insert(0, remainder) return bits else: return [0] number_to_bits(6) ``` -------------------------------- ### Top-level API Source: https://github.com/cool-rr/pysnooper/blob/master/_autodocs/START_HERE.md These are the primary components you can import directly from the `pysnooper` package to use its core functionality. ```APIDOC ## Top-level API Import these directly from the `pysnooper` package: - `snoop`: The main decorator for tracing code execution. - `Attrs`: Utility for watching attributes. - `Keys`: Utility for watching dictionary keys. - `Indices`: Utility for watching list/tuple indices. - `Exploding`: Utility for handling exceptions during tracing. - `__version__`: The installed version of PySnooper. - `__version_info__`: Detailed version information. ``` -------------------------------- ### Disable Specific PySnooper Decorators at Runtime Source: https://github.com/cool-rr/pysnooper/blob/master/_autodocs/configuration.md Conditionally disable PySnooper tracing based on environment variables. This example disables tracing for production environments by setting PYSNOOPER_DISABLED. ```python import os # Disable tracing for production if os.environ.get('ENV') == 'production': os.environ['PYSNOOPER_DISABLED'] = '1' @pysnooper.snoop() # Will be ignored in production def expensive_operation(): pass ``` -------------------------------- ### Tracer Constructor Parameters Source: https://github.com/cool-rr/pysnooper/blob/master/_autodocs/api-reference/tracer.md Defines the parameters available for the Tracer constructor, controlling output, variable watching, depth, prefix, and more. ```python Tracer( output=None, watch=(), watch_explode=(), depth=1, prefix='', overwrite=False, thread_info=False, custom_repr=(), max_variable_length=100, normalize=False, relative_time=False, color=sys.platform in ('linux', 'linux2', 'cygwin', 'darwin') ) ``` -------------------------------- ### Normalize Representation String Source: https://github.com/cool-rr/pysnooper/blob/master/_autodocs/api-reference/utils.md Removes memory addresses from Python object representation strings. Use this to get consistent repr strings for objects, especially when logging or comparing them. ```python from pysnooper.utils import normalize_repr class MyClass: pass obj = MyClass() repr_str = repr(obj) # '<__main__.MyClass object at 0x7f1234567890>' normalized = normalize_repr(repr_str) # '<__main__.MyClass object>' ``` -------------------------------- ### Use WritableStream with PySnooper Source: https://github.com/cool-rr/pysnooper/blob/master/_autodocs/api-reference/utils.md Demonstrates how to use an object conforming to the `WritableStream` protocol (like `io.StringIO`) with `@pysnooper.snoop` to capture traced output. ```python import io import pysnooper # io.StringIO is automatically a WritableStream output = io.StringIO() @pysnooper.snoop(output) def traced(): x = 1 return x traced() print(output.getvalue()) ``` -------------------------------- ### PySnooper Custom Type Formatting Source: https://github.com/cool-rr/pysnooper/blob/master/_autodocs/configuration.md Define custom functions to format specific object types for clearer debugging output. This example shows custom formatting for NumPy arrays. ```python import numpy as np def is_array(obj): return isinstance(obj, np.ndarray) def format_array(arr): return f'ndarray(shape={arr.shape}, dtype={arr.dtype}, min={arr.min()}, max={arr.max()})' @pysnooper.snoop(custom_repr=((is_array, format_array),)) def analyze(): data = np.random.random((1000, 1000)) return data ``` -------------------------------- ### Truncate String Source: https://github.com/cool-rr/pysnooper/blob/master/_autodocs/api-reference/utils.md Truncates a string to a specified maximum length, preserving the start and end with an ellipsis in the middle if necessary. Use when displaying strings that might exceed a certain width. ```python from pysnooper.utils import truncate s = "The quick brown fox jumps over the lazy dog" print(truncate(s, 20)) # The quic...lazy dog print(truncate(s, 30)) # The quick brown f...lazy dog print(truncate(s, 100)) # The quick brown fox jumps over the lazy dog (unchanged) ``` -------------------------------- ### PathLike Class Source: https://github.com/cool-rr/pysnooper/blob/master/_autodocs/api-reference/pycompat.md An abstract base class for file system path objects, ensuring compatibility across Python versions. ```APIDOC ## Class PathLike ### Description An abstract base class for implementing the file system path protocol. It ensures compatibility for path-like objects across different Python versions (Python 2.7 - 3.6+). ### Protocol - Must implement `__fspath__()` which returns a string path. - Old `pathlib` implementations are recognized by duck typing. ### Usage ```python from pysnooper.pycompat import PathLike import pathlib import pysnooper # pathlib.Path is automatically a PathLike @pysnooper.snoop(pathlib.Path('/tmp/trace.log')) def func(): pass ``` ``` -------------------------------- ### Utilities Source: https://github.com/cool-rr/pysnooper/blob/master/_autodocs/START_HERE.md Utility functions available for import from `pysnooper.utils` to assist with common debugging tasks. ```APIDOC ## Utilities Import these from `pysnooper.utils`: - `get_shortish_repr`: Get a shortened representation of an object. - `truncate`: Truncate a string to a specified length. - `format_exception`: Format exception information. - `WritableStream`: A stream-like object that can be written to. ``` -------------------------------- ### Get Bounded-Length Object Representation Source: https://github.com/cool-rr/pysnooper/blob/master/_autodocs/api-reference/utils.md Use `get_shortish_repr` to obtain a string representation of an object with optional truncation and normalization. It handles custom repr functions and falls back to a default message on errors. ```python from pysnooper.utils import get_shortish_repr obj = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] # No truncation print(get_shortish_repr(obj, max_length=None)) # [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] # With truncation print(get_shortish_repr(obj, max_length=15)) # [1, 2, 3...9, 10] # With normalization (removes memory addresses) class MyClass: pass obj = MyClass() print(get_shortish_repr(obj, normalize=True)) # <__main__.MyClass object> (address removed) ``` -------------------------------- ### PySnooper Tracer Custom Repr for Large Lists Source: https://github.com/cool-rr/pysnooper/blob/master/_autodocs/api-reference/tracer.md Define custom representation functions for specific types or conditions using the 'custom_repr' parameter. This example shows how to provide a custom representation for large lists. ```python def is_large_list(obj): return isinstance(obj, list) and len(obj) > 100 def repr_large_list(obj): return f'list(size={len(obj)})' @pysnooper.snoop(custom_repr=((is_large_list, repr_large_list),)) def handle_data(): big_list = list(range(1000)) return len(big_list) ``` -------------------------------- ### Import Compatibility Modules from PySnooper.pycompat Source: https://github.com/cool-rr/pysnooper/blob/master/_autodocs/START_HERE.md Import compatibility-related modules and constants such as ABC, PathLike, PY2, PY3, and formatting/parsing functions for timedeltas. ```python from pysnooper.pycompat import ABC, PathLike, PY2, PY3 from pysnooper.pycompat import timedelta_format, timedelta_parse ``` -------------------------------- ### Write a prefixed message with pysnooper tracer Source: https://github.com/cool-rr/pysnooper/blob/master/_autodocs/api-reference/tracer.md Demonstrates using the tracer's write method to output a custom message with a configured prefix. This is useful for custom logging within traced code. ```python tracer = pysnooper.snoop(prefix='DEBUG: ') tracer.write('This is a debug message') # Output: "DEBUG: This is a debug message\n" ``` -------------------------------- ### Attrs Source: https://github.com/cool-rr/pysnooper/blob/master/_autodocs/api-reference/variables.md Expands an object by showing all its attributes and slots. It displays the main object's representation and iterates over instance attributes and slot descriptors, showing each accessible attribute and its value, while skipping attributes that raise exceptions. ```APIDOC ## Class: Attrs Expands an object by showing all its attributes and slots. ### Constructor ```python Attrs(source: str, exclude: tuple = ()) ``` **Parameters:** | Parameter | Type | Required | Default | Description | |-----------|------|----------|---------|-------------| | `source` | `str` | Yes | — | The Python expression referencing an object (e.g., `'self'`, `'obj'`). | | `exclude` | `tuple[str]` | No | `()` | Attribute names to exclude (e.g., `('_private', '__dict__')`). | **Returns:** `Attrs` instance **Behavior:** - Shows the main object's repr. - Iterates over `__dict__` (instance attributes) and `__slots__` (slot descriptors). - For each accessible attribute, shows `obj.attr = value`. - Skips attributes that raise exceptions. **Output format:** ``` New var:....... self = New var:....... self.name = 'John' New var:....... self.age = 30 New var:....... self.__dict__ = {'name': 'John', 'age': 30} ``` **Example:** ```python import pysnooper class Person: def __init__(self, name): self.name = name self._private = 'secret' @pysnooper.snoop(watch=(pysnooper.Attrs('self', exclude=('_private',)),)) def greet(self): self.name = self.name.upper() return f'Hello {self.name}' person = Person('alice') person.greet() ``` ``` -------------------------------- ### Utility Functions Source: https://github.com/cool-rr/pysnooper/blob/master/_autodocs/module-map.md Directly callable utility functions for string representation and exception formatting. ```APIDOC ## pysnooper.utils.get_shortish_repr(obj, max_length) ### Description Gets a shortened string representation of an object, truncated to a maximum length. ### Method Function ### Endpoint N/A ### Parameters #### Path Parameters N/A #### Query Parameters N/A #### Request Body N/A ### Request Example ```python from pysnooper.utils import get_shortish_repr repr_str = get_shortish_repr(obj, max_length=100) ``` ### Response #### Success Response (200) - **repr_str** (string) - The shortened string representation of the object. #### Response Example N/A ``` ```APIDOC ## pysnooper.utils.truncate(text, max_length) ### Description Truncates a string to a specified maximum length. ### Method Function ### Endpoint N/A ### Parameters #### Path Parameters N/A #### Query Parameters N/A #### Request Body N/A ### Request Example ```python from pysnooper.utils import truncate short_str = truncate(long_string, 50) ``` ### Response #### Success Response (200) - **short_str** (string) - The truncated string. #### Response Example N/A ``` ```APIDOC ## pysnooper.utils.format_exception(exc_type, exc_value) ### Description Formats an exception type and value into a readable string. ### Method Function ### Endpoint N/A ### Parameters #### Path Parameters N/A #### Query Parameters N/A #### Request Body N/A ### Request Example ```python from pysnooper.utils import format_exception exc_str = format_exception(exc_type, exc_value) ``` ### Response #### Success Response (200) - **exc_str** (string) - The formatted exception string. #### Response Example N/A ``` -------------------------------- ### Using PathLike with PySnooper Source: https://github.com/cool-rr/pysnooper/blob/master/_autodocs/types.md Shows how to use a pathlib.Path object as a file path argument for the pysnooper.snoop decorator. ```python from pathlib import Path import pysnooper @pysnooper.snoop(Path('/tmp/trace.log')) def func(): pass ``` -------------------------------- ### Imports in tracer.py Source: https://github.com/cool-rr/pysnooper/blob/master/_autodocs/module-map.md Shows the necessary imports for the tracer.py module, including standard libraries and internal Pysnooper modules. ```python import functools import inspect import opcode import os import sys import re import collections import datetime import itertools import threading import traceback from .variables import CommonVariable, Exploding, BaseVariable from . import utils, pycompat ``` -------------------------------- ### Format Exception Group (Python 3.11+) Source: https://github.com/cool-rr/pysnooper/blob/master/_autodocs/api-reference/utils.md Shows how to format a BaseExceptionGroup, which aggregates multiple exceptions. This is applicable for Python 3.11 and later versions. ```python # With exception group (Python 3.11+) try: try: raise ValueError("error 1") except ValueError as e1: try: raise TypeError("error 2") except TypeError as e2: raise BaseExceptionGroup("Multiple", [e1, e2]) except BaseExceptionGroup as eg: formatted = format_exception(type(eg), eg) print(formatted) # BaseExceptionGroup: 'Multiple' (2 sub-exceptions: ValueError, TypeError) ``` -------------------------------- ### Decorator Usage with Pysnooper Source: https://github.com/cool-rr/pysnooper/blob/master/_autodocs/module-map.md Demonstrates how to use the @pysnooper.snoop decorator to trace function execution. Supports default logging, file logging, and variable watching. ```python @pysnooper.snoop() def func(): pass ``` ```python @pysnooper.snoop('/path/to/file.log') def func(): pass ``` ```python @pysnooper.snoop(watch=('x', 'y')) def func(): pass ``` -------------------------------- ### PySnooper Usage with Expansion Watchers Source: https://github.com/cool-rr/pysnooper/blob/master/_autodocs/module-map.md Shows how to use `snoop` with expansion watchers like `Attrs`, `Keys`, and `Indices` to trace specific object attributes, dictionary keys, or list indices. This allows for more detailed inspection of data structures during tracing. ```python import pysnooper @pysnooper.snoop(watch=( pysnooper.Attrs('self'), pysnooper.Keys('dict'), pysnooper.Indices('list'), )) def trace_with_expansion(): pass ``` -------------------------------- ### Configure PySnooper Output Destinations Source: https://github.com/cool-rr/pysnooper/blob/master/_autodocs/types.md Shows how to configure PySnooper's output to different destinations: stderr (default), a file path (string or PathLike), a custom logger function, or a file-like object like sys.stdout. ```python import pysnooper import sys from pathlib import Path # To stderr (default) @pysnooper.snoop() def func1(): pass # To file (string path) @pysnooper.snoop('/tmp/trace.log') def func2(): pass # To file (pathlib.Path) @pysnooper.snoop(Path('/tmp/trace.log')) def func3(): pass # To custom callable def my_logger(line): print(f'[TRACE] {line}') @pysnooper.snoop(my_logger) def func4(): pass # To file-like object @pysnooper.snoop(sys.stdout) def func5(): pass ``` -------------------------------- ### Import Python Compatibility Helpers Source: https://github.com/cool-rr/pysnooper/blob/master/_autodocs/README.md Imports compatibility helpers for different Python versions, including abstract base classes, type aliases, and version checks from the pysnooper.pycompat submodule. ```python from pysnooper.pycompat import ABC # Abstract base class from pysnooper.pycompat import PathLike # Path protocol from pysnooper.pycompat import string_types # String type tuple from pysnooper.pycompat import text_type # Text string type from pysnooper.pycompat import binary_type # Bytes type from pysnooper.pycompat import collections_abc # Collections abstract base from pysnooper.pycompat import timedelta_format # Format duration from pysnooper.pycompat import timedelta_parse # Parse duration from pysnooper.pycompat import PY2, PY3 # Version checks ``` -------------------------------- ### Access PySnooper Version Information Source: https://github.com/cool-rr/pysnooper/blob/master/_autodocs/types.md Demonstrates how to access and print the major, minor, and micro version components of PySnooper using the __version_info__ attribute. Supports both attribute access and indexing. ```python import pysnooper version_info = pysnooper.__version_info__ print(version_info.major) # 1 print(version_info.minor) # 2 print(version_info.micro) # 3 print(version_info[0]) # 1 (also supports indexing) ``` -------------------------------- ### Imports in utils.py Source: https://github.com/cool-rr/pysnooper/blob/master/_autodocs/module-map.md Details the imports used in the utils.py module, focusing on standard libraries and compatibility modules. ```python import abc import re import traceback import sys from .pycompat import ABC, string_types, collections_abc ``` -------------------------------- ### pysnooper.snoop() as a context manager Source: https://github.com/cool-rr/pysnooper/blob/master/_autodocs/api-reference/tracer.md The `__enter__` and `__exit__` methods implement the context manager protocol, allowing `pysnooper.snoop()` to be used with a `with` statement for tracing blocks of code. ```APIDOC ## `__enter__` and `__exit__` (Context Manager Usage) ### Description These methods enable the use of `pysnooper.snoop()` as a context manager, allowing tracing of code blocks within a `with` statement. ### Method `__enter__` and `__exit__` ### Behavior - `__enter__`: Registers the trace function and sets up tracing context. - `__exit__`: Restores the previous trace function and cleans up tracing context, writing elapsed time information. ### Example ```python import pysnooper def main(): x = 1 with pysnooper.snoop(): y = x + 2 z = y * 3 ``` ``` -------------------------------- ### Trace with Unavailable Source Code Source: https://github.com/cool-rr/pysnooper/blob/master/_autodocs/errors.md Demonstrates PySnooper's behavior when the source code of a traced module is unavailable (e.g., file deleted after import). Tracing continues by falling back to alternative methods. ```python import pysnooper # File deleted after import import temp_module @pysnooper.snoop() def func(): temp_module.some_call() # Source unavailable, but tracing continues ``` -------------------------------- ### Trace Exception with ZeroDivisionError Source: https://github.com/cool-rr/pysnooper/blob/master/_autodocs/errors.md Demonstrates how PySnooper traces a function that raises a ZeroDivisionError. The output includes exception details and indicates that the call ended due to an exception. ```python import pysnooper @pysnooper.snoop() def func(): x = 1 y = 0 z = x / y # ZeroDivisionError return z try: func() except ZeroDivisionError: pass # Output includes: # Exception:...... ZeroDivisionError: division by zero # Call ended by exception ``` -------------------------------- ### Import Tracer Class and Utilities Source: https://github.com/cool-rr/pysnooper/blob/master/_autodocs/README.md Imports the Tracer class, which is an alias for snoop, and internal utility functions from the pysnooper.tracer submodule. ```python from pysnooper.tracer import Tracer # The main class (same as snoop) from pysnooper.tracer import call_ended_by_exception # Internal utility from pysnooper.tracer import get_local_reprs # Internal utility from pysnooper.tracer import get_path_and_source_from_frame # Internal utility ``` -------------------------------- ### pysnooper.pycompat Exports Source: https://github.com/cool-rr/pysnooper/blob/master/_autodocs/module-map.md This section details the compatibility helpers and type aliases provided by the `pysnooper.pycompat` module. These are designed to ensure PySnooper works across different Python versions. ```APIDOC ## Module: `pysnooper.pycompat` **Import as:** `from pysnooper.pycompat import ...` ### Exported Classes - `ABC`: Abstract base class (Python 2/3 compatible). - `PathLike`: File system path protocol (Python 2/3 compatible). ### Exported Functions - `time_isoformat`: Format time as ISO string with microseconds. - `timedelta_format`: Format duration as ISO time string. - `timedelta_parse`: Parse ISO time string to duration. - `iscoroutinefunction`: Check if callable is async function. - `isasyncgenfunction`: Check if callable is async generator. ### Exported Type Aliases - `PY3`: Boolean indicating Python 3. - `PY2`: Boolean indicating Python 2. - `string_types`: String type tuple. - `text_type`: Text string type. - `binary_type`: Binary type. - `collections_abc`: Abstract base module. ``` -------------------------------- ### Define Abstract Base Class (ABC) Source: https://github.com/cool-rr/pysnooper/blob/master/_autodocs/api-reference/pycompat.md This snippet shows how to define an Abstract Base Class (ABC) that is compatible with both Python 2 and Python 3. It demonstrates the usage with abstract methods and subclass implementation. ```Python from pysnooper.pycompat import ABC import abc class MyBase(ABC): @abc.abstractmethod def my_method(self): pass class Concrete(MyBase): def my_method(self): return "implemented" ``` -------------------------------- ### Exploding Constructor Source: https://github.com/cool-rr/pysnooper/blob/master/_autodocs/api-reference/variables.md The Exploding class constructor takes a source expression and an optional tuple of keys/attributes/indices to exclude. It automatically determines the best expansion strategy based on the object type. ```python Exploding(source: str, exclude: tuple = ()) ``` -------------------------------- ### Programmatically apply pysnooper tracer Source: https://github.com/cool-rr/pysnooper/blob/master/_autodocs/api-reference/tracer.md Instantiate the snoop() tracer and then apply it to a function or class. This allows for more control over the tracer instance. ```python tracer = pysnooper.snoop() traced_function = tracer(traced_function) ``` -------------------------------- ### pysnooper.snoop().write Source: https://github.com/cool-rr/pysnooper/blob/master/_autodocs/api-reference/tracer.md The `write` method handles the output of traced information, prepending a configured prefix and appending a newline before writing to the designated output stream. ```APIDOC ## `write` ### Description Writes a formatted line to the configured output stream, prepending the tracer's prefix and ensuring a newline character is appended. ### Method `write(self, s: str)` ### Parameters #### Path Parameters - **s** (str) - Required - The line of text to write (without a trailing newline). ### Behavior - Adds the configured `prefix` to the beginning of the line. - Appends a newline character. - Writes to the configured output (e.g., stderr, file, stream, or callable). ### Example ```python tracer = pysnooper.snoop(prefix='DEBUG: ') tracer.write('This is a debug message') # Output: "DEBUG: This is a debug message\n" ``` ``` -------------------------------- ### Imports in pycompat.py Source: https://github.com/cool-rr/pysnooper/blob/master/_autodocs/module-map.md Specifies the imports for the pycompat.py module, primarily standard libraries for Python compatibility. ```python import abc import os import inspect import sys import datetime ``` -------------------------------- ### Normalize Output Data Source: https://github.com/cool-rr/pysnooper/blob/master/ADVANCED_USAGE.md Use `normalize=True` to remove machine-specific details like paths, timestamps, and memory addresses from the output. This is beneficial for comparing traces across different runs or environments. ```python @pysnooper.snoop(normalize=True) def normalized_function(): pass ``` -------------------------------- ### Import Top-Level API from PySnooper Source: https://github.com/cool-rr/pysnooper/blob/master/_autodocs/START_HERE.md Import core PySnooper functionalities like snoop, Attrs, Keys, Indices, Exploding, and version information. ```python from pysnooper import snoop, Attrs, Keys, Indices, Exploding from pysnooper import __version__, __version_info__ ``` -------------------------------- ### Define VersionInfo Named Tuple Source: https://github.com/cool-rr/pysnooper/blob/master/_autodocs/types.md Defines the VersionInfo named tuple structure used to represent PySnooper version information. ```python VersionInfo = collections.namedtuple('VersionInfo', ('major', 'minor', 'micro')) ``` -------------------------------- ### PySnooper Main Entry Point and Variable Watchers Source: https://github.com/cool-rr/pysnooper/blob/master/_autodocs/README.md PySnooper exports a single main decorator/context manager `pysnooper.snoop()` and four specialized variable watcher classes that can be imported from the `pysnooper` module. ```APIDOC ## PySnooper API Reference ### Main Entry Point - **`pysnooper.snoop()`** - Description: Tracer class for decorating functions or creating context managers. - Usage: Can be used as a decorator (`@pysnooper.snoop()`) or a context manager (`with pysnooper.snoop():`). ### Variable Watchers These classes can be imported from the `pysnooper` module to customize variable watching. - **`pysnooper.Attrs(source)`** - Description: Watch object attributes. - **`pysnooper.Keys(source)`** - Description: Watch dictionary keys. - **`pysnooper.Indices(source)`** - Description: Watch sequence indices. - **`pysnooper.Exploding(source)`** - Description: Auto-expanding variable watcher. ```