Skip to content

Instantly share code, notes, and snippets.

@mikek
Created October 22, 2017 15:48
Show Gist options
  • Save mikek/68ad4d5c79ba60f6ddffeb600884881d to your computer and use it in GitHub Desktop.
Save mikek/68ad4d5c79ba60f6ddffeb600884881d to your computer and use it in GitHub Desktop.
Tenacity repr() KeyError
diff --git a/tenacity/__init__.py b/tenacity/__init__.py
index ef516e7..61291cc 100644
--- a/tenacity/__init__.py
+++ b/tenacity/__init__.py
@@ -125,13 +125,19 @@ class BaseRetrying(object):
self._local = threading.local()
def __repr__(self):
- attrs = dict(
- _utils.visible_attrs(self, attrs={'me': id(self)}),
- __class__=self.__class__.__name__,
- )
- return ("<%(__class__)s object at 0x%(me)x (stop=%(stop)s, "
- "wait=%(wait)s, sleep=%(sleep)s, retry=%(retry)s, "
- "before=%(before)s, after=%(after)s)>") % (attrs)
+ possible_attrs = ('stop', 'wait', 'sleep', 'retry', 'before', 'after')
+ visible_attrs = _utils.visible_attrs(self)
+ attrs_repr_list = []
+ for attr in possible_attrs:
+ value = visible_attrs.get(attr)
+ if value is None:
+ continue
+ attrs_repr_list.append('%s=%s' % (attr, value))
+ context = dict(
+ attrs=', '.join(attrs_repr_list),
+ me=id(self),
+ __class__=self.__class__.__name__)
+ return "<%(__class__)s object at 0x%(me)x (%(attrs)s)>" % context
@property
def statistics(self):
diff --git a/tenacity/tests/test_tenacity.py b/tenacity/tests/test_tenacity.py
index b14cb6e..786d729 100644
--- a/tenacity/tests/test_tenacity.py
+++ b/tenacity/tests/test_tenacity.py
@@ -20,6 +20,7 @@ import unittest
import tenacity
from tenacity import retry
+from tenacity import BaseRetrying
from tenacity import RetryError
from tenacity import Retrying
@@ -757,5 +758,14 @@ class TestStatistics(unittest.TestCase):
self.assertEqual(2, _foobar.retry.statistics['attempt_number'])
+class TestMisc(unittest.TestCase):
+ def test_repr(self):
+ class CustomRetrying(BaseRetrying):
+ pass
+
+ repr(Retrying())
+ repr(CustomRetrying())
+
+
if __name__ == '__main__':
unittest.main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment