ubelt.util_mixins module¶
This module defines the NiceRepr mixin class, which defines a __repr__ and __str__ method that only depend on a custom __nice__ method, which you must define. This means you only have to overload one function instead of two. Furthermore, if the object defines a __len__ method, then the __nice__ method defaults to something sensible, otherwise it is treated as abstract and raises NotImplementedError.
-
class
ubelt.util_mixins.
NiceRepr
[source]¶ Bases:
object
Defines __str__ and __repr__ in terms of __nice__ function Classes that inherit from NiceRepr must define __nice__
Example
>>> import ubelt as ub >>> class Foo(ub.NiceRepr): ... def __nice__(self): ... return 'info' >>> foo = Foo() >>> assert str(foo) == '<Foo(info)>' >>> assert repr(foo).startswith('<Foo(info) at ')
Example
>>> import ubelt as ub >>> class Bar(ub.NiceRepr): ... pass >>> bar = Bar() >>> import pytest >>> with pytest.warns(None) as record: >>> assert 'object at' in str(bar) >>> assert 'object at' in repr(bar)
Example
>>> import ubelt as ub >>> class Baz(ub.NiceRepr): ... def __len__(self): ... return 5 >>> baz = Baz() >>> assert str(baz) == '<Baz(5)>'