CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/pypi-scooby

A Python environment detective tool that reports package versions and hardware resources.

Pending
Overview
Eval results
Files

import-tracking.mddocs/

Import Tracking

Track all imports during a Python session and generate reports based on the actually imported packages. This is useful for discovering the real dependencies of a script or notebook session.

Capabilities

Import Tracking Functions

Control the import tracking system to monitor all package imports during execution.

def track_imports() -> None:
    """
    Start tracking all imported modules for the remainder of this session.
    
    This function replaces the built-in __import__ function with a tracking
    version that records all non-standard library packages that are imported.
    
    Raises:
        RuntimeError: If tracking is not supported (Python version too old)
    """

def untrack_imports() -> None:
    """
    Stop tracking imports and return to the builtin import method.
    
    This will also clear the tracked imports list, resetting it to only
    contain 'scooby'.
    
    Raises:
        RuntimeError: If tracking is not supported (Python version too old)
    """

TrackedReport Class

Generate environment reports based on the packages that were actually imported during the session.

class TrackedReport(Report):
    def __init__(
        self,
        additional: list[str | ModuleType] | None = None,
        ncol: int = 3,
        text_width: int = 80,
        sort: bool = False
    ):
        """
        Generate a report based on tracked imports.

        Parameters:
        - additional (list[str | ModuleType], optional): Additional packages to include beyond tracked imports
        - ncol (int): Number of columns in HTML table, default: 3
        - text_width (int): Text width for plain text output, default: 80
        - sort (bool): Sort packages alphabetically, default: False
        
        Raises:
            RuntimeError: If tracking is not supported or no imports have been tracked
        """

Usage Examples

Basic Import Tracking

import scooby

# Start tracking imports
scooby.track_imports()

# Import packages during your work
import numpy as np
import pandas as pd
from matplotlib import pyplot as plt
import requests

# Generate report based on tracked imports
report = scooby.TrackedReport()
print(report)

# Stop tracking and clear the list
scooby.untrack_imports()

Tracking with Additional Packages

import scooby

# Start tracking
scooby.track_imports()

# Do some work that imports packages
import json  # Standard library - won't be tracked
import numpy
from scipy import stats
import custom_local_module  # Local modules may not be tracked

# Generate report with additional packages beyond tracked ones
report = scooby.TrackedReport(
    additional=['psutil', 'mkl'],  # Add packages not imported but relevant
    sort=True
)
print(report)

# Clean up tracking
scooby.untrack_imports()

Session-based Analysis

import scooby

# Track imports for analysis session
scooby.track_imports()

# Simulate a data analysis workflow
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
from sklearn.model_selection import train_test_split
from sklearn.ensemble import RandomForestClassifier

# Some work happens here...
data = pd.read_csv('data.csv')
# ... analysis code ...

# Generate report showing what was actually used
report = scooby.TrackedReport()
print("Packages used in this analysis:")
print(report)

# Stop tracking
scooby.untrack_imports()

Jupyter Notebook Usage

# In first cell
import scooby
scooby.track_imports()

# In various cells throughout the notebook
import numpy as np
import pandas as pd
# ... other imports as needed ...

# In final cell - see what was actually imported
report = scooby.TrackedReport()
display(report)  # Shows HTML in Jupyter

# Clean up
scooby.untrack_imports()

Context Manager Pattern

import scooby

class ImportTracker:
    def __enter__(self):
        scooby.track_imports()
        return self
    
    def __exit__(self, exc_type, exc_val, exc_tb):
        scooby.untrack_imports()
    
    def report(self):
        return scooby.TrackedReport()

# Use with context manager
with ImportTracker() as tracker:
    import numpy
    import pandas
    # ... do work ...
    
    # Generate report within the tracking context
    report = tracker.report()
    print(report)
# Tracking automatically stopped

Important Notes

Tracking Limitations

  • Python Version: Import tracking requires modern Python versions. Older versions will raise RuntimeError.
  • Standard Library: Standard library modules are automatically excluded from tracking.
  • Module Filtering: Some modules are excluded by default (e.g., internal modules starting with _, certain system modules).
  • Import Timing: Only tracks imports that happen after track_imports() is called.

Best Practices

import scooby

# Always use try/finally or context managers to ensure cleanup
scooby.track_imports()
try:
    # ... your code with imports ...
    report = scooby.TrackedReport()
    print(report)
finally:
    scooby.untrack_imports()

Error Handling

import scooby

try:
    scooby.track_imports()
except RuntimeError as e:
    print(f"Tracking not supported: {e}")
    # Fall back to regular Report
    report = scooby.Report()
else:
    # ... do tracked work ...
    try:
        report = scooby.TrackedReport()
    except RuntimeError as e:
        print(f"No tracked imports: {e}")
        report = scooby.Report()
    finally:
        scooby.untrack_imports()

print(report)

Install with Tessl CLI

npx tessl i tessl/pypi-scooby

docs

environment-reporting.md

import-tracking.md

index.md

utilities.md

tile.json