Skip to content

Results

All operations return Result objects instead of raising exceptions.

Result

The base result class for successful operations.

@dataclass
class Result:
    success: bool
    message: str
    files_changed: list[Path]
    data: Any = None

Properties

Property Type Description
success bool Whether the operation succeeded
message str Human-readable description
files_changed list[Path] Files that were modified
data Any Optional payload for queries

Methods

__bool__

Results are truthy when successful:

result = cls.rename("NewName")
if result:
    print("Success!")

is_error

Check if this is an error result:

if result.is_error():
    print(f"Failed: {result.message}")

Example

result = cls.rename("NewName")

print(result.success)        # True
print(result.message)        # "Renamed User to NewName"
print(result.files_changed)  # [Path("models.py")]

ErrorResult

Returned when an operation fails.

@dataclass
class ErrorResult(Result):
    success: bool = False  # Always False
    exception: Exception | None = None
    operation: str = ""
    target_repr: str = ""

Properties

Property Type Description
success bool Always False
message str Error description
exception Exception \| None Original exception if any
operation str Name of the failed operation
target_repr str String representation of the target

Methods

raise_if_error

Convert the result to an exception:

result = cls.rename("NewName")
if result.is_error():
    result.raise_if_error()  # Raises RuntimeError or original exception

Example

result = cls.rename("NewName")

if result.is_error():
    print(result.message)       # "Class 'User' not found"
    print(result.operation)     # "rename"
    print(result.target_repr)   # "ClassTarget(name='User')"

    if result.exception:
        print(type(result.exception))  # Original exception type

BatchResult

Returned when operating on multiple targets.

@dataclass
class BatchResult:
    results: list[Result]

Properties

Property Type Description
results list[Result] All individual results
success bool True if ALL succeeded
partial_success bool True if ANY succeeded
all_failed bool True if ALL failed
succeeded list[Result] Successful results
failed list[Result] Failed results
files_changed list[Path] All modified files

Methods

__bool__

Truthy only when ALL operations succeeded:

results = classes.add_decorator("@slow")
if results:
    print("All succeeded!")

__len__

Number of operations:

print(f"Processed {len(results)} targets")

__iter__

Iterate over all results:

for result in results:
    print(result.message)

Example

results = rj.find_classes("^Test").add_decorator("@slow")

# Check status
if results.success:
    print(f"Added to all {len(results)} classes")
elif results.partial_success:
    print(f"Succeeded: {len(results.succeeded)}")
    print(f"Failed: {len(results.failed)}")
else:
    print("All failed")

# Handle failures
for r in results.failed:
    print(f"Failed: {r.message}")

# Get modified files
print(f"Files changed: {results.files_changed}")

Common Patterns

Simple Success Check

result = cls.rename("NewName")
if result:
    print("Done!")

Detailed Error Handling

result = cls.rename("NewName")
if result.is_error():
    print(f"Operation: {result.operation}")
    print(f"Target: {result.target_repr}")
    print(f"Error: {result.message}")

Convert to Exception

result = cls.rename("NewName")
if not result:
    result.raise_if_error()

Batch with Partial Failure Handling

results = classes.add_decorator("@slow")

if not results.success:
    print("Some operations failed:")
    for r in results.failed:
        print(f"  - {r.message}")

Collect All Errors

errors = []
for cls in classes:
    result = cls.add_decorator("@slow")
    if not result:
        errors.append(result)

if errors:
    for e in errors:
        print(f"{e.target_repr}: {e.message}")

results

Result types for all operations.

This module defines the core result classes: - Result - Base result for all operations - ErrorResult - Result for failed operations - BatchResult - Aggregate result for batch operations

Result(success, message, files_changed=list(), data=None, diff=None, diffs=dict()) dataclass

Base result for all operations.

Operations never raise exceptions. Instead, they return Result objects that indicate success or failure.

Attributes:

Name Type Description
success bool

Whether the operation succeeded

message str

Human-readable description of what happened

files_changed list[Path]

List of files that were modified

data Any

Optional payload for operations that return data

diff str | None

Combined unified diff of all changes (if any)

diffs dict[Path, str]

Per-file diffs mapping path to diff string

get_diff(path=None)

Get diff for a specific file or combined diff.

Parameters

path : Path | None If provided, returns diff for that specific file. If None, returns the combined diff.

Returns

str | None The diff string, or None if no diff available.

is_error()

Check if this result represents an error.

ErrorResult(success, message, files_changed=list(), data=None, diff=None, diffs=dict(), exception=None, operation='', target_repr='') dataclass

Bases: Result

Result for failed operations - never raises automatically.

Attributes:

Name Type Description
exception Exception | None

The original exception, if any

operation str

Name of the attempted operation

target_repr str

String representation of the target

raise_if_error()

Explicitly re-raise the exception if the programmer wants to.

BatchResult(results=list()) dataclass

Aggregate result for operations applied to multiple targets.

Used by TargetList when performing batch operations.

all_failed property

True if all operations failed.

diff property

Combined diff from all results.

diffs property

Merged diffs from all results.

failed property

Results that failed.

files_changed property

All files changed across all operations.

partial_success property

True if at least one operation succeeded.

succeeded property

Results that succeeded.

success property

True if all operations succeeded.

get_diff(path=None)

Get diff for a specific file or combined diff.

Parameters

path : Path | None If provided, returns diff for that specific file. If None, returns the combined diff.

Returns

str | None The diff string, or None if no diff available.