cheap_repr
==========
[![Tests](https://github.com/alexmojaki/cheap_repr/actions/workflows/pytest.yml/badge.svg)](https://github.com/alexmojaki/cheap_repr/actions/workflows/pytest.yml) [![Coverage Status](https://coveralls.io/repos/github/alexmojaki/cheap_repr/badge.svg?branch=master)](https://coveralls.io/github/alexmojaki/cheap_repr?branch=master) [![Supports Python versions 3.8+](https://img.shields.io/pypi/pyversions/cheap_repr.svg)](https://pypi.python.org/pypi/cheap_repr)
This library provides short, fast, configurable string representations, and an easy API for registering your own. It's an improvement of the standard library module `reprlib` (`repr` in Python 2).
Just use the `cheap_repr` function instead of `repr`:
```python
>>> from cheap_repr import cheap_repr
>>> cheap_repr(list(range(100)))
'[0, 1, 2, ..., 97, 98, 99]'
```
`cheap_repr` knows how to handle many different types out of the box. You can register a function for any type, and pull requests to make these part of the library are welcome. If it doesn't know how to handle a particular type, the default `repr()` is used, possibly truncated:
```python
>>> class MyClass(object):
... def __init__(self, items):
... self.items = items
...
... def __repr__(self):
... return 'MyClass(%r)' % self.items
...
>>> c = MyClass(list(range(20)))
>>> c
MyClass([0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19])
>>> cheap_repr(c)
'MyClass([0, 1, 2, 3, 4, 5, 6... 13, 14, 15, 16, 17, 18, 19])'
```
## Suppression of long reprs
`cheap_repr` is meant to prevent slow, expensive computations of string representations. So if it finds that a particular class can potentially produce very long representations, the class will be *suppressed*, meaning that in future the `__repr__` won't be calculated at all:
```python
>>> cheap_repr(MyClass(list(range(1000))))
'MyClass([0, 1, 2, 3, 4, 5, 6...94, 995, 996, 997, 998, 999])'
.../cheap_repr/__init__.py:80: ReprSuppressedWarning: MyClass.__repr__ is too long and has been suppressed. Register a repr for the class to avoid this warning and see an informative repr again, or increase cheap_repr.suppression_threshold
>>> cheap_repr(MyClass(list(range(1000))))
'<MyClass instance at 0x1034de7f0 (repr suppressed)>'
```
`cheap_repr.suppression_threshold` refers to the attribute on the function itself, not the module. By default it's 300, meaning that a `repr` longer than 300 characters will trigger the suppression.
## Registering your own repr function
For example:
```python
>>> from cheap_repr import register_repr
>>> @register_repr(MyClass)
... def repr_my_class(x, helper):
... return helper.repr_iterable(x.items, 'MyClass([', '])')
...
>>> cheap_repr(MyClass(list(range(1000))))
'MyClass([0, 1, 2, 3, 4, 5, ...])'
```
In general, write a function that takes two arguments `(x, helper)` and decorate it with `register_repr(cls)`. Then `cheap_repr(x)` where `isinstance(x, cls)` will dispatch to that function, unless there is also a registered function for a subclass which `x` is also an instance of. More precisely, the function corresponding to the first class in the MRO will be used. This is in contrast to the standard library module `reprlib`, which cannot handle subclasses that aren't explicitly 'registered', or classes with the same name.
The `helper` argument is an object with a couple of useful attributes and methods:
- `repr_iterable(iterable, left, right, end=False, length=None)` produces a comma-separated representation of `iterable`, automatically handling nesting and iterables that are too long, surrounded by `left` and `right`. The number of items is limited to `func.maxparts` (see the configuration section below).
Set `end=True` to include items from both the beginning and end, possibly leaving out items
in the middle. Only do this if `iterable` supports efficient slicing at the end, e.g. `iterable[-3:]`.
Provide the `length` parameter if `len(iterable)` doesn't work. Usually this is not needed.
- `truncate(string)` returns a version of `string` at most `func.maxparts` characters long, with the middle replaced by `...` if necessary.
- `level` indicates how much nesting is still allowed in the result. If it's 0, return something minimal such as `[...]` to indicate that the original object is too deep to show all its contents. Otherwise, if you use `cheap_repr` on several items inside `x`, pass `helper.level - 1` as the second argument, e.g. `', '.join(cheap_repr(item, helper.level - 1) for item in x)`.
## Exceptions in repr functions
If an exception occurs in `cheap_repr`, whether from a registered repr function or the usual `__repr__`, the exception will be caught and the cheap repr of the class will be suppressed:
```python
>>> @register_repr(MyClass)
... def repr_my_class(x, helper):
... return 'MyClass([%r, ...])' % x.items[0]
...
>>> cheap_repr(MyClass([]))
'<MyClass instance at 0x10f44ec50 (exception in repr)>'
.../cheap_repr/__init__.py:123: ReprSuppressedWarning: Exception 'IndexError: list index out of range' in repr_my_class for object of type MyClass. The repr has been suppressed for this type.
...
>>> cheap_repr(MyClass([1, 2, 3]))
'<MyClass instance at 0x10f44ecc0 (repr suppressed)>'
```
If you would prefer exceptions to bubble up normally, you can:
1. Set `cheap_repr.raise_exceptions = True` to globally make all exceptions bubble up.
2. To bubble exceptions from the `__repr__` of a class, call `raise_exceptions_from_default_repr()`.
3. Set `repr_my_class.raise_exceptions = True` (substituting your own registered repr function) to make exceptions bubble from that function. The way to find the relevant function is in the next section.
## Configuration:
### Configuration for specific functions
To configure a specific function, you set attributes on that function. To find the function corresponding to a class, use `find_repr_function`:
```python
>>> from cheap_repr import find_repr_function
>>> find_repr_function(MyClass)
<function repr_my_class at 0x10f43d8c8>
```
For most functions, there are two attributes available to configure, but contributors and library writers are encouraged to add arbitrary attributes for their own functions. The first attribute is `raise_exceptions`, described in the previous section.
### maxparts
The other configurable attribute is `maxparts`. All registered repr functions have this attribute. It determines the maximum number of 'parts' (e.g. list elements or string characters, the meaning depends on the function) from the input that the output can display without truncation. The default value is 6. The decorator `@maxparts(n)` conveniently sets the attribute to make writing your own registered functions nicer. For example:
```python
>>> from cheap_repr import maxparts
>>> @register_repr(MyClass)
... @maxparts(2)
... def repr_my_class(x, helper):
... return helper.repr_iterable(x.items, 'MyClass([', '])')
...
>>> cheap_repr(MyClass([1, 2, 3, 4]))
'MyClass([1, 2, ...])'
>>> find_repr_function(MyClass).maxparts = 3
>>> cheap_repr(MyClass([1, 2, 3, 4]))
'MyClass([1, 2, 3, ...])'
```
### pandas
The functions for `DataFrame`s and `Series` from the `pandas` library don't use `maxparts`.
For the `DataFrame` function there's `max_rows` and `max_cols`. For the `Series` function there's just `max_rows`.
### level and max_level
`cheap_repr` takes an optional argument `level` which controls the display of nested objects. Typically this decreases through recursive calls, and when it's 0, the contents of the object aren't shown. See 'Registering your own repr function' for more details. This means you can change the amount of nested data in the output of `cheap_repr` by changing the `level` argument. The default value is `cheap_repr.max_level`, which is initially 3. This means that changing `cheap_repr.max_level` will effectively change the `level` argument whenever it isn't explicitly specified.
### Global configuration
These things that can be configured globally:
1. `cheap_repr.suppression_threshold`, discussed in the 'Suppression of long reprs' section.
2. The handling of exceptions, discussed in the 'Exceptions in repr functions' section, which can be changed by setting `cheap_repr.raise_exceptions = True` or calling `raise_exceptions_from_default_repr()`.
3. `cheap_repr.max_level`, discussed above.
## Other miscellaneous functions
`basic_repr(x)` returns a string that looks like the default `object.__repr__`. This is handy if you don't want to write your own repr function to register. Simply register this function instead, e.g.
```python
>>> from cheap_repr import basic_repr
>>> register_repr(MyClass)(basic_repr)
>>> cheap_repr(MyClass([1, 2, 3, 4]))
'<MyClass instance at 0x10f39dda0>'
```
`normal_repr(x)` returns `repr(x)` - register it with a class to indicate that its own `__repr__` method is already fine. This prevents it from being supressed when its output is a bit long.
`try_register_repr` is handy when you want to register a repr function for a class that may not exist, e.g. if the class is in a third party package that may not be installed. See the docstring for more details.
Raw data
{
"_id": null,
"home_page": "https://github.com/alexmojaki/cheap_repr",
"name": "cheap-repr",
"maintainer": null,
"docs_url": null,
"requires_python": null,
"maintainer_email": null,
"keywords": null,
"author": "Alex Hall",
"author_email": "alex.mojaki@gmail.com",
"download_url": "https://files.pythonhosted.org/packages/b1/30/f0e9d5bfe80b8287ea8a9263eb3c71c5fdf44b6f7a781a7c96f83172ccad/cheap_repr-0.5.2.tar.gz",
"platform": null,
"description": "cheap_repr\n==========\n\n[![Tests](https://github.com/alexmojaki/cheap_repr/actions/workflows/pytest.yml/badge.svg)](https://github.com/alexmojaki/cheap_repr/actions/workflows/pytest.yml) [![Coverage Status](https://coveralls.io/repos/github/alexmojaki/cheap_repr/badge.svg?branch=master)](https://coveralls.io/github/alexmojaki/cheap_repr?branch=master) [![Supports Python versions 3.8+](https://img.shields.io/pypi/pyversions/cheap_repr.svg)](https://pypi.python.org/pypi/cheap_repr)\n\nThis library provides short, fast, configurable string representations, and an easy API for registering your own. It's an improvement of the standard library module `reprlib` (`repr` in Python 2).\n\nJust use the `cheap_repr` function instead of `repr`:\n\n```python\n>>> from cheap_repr import cheap_repr\n>>> cheap_repr(list(range(100)))\n'[0, 1, 2, ..., 97, 98, 99]'\n```\n\n`cheap_repr` knows how to handle many different types out of the box. You can register a function for any type, and pull requests to make these part of the library are welcome. If it doesn't know how to handle a particular type, the default `repr()` is used, possibly truncated:\n\n```python\n>>> class MyClass(object):\n... def __init__(self, items):\n... self.items = items\n...\n... def __repr__(self):\n... return 'MyClass(%r)' % self.items\n...\n>>> c = MyClass(list(range(20)))\n>>> c\nMyClass([0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19])\n>>> cheap_repr(c)\n'MyClass([0, 1, 2, 3, 4, 5, 6... 13, 14, 15, 16, 17, 18, 19])'\n```\n\n## Suppression of long reprs\n\n`cheap_repr` is meant to prevent slow, expensive computations of string representations. So if it finds that a particular class can potentially produce very long representations, the class will be *suppressed*, meaning that in future the `__repr__` won't be calculated at all:\n\n```python\n>>> cheap_repr(MyClass(list(range(1000))))\n'MyClass([0, 1, 2, 3, 4, 5, 6...94, 995, 996, 997, 998, 999])'\n.../cheap_repr/__init__.py:80: ReprSuppressedWarning: MyClass.__repr__ is too long and has been suppressed. Register a repr for the class to avoid this warning and see an informative repr again, or increase cheap_repr.suppression_threshold\n>>> cheap_repr(MyClass(list(range(1000))))\n'<MyClass instance at 0x1034de7f0 (repr suppressed)>'\n```\n\n`cheap_repr.suppression_threshold` refers to the attribute on the function itself, not the module. By default it's 300, meaning that a `repr` longer than 300 characters will trigger the suppression.\n\n## Registering your own repr function\n\nFor example:\n\n```python\n>>> from cheap_repr import register_repr\n>>> @register_repr(MyClass)\n... def repr_my_class(x, helper):\n... return helper.repr_iterable(x.items, 'MyClass([', '])')\n...\n>>> cheap_repr(MyClass(list(range(1000))))\n'MyClass([0, 1, 2, 3, 4, 5, ...])'\n```\n\nIn general, write a function that takes two arguments `(x, helper)` and decorate it with `register_repr(cls)`. Then `cheap_repr(x)` where `isinstance(x, cls)` will dispatch to that function, unless there is also a registered function for a subclass which `x` is also an instance of. More precisely, the function corresponding to the first class in the MRO will be used. This is in contrast to the standard library module `reprlib`, which cannot handle subclasses that aren't explicitly 'registered', or classes with the same name.\n\nThe `helper` argument is an object with a couple of useful attributes and methods:\n\n- `repr_iterable(iterable, left, right, end=False, length=None)` produces a comma-separated representation of `iterable`, automatically handling nesting and iterables that are too long, surrounded by `left` and `right`. The number of items is limited to `func.maxparts` (see the configuration section below).\n\n Set `end=True` to include items from both the beginning and end, possibly leaving out items\n in the middle. Only do this if `iterable` supports efficient slicing at the end, e.g. `iterable[-3:]`.\n\n Provide the `length` parameter if `len(iterable)` doesn't work. Usually this is not needed.\n- `truncate(string)` returns a version of `string` at most `func.maxparts` characters long, with the middle replaced by `...` if necessary.\n- `level` indicates how much nesting is still allowed in the result. If it's 0, return something minimal such as `[...]` to indicate that the original object is too deep to show all its contents. Otherwise, if you use `cheap_repr` on several items inside `x`, pass `helper.level - 1` as the second argument, e.g. `', '.join(cheap_repr(item, helper.level - 1) for item in x)`.\n\n## Exceptions in repr functions\n\nIf an exception occurs in `cheap_repr`, whether from a registered repr function or the usual `__repr__`, the exception will be caught and the cheap repr of the class will be suppressed:\n\n```python\n>>> @register_repr(MyClass)\n... def repr_my_class(x, helper):\n... return 'MyClass([%r, ...])' % x.items[0]\n...\n>>> cheap_repr(MyClass([]))\n'<MyClass instance at 0x10f44ec50 (exception in repr)>'\n.../cheap_repr/__init__.py:123: ReprSuppressedWarning: Exception 'IndexError: list index out of range' in repr_my_class for object of type MyClass. The repr has been suppressed for this type.\n...\n>>> cheap_repr(MyClass([1, 2, 3]))\n'<MyClass instance at 0x10f44ecc0 (repr suppressed)>'\n```\n\nIf you would prefer exceptions to bubble up normally, you can:\n\n1. Set `cheap_repr.raise_exceptions = True` to globally make all exceptions bubble up.\n2. To bubble exceptions from the `__repr__` of a class, call `raise_exceptions_from_default_repr()`.\n3. Set `repr_my_class.raise_exceptions = True` (substituting your own registered repr function) to make exceptions bubble from that function. The way to find the relevant function is in the next section.\n\n## Configuration:\n\n### Configuration for specific functions\n\nTo configure a specific function, you set attributes on that function. To find the function corresponding to a class, use `find_repr_function`:\n\n```python\n>>> from cheap_repr import find_repr_function\n>>> find_repr_function(MyClass)\n<function repr_my_class at 0x10f43d8c8>\n```\n\nFor most functions, there are two attributes available to configure, but contributors and library writers are encouraged to add arbitrary attributes for their own functions. The first attribute is `raise_exceptions`, described in the previous section.\n\n### maxparts\n\nThe other configurable attribute is `maxparts`. All registered repr functions have this attribute. It determines the maximum number of 'parts' (e.g. list elements or string characters, the meaning depends on the function) from the input that the output can display without truncation. The default value is 6. The decorator `@maxparts(n)` conveniently sets the attribute to make writing your own registered functions nicer. For example:\n\n```python\n>>> from cheap_repr import maxparts\n>>> @register_repr(MyClass)\n... @maxparts(2)\n... def repr_my_class(x, helper):\n... return helper.repr_iterable(x.items, 'MyClass([', '])')\n...\n>>> cheap_repr(MyClass([1, 2, 3, 4]))\n'MyClass([1, 2, ...])'\n>>> find_repr_function(MyClass).maxparts = 3\n>>> cheap_repr(MyClass([1, 2, 3, 4]))\n'MyClass([1, 2, 3, ...])'\n```\n\n### pandas\n\nThe functions for `DataFrame`s and `Series` from the `pandas` library don't use `maxparts`.\nFor the `DataFrame` function there's `max_rows` and `max_cols`. For the `Series` function there's just `max_rows`.\n\n### level and max_level\n\n`cheap_repr` takes an optional argument `level` which controls the display of nested objects. Typically this decreases through recursive calls, and when it's 0, the contents of the object aren't shown. See 'Registering your own repr function' for more details. This means you can change the amount of nested data in the output of `cheap_repr` by changing the `level` argument. The default value is `cheap_repr.max_level`, which is initially 3. This means that changing `cheap_repr.max_level` will effectively change the `level` argument whenever it isn't explicitly specified.\n\n### Global configuration\n\nThese things that can be configured globally:\n\n1. `cheap_repr.suppression_threshold`, discussed in the 'Suppression of long reprs' section.\n2. The handling of exceptions, discussed in the 'Exceptions in repr functions' section, which can be changed by setting `cheap_repr.raise_exceptions = True` or calling `raise_exceptions_from_default_repr()`.\n3. `cheap_repr.max_level`, discussed above.\n\n## Other miscellaneous functions\n\n`basic_repr(x)` returns a string that looks like the default `object.__repr__`. This is handy if you don't want to write your own repr function to register. Simply register this function instead, e.g.\n\n```python\n>>> from cheap_repr import basic_repr\n>>> register_repr(MyClass)(basic_repr)\n>>> cheap_repr(MyClass([1, 2, 3, 4]))\n'<MyClass instance at 0x10f39dda0>'\n```\n\n`normal_repr(x)` returns `repr(x)` - register it with a class to indicate that its own `__repr__` method is already fine. This prevents it from being supressed when its output is a bit long.\n\n`try_register_repr` is handy when you want to register a repr function for a class that may not exist, e.g. if the class is in a third party package that may not be installed. See the docstring for more details.\n",
"bugtrack_url": null,
"license": "MIT",
"summary": "Better version of repr/reprlib for short, cheap string representations.",
"version": "0.5.2",
"project_urls": {
"Homepage": "https://github.com/alexmojaki/cheap_repr"
},
"split_keywords": [],
"urls": [
{
"comment_text": "",
"digests": {
"blake2b_256": "ec52fec0262af470a157a557e46be1d52ecdaf1695cefd80bb62bb6a07cc4ea9",
"md5": "f0266af97a5c83022e03d89fa4bf6561",
"sha256": "537ec1991bfee885c13c6d473afd110a408e039cde26882e95bf92761556ab6e"
},
"downloads": -1,
"filename": "cheap_repr-0.5.2-py2.py3-none-any.whl",
"has_sig": false,
"md5_digest": "f0266af97a5c83022e03d89fa4bf6561",
"packagetype": "bdist_wheel",
"python_version": "py2.py3",
"requires_python": null,
"size": 12228,
"upload_time": "2024-08-10T14:08:05",
"upload_time_iso_8601": "2024-08-10T14:08:05.965981Z",
"url": "https://files.pythonhosted.org/packages/ec/52/fec0262af470a157a557e46be1d52ecdaf1695cefd80bb62bb6a07cc4ea9/cheap_repr-0.5.2-py2.py3-none-any.whl",
"yanked": false,
"yanked_reason": null
},
{
"comment_text": "",
"digests": {
"blake2b_256": "b130f0e9d5bfe80b8287ea8a9263eb3c71c5fdf44b6f7a781a7c96f83172ccad",
"md5": "8004ea6c36f2aab35b0ad55b81db5f3a",
"sha256": "001a5cf8adb0305c7ad3152c5f776040ac2a559d97f85770cebcb28c6ca5a30f"
},
"downloads": -1,
"filename": "cheap_repr-0.5.2.tar.gz",
"has_sig": false,
"md5_digest": "8004ea6c36f2aab35b0ad55b81db5f3a",
"packagetype": "sdist",
"python_version": "source",
"requires_python": null,
"size": 20232,
"upload_time": "2024-08-10T14:08:07",
"upload_time_iso_8601": "2024-08-10T14:08:07.314843Z",
"url": "https://files.pythonhosted.org/packages/b1/30/f0e9d5bfe80b8287ea8a9263eb3c71c5fdf44b6f7a781a7c96f83172ccad/cheap_repr-0.5.2.tar.gz",
"yanked": false,
"yanked_reason": null
}
],
"upload_time": "2024-08-10 14:08:07",
"github": true,
"gitlab": false,
"bitbucket": false,
"codeberg": false,
"github_user": "alexmojaki",
"github_project": "cheap_repr",
"travis_ci": false,
"coveralls": false,
"github_actions": true,
"tox": true,
"lcname": "cheap-repr"
}