Skip to content

Commit

Permalink
Better get_name
Browse files Browse the repository at this point in the history
  • Loading branch information
acu192 committed Jan 18, 2025
1 parent cc38166 commit c4e2fc9
Show file tree
Hide file tree
Showing 2 changed files with 20 additions and 2 deletions.
18 changes: 16 additions & 2 deletions src/lasagna/util.py
Original file line number Diff line number Diff line change
Expand Up @@ -172,9 +172,23 @@ def exponential_backoff_retry_delays(
return [min(d, max_delay) for d in delay_list]


def _has_own_str_method(obj: Any) -> bool:
if not hasattr(obj, '__class__'):
return False
class_str = obj.__class__.__str__
superclass_str = obj.__class__.__base__.__str__
return class_str is not superclass_str


def get_name(obj: Any) -> str:
name = str(obj.__name__) if hasattr(obj, '__name__') else str(obj)
return name
if hasattr(obj, '__name__'):
return str(obj.__name__)
elif _has_own_str_method(obj):
return str(obj)
elif hasattr(obj, '__class__'):
return get_name(obj.__class__)
else:
return str(obj)


class HashAlgorithm(Protocol):
Expand Down
4 changes: 4 additions & 0 deletions tests/test_util.py
Original file line number Diff line number Diff line change
Expand Up @@ -436,10 +436,14 @@ class class_with_str_method:
def __str__(self) -> str:
return 'Hi!'

class class_with_no_str_method:
pass

def test_get_name():
assert get_name(regular_function) == 'regular_function'
assert get_name(async_regular_function) == 'async_regular_function'
assert get_name(class_with_str_method()) == 'Hi!'
assert get_name(class_with_no_str_method()) == 'class_with_no_str_method'


def test_recursive_hash():
Expand Down

0 comments on commit c4e2fc9

Please sign in to comment.