Skip to content

Commit

Permalink
fix critical recursion problem with safe_repr
Browse files Browse the repository at this point in the history
  • Loading branch information
th3w1zard1 committed Mar 24, 2024
1 parent 951c341 commit df1c9ba
Show file tree
Hide file tree
Showing 2 changed files with 13 additions and 5 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -329,9 +329,6 @@ def __init__(
self._field_type: GFFFieldType = field_type
self._value: Any = value

def __repr__(self):
return safe_repr(self)

def field_type(
self,
) -> GFFFieldType:
Expand Down
15 changes: 13 additions & 2 deletions Libraries/Utility/src/utility/error_handling.py
Original file line number Diff line number Diff line change
Expand Up @@ -107,7 +107,7 @@ def is_builtin_class_instance(obj: Any) -> bool:
_currently_processing: ContextVar[list] = ContextVar("_currently_processing", default=[])


def safe_repr(obj: Any, max_length: int = 200, indent_level: int = 0) -> str:
def safe_repr(obj: Any, max_length: int = 200, indent_level: int = 0, max_depth: int = 3, _depth: int = 0) -> str:
"""Safely generate a repr string for objects without a custom __repr__, with line wrapping and indentation."""
if is_builtin_class_instance(obj):
try:
Expand All @@ -132,6 +132,17 @@ def safe_repr(obj: Any, max_length: int = 200, indent_level: int = 0) -> str:
base_indent = indent * frame["indent_level"]
return f"{frame['representation']}...\n{base_indent})"

if _depth > max_depth:
try:
obj_repr = repr(obj)
# Truncate if necessary
if len(obj_repr) > max_length:
return f"{obj_repr[:max_length]}..."
except Exception: # noqa: BLE001
return object.__repr__(obj)
else:
return obj_repr

try:
# Initialize the representation for this object and add it to the stack
base_indent = indent * indent_level
Expand All @@ -154,7 +165,7 @@ def safe_repr(obj: Any, max_length: int = 200, indent_level: int = 0) -> str:
attr_value = getattr(obj, attr_name)
if not attr_name.startswith("__") and not callable(attr_value):
try:
this_repr = safe_repr(attr_value, max_length, indent_level + 1)
this_repr = safe_repr(attr_value, max_length, indent_level + 1, _depth=_depth+1)
# Concatenate attribute name and its representation with appropriate indentation
attr_repr = f"{attr_name}={this_repr}"
# Check if current attribute representation exceeds the max length
Expand Down

0 comments on commit df1c9ba

Please sign in to comment.