jk_prettyprintobj


Namejk_prettyprintobj JSON
Version 0.2024.2.18 PyPI version JSON
download
home_pageNone
SummaryThis python module provides a mixin for creating pretty debugging output for objects. This is especially useful for semi-complex data structures.
upload_time2024-02-19 07:15:09
maintainerNone
docs_urlNone
authorNone
requires_python>=3.8
licenseNone
keywords pretty-print debugging debug
VCS
bugtrack_url
requirements No requirements were recorded.
Travis-CI No Travis.
coveralls test coverage No coveralls.
            jk_prettyprintobj
========

Introduction
------------

This python module provides a mixin for dumping objects. This is ment for debugging purposes: Sometimes it is very convenient to have a way of writing all data of an object to STDOUT in a human readable way. This module assists in such implementations.

Information about this module can be found here:

* [github.org](https://github.com/jkpubsrc/python-module-jk-prettyprintobj)
* [pypi.python.org](https://pypi.python.org/pypi/jk_prettyprintobj)

How to use this module
----------------------

### Import the module

In order to use this module you need to import it first. So add this line to the head of your python source code file:

```python
import jk_prettyprintobj
```

### Use the provided mixin

To make use of the features of this module you must add a mixin to your class. Example:

```python
class ExampleClass(jk_prettyprintobj.DumpMixin):

	def __init__(self, ...):
		...

	...
```

If you derive your class from a base class just add the mixin to your list of base classes. The order does not matter in this case. Here is an example how to do this:

```python
class MyFancyException(Exception, jk_prettyprintobj.DumpMixin):

	def __init__(self, msg:str):
		super().__init__(msg)

	...
```

In this example we use `Exception` as a base class to keep this example simple. It just demonstrates the technique. You can use any base class for inheritance, it is just necessary that you somewhere in the list of base classes add `jk_prettyprintobj.DumpMixin`. This does not yet make use of the features provided by `jk_prettyprintobj` but prepares its use.

This mixin adds a regular method named `dump()` to the class. For all things to work it is important that you have no other method named `dump()` in your class that might conflict with the implementation provided by `DumpMixin`. This method can be called later, but some additional implementation steps need to be taken first. (See next section!)

### Implement a helper method

To actually enable the class to produce output we must implement one of the helper methods. These are:

| **Method name**									| **Description**								|
| ---												| ---											|
| `_dump(ctx:jk_prettyprintobj.DumpCtx) -> None`	| Implement dumping data on your own			|
| `_dumpVarNames() -> typing.List[str]`				| Provide the names of the variable to output	|

More to these options in the next sections.

### Helper method _dumpVarNames()

If you implement the method `_dumpVarNames() -> typing.List[str]` your method needs to return a list of variable names that should be dumped to STDOUT.

Here is an example of a simple but working implementation.

```python
class Matrix(jk_prettyprintobj.DumpMixin):

	def __init__(self, m):
		self.m = m
		self.nRows = len(m)
		self.nColumns = len(m[0])

	def _dumpVarNames(self) -> list:
		return [
			"nRows",
			"nColumns",
			"m",
		]
```

Now what `_dumpVarNames()` will do is simply returning a list of variables to access for output.

As private variables can not be accessed by mixins all variables in this example have therefore been defined as public variables. This is a general limitation of python so there is no way around this: All variables to output this way need to be non-private.

Now let's create an instance of `Matrix` and invoke `dump()`:

```python
m = Matrix([
	[	1,	2,	3 	],
	[	4,	5,	6 	],
	[	7,	8,	9.1234567	],
])

m.dump()
```

If `dump()` is invoked on an initialized instance of `Matrix` from this example such an object will render to something like this:

```
<Matrix(
	nRows = 3
	nColumns = 3
	m = [
		[ 1, 2, 3 ],
		[ 4, 5, 6 ],
		[ 7, 8, 9.1234567 ],
	]
)>
```

### Helper method _dump(ctx)

If you implement the method `_dump(ctx:jk_prettyprintobj.DumpCtx) -> None` your method needs to use the provided context object to implement dumping variables to STDOUT on your own. This variant is helpful if you - for some reason - require to output private variables that an implementation of `_dumpVarNames()` will not be able to access.

By implementing this method you will also be able to modify the way how the contents of a variable will be written to STDOUT.

Here is an example of a simple but working implementation:

```python
class Matrix(jk_prettyprintobj.DumpMixin):

	def __init__(self, m):
		self.__m = m
		self.__nRows = len(m)
		self.__nColumns = len(m[0])

	def _dump(self, ctx:jk_prettyprintobj.DumpCtx):
		ctx.dumpVar("nRows", self.__nRows)
		ctx.dumpVar("nColumns", self.__nColumns)
		ctx.dumpVar("m", self.__m, "float_round3")
```

This class is expected to represent a mathematical matrix and therefore should receive a two-dimensional field of `float` values during construction. During construction this data is stored in a private variable named `__m`. Additional private variables are created. For simplicity no other methods except `dump_()` are implemented in this example.

Now what `_dump()` will do is to invoke `dumpVar()` for every single variable. `dumpVar()` has the following signature:

* `dumpVar(varName:str, value, postProcessorName:str = None) -> None`

This method requires to receive up to three arguments:
* `str varName`: The name to use for output. In this example we use `nRows` as we might add a property of exactly this name. (Not implemented in this example!)
* `* value`: A value of any kind. This is the value that should later on be written to STDOUT.
* `str processorName`: This optional value can be one of several identifiers that indicate how to process the value *before* it is converted to a string. (See section below.)

If `dump()` is invoked on an initialized instance of `Matrix` from this example such an object will render to something like this:

```
<Matrix(
	nRows = 3
	nColumns = 3
	m = [
		[ 1, 2, 3 ],
		[ 4, 5, 6 ],
		[ 7, 8, 9.123 ],
	]
)>
```

Please note that in this case the output of the very last `float` in the matrix might be rounded to three digits as defined by the processor `float_round3`. This is different to an implementation providing `_dumpVarNames()`.

### Processors

For producing output you can apply a processor that will preprocess the output before writing it to STDOUT. This is useful to achieve a more human readable representation of data in some cases.

These are the processors you can use:

| **Name**			| **Description**				|
| ---				| ---							|
| `float_round1`	| Round to 1 fractional digit	|
| `float_round2`	| Round to 2 fractional digit	|
| `float_round3`	| Round to 3 fractional digit	|
| `float_round4`	| Round to 4 fractional digit	|
| `float_round5`	| Round to 5 fractional digit	|
| `float_round6`	| Round to 6 fractional digit	|
| `float_round7`	| Round to 7 fractional digit	|
| `int_hex`			| Convert to hexadecimal representation		|
| `int_bit`			| Convert to binary representation		|
| `str_shorten`		| Shorten a string to at most 40 characters. If you have objects with large amounts of text this feature can make your output more readable.	|

Futher Development
-------------------

It is likely that future developments will add more alternatives for dumping an objects. If you have any ideas, requirements or recommendations please feel free to leave a comment.

Contact Information
-------------------

This is Open Source code. That not only gives you the possibility of freely using this code it also
allows you to contribute. Feel free to contact the author(s) of this software listed below, either
for comments, collaboration requests, suggestions for improvement or reporting bugs:

* Jürgen Knauth: pubsrc@binary-overflow.de

License
-------

This software is provided under the following license:

* Apache Software License 2.0




            

Raw data

            {
    "_id": null,
    "home_page": null,
    "name": "jk_prettyprintobj",
    "maintainer": null,
    "docs_url": null,
    "requires_python": ">=3.8",
    "maintainer_email": "J\u00fcrgen Knauth <pubsrc@binary-overflow.de>",
    "keywords": "pretty-print,debugging,debug",
    "author": null,
    "author_email": "J\u00fcrgen Knauth <pubsrc@binary-overflow.de>",
    "download_url": "https://files.pythonhosted.org/packages/59/85/ee3f92b666db960499d8214622b0f8e9fdb4f6f252d1db29a2eccd753932/jk_prettyprintobj-0.2024.2.18.tar.gz",
    "platform": null,
    "description": "jk_prettyprintobj\n========\n\nIntroduction\n------------\n\nThis python module provides a mixin for dumping objects. This is ment for debugging purposes: Sometimes it is very convenient to have a way of writing all data of an object to STDOUT in a human readable way. This module assists in such implementations.\n\nInformation about this module can be found here:\n\n* [github.org](https://github.com/jkpubsrc/python-module-jk-prettyprintobj)\n* [pypi.python.org](https://pypi.python.org/pypi/jk_prettyprintobj)\n\nHow to use this module\n----------------------\n\n### Import the module\n\nIn order to use this module you need to import it first. So add this line to the head of your python source code file:\n\n```python\nimport jk_prettyprintobj\n```\n\n### Use the provided mixin\n\nTo make use of the features of this module you must add a mixin to your class. Example:\n\n```python\nclass ExampleClass(jk_prettyprintobj.DumpMixin):\n\n\tdef __init__(self, ...):\n\t\t...\n\n\t...\n```\n\nIf you derive your class from a base class just add the mixin to your list of base classes. The order does not matter in this case. Here is an example how to do this:\n\n```python\nclass MyFancyException(Exception, jk_prettyprintobj.DumpMixin):\n\n\tdef __init__(self, msg:str):\n\t\tsuper().__init__(msg)\n\n\t...\n```\n\nIn this example we use `Exception` as a base class to keep this example simple. It just demonstrates the technique. You can use any base class for inheritance, it is just necessary that you somewhere in the list of base classes add `jk_prettyprintobj.DumpMixin`. This does not yet make use of the features provided by `jk_prettyprintobj` but prepares its use.\n\nThis mixin adds a regular method named `dump()` to the class. For all things to work it is important that you have no other method named `dump()` in your class that might conflict with the implementation provided by `DumpMixin`. This method can be called later, but some additional implementation steps need to be taken first. (See next section!)\n\n### Implement a helper method\n\nTo actually enable the class to produce output we must implement one of the helper methods. These are:\n\n| **Method name**\t\t\t\t\t\t\t\t\t| **Description**\t\t\t\t\t\t\t\t|\n| ---\t\t\t\t\t\t\t\t\t\t\t\t| ---\t\t\t\t\t\t\t\t\t\t\t|\n| `_dump(ctx:jk_prettyprintobj.DumpCtx) -> None`\t| Implement dumping data on your own\t\t\t|\n| `_dumpVarNames() -> typing.List[str]`\t\t\t\t| Provide the names of the variable to output\t|\n\nMore to these options in the next sections.\n\n### Helper method _dumpVarNames()\n\nIf you implement the method `_dumpVarNames() -> typing.List[str]` your method needs to return a list of variable names that should be dumped to STDOUT.\n\nHere is an example of a simple but working implementation.\n\n```python\nclass Matrix(jk_prettyprintobj.DumpMixin):\n\n\tdef __init__(self, m):\n\t\tself.m = m\n\t\tself.nRows = len(m)\n\t\tself.nColumns = len(m[0])\n\n\tdef _dumpVarNames(self) -> list:\n\t\treturn [\n\t\t\t\"nRows\",\n\t\t\t\"nColumns\",\n\t\t\t\"m\",\n\t\t]\n```\n\nNow what `_dumpVarNames()` will do is simply returning a list of variables to access for output.\n\nAs private variables can not be accessed by mixins all variables in this example have therefore been defined as public variables. This is a general limitation of python so there is no way around this: All variables to output this way need to be non-private.\n\nNow let's create an instance of `Matrix` and invoke `dump()`:\n\n```python\nm = Matrix([\n\t[\t1,\t2,\t3 \t],\n\t[\t4,\t5,\t6 \t],\n\t[\t7,\t8,\t9.1234567\t],\n])\n\nm.dump()\n```\n\nIf `dump()` is invoked on an initialized instance of `Matrix` from this example such an object will render to something like this:\n\n```\n<Matrix(\n\tnRows = 3\n\tnColumns = 3\n\tm = [\n\t\t[ 1, 2, 3 ],\n\t\t[ 4, 5, 6 ],\n\t\t[ 7, 8, 9.1234567 ],\n\t]\n)>\n```\n\n### Helper method _dump(ctx)\n\nIf you implement the method `_dump(ctx:jk_prettyprintobj.DumpCtx) -> None` your method needs to use the provided context object to implement dumping variables to STDOUT on your own. This variant is helpful if you - for some reason - require to output private variables that an implementation of `_dumpVarNames()` will not be able to access.\n\nBy implementing this method you will also be able to modify the way how the contents of a variable will be written to STDOUT.\n\nHere is an example of a simple but working implementation:\n\n```python\nclass Matrix(jk_prettyprintobj.DumpMixin):\n\n\tdef __init__(self, m):\n\t\tself.__m = m\n\t\tself.__nRows = len(m)\n\t\tself.__nColumns = len(m[0])\n\n\tdef _dump(self, ctx:jk_prettyprintobj.DumpCtx):\n\t\tctx.dumpVar(\"nRows\", self.__nRows)\n\t\tctx.dumpVar(\"nColumns\", self.__nColumns)\n\t\tctx.dumpVar(\"m\", self.__m, \"float_round3\")\n```\n\nThis class is expected to represent a mathematical matrix and therefore should receive a two-dimensional field of `float` values during construction. During construction this data is stored in a private variable named `__m`. Additional private variables are created. For simplicity no other methods except `dump_()` are implemented in this example.\n\nNow what `_dump()` will do is to invoke `dumpVar()` for every single variable. `dumpVar()` has the following signature:\n\n* `dumpVar(varName:str, value, postProcessorName:str = None) -> None`\n\nThis method requires to receive up to three arguments:\n* `str varName`: The name to use for output. In this example we use `nRows` as we might add a property of exactly this name. (Not implemented in this example!)\n* `* value`: A value of any kind. This is the value that should later on be written to STDOUT.\n* `str processorName`: This optional value can be one of several identifiers that indicate how to process the value *before* it is converted to a string. (See section below.)\n\nIf `dump()` is invoked on an initialized instance of `Matrix` from this example such an object will render to something like this:\n\n```\n<Matrix(\n\tnRows = 3\n\tnColumns = 3\n\tm = [\n\t\t[ 1, 2, 3 ],\n\t\t[ 4, 5, 6 ],\n\t\t[ 7, 8, 9.123 ],\n\t]\n)>\n```\n\nPlease note that in this case the output of the very last `float` in the matrix might be rounded to three digits as defined by the processor `float_round3`. This is different to an implementation providing `_dumpVarNames()`.\n\n### Processors\n\nFor producing output you can apply a processor that will preprocess the output before writing it to STDOUT. This is useful to achieve a more human readable representation of data in some cases.\n\nThese are the processors you can use:\n\n| **Name**\t\t\t| **Description**\t\t\t\t|\n| ---\t\t\t\t| ---\t\t\t\t\t\t\t|\n| `float_round1`\t| Round to 1 fractional digit\t|\n| `float_round2`\t| Round to 2 fractional digit\t|\n| `float_round3`\t| Round to 3 fractional digit\t|\n| `float_round4`\t| Round to 4 fractional digit\t|\n| `float_round5`\t| Round to 5 fractional digit\t|\n| `float_round6`\t| Round to 6 fractional digit\t|\n| `float_round7`\t| Round to 7 fractional digit\t|\n| `int_hex`\t\t\t| Convert to hexadecimal representation\t\t|\n| `int_bit`\t\t\t| Convert to binary representation\t\t|\n| `str_shorten`\t\t| Shorten a string to at most 40 characters. If you have objects with large amounts of text this feature can make your output more readable.\t|\n\nFuther Development\n-------------------\n\nIt is likely that future developments will add more alternatives for dumping an objects. If you have any ideas, requirements or recommendations please feel free to leave a comment.\n\nContact Information\n-------------------\n\nThis is Open Source code. That not only gives you the possibility of freely using this code it also\nallows you to contribute. Feel free to contact the author(s) of this software listed below, either\nfor comments, collaboration requests, suggestions for improvement or reporting bugs:\n\n* J\u00fcrgen Knauth: pubsrc@binary-overflow.de\n\nLicense\n-------\n\nThis software is provided under the following license:\n\n* Apache Software License 2.0\n\n\n\n",
    "bugtrack_url": null,
    "license": null,
    "summary": "This python module provides a mixin for creating pretty debugging output for objects. This is especially useful for semi-complex data structures.",
    "version": "0.2024.2.18",
    "project_urls": null,
    "split_keywords": [
        "pretty-print",
        "debugging",
        "debug"
    ],
    "urls": [
        {
            "comment_text": null,
            "digests": {
                "blake2b_256": "3d86529c6fa41352c1b90c1eb82c3ea56f66cf91506924cc0860e3e0ad9761e4",
                "md5": "2b83c0d98ea4b69710e6c163694ffe8e",
                "sha256": "418d5e3d5c56667810c1ef40d0e4a829a429363a6599b9b83cc7f94bb4215efe"
            },
            "downloads": -1,
            "filename": "jk_prettyprintobj-0.2024.2.18-py3-none-any.whl",
            "has_sig": false,
            "md5_digest": "2b83c0d98ea4b69710e6c163694ffe8e",
            "packagetype": "bdist_wheel",
            "python_version": "py3",
            "requires_python": ">=3.8",
            "size": 9530,
            "upload_time": "2024-02-19T07:15:07",
            "upload_time_iso_8601": "2024-02-19T07:15:07.799460Z",
            "url": "https://files.pythonhosted.org/packages/3d/86/529c6fa41352c1b90c1eb82c3ea56f66cf91506924cc0860e3e0ad9761e4/jk_prettyprintobj-0.2024.2.18-py3-none-any.whl",
            "yanked": false,
            "yanked_reason": null
        },
        {
            "comment_text": null,
            "digests": {
                "blake2b_256": "5985ee3f92b666db960499d8214622b0f8e9fdb4f6f252d1db29a2eccd753932",
                "md5": "173c90a61bac92b1b7734aee17bc412b",
                "sha256": "5057479eadcd566219e3a0aaa76f8e4ccb2b8a10040fce25401cba5232e222cc"
            },
            "downloads": -1,
            "filename": "jk_prettyprintobj-0.2024.2.18.tar.gz",
            "has_sig": false,
            "md5_digest": "173c90a61bac92b1b7734aee17bc412b",
            "packagetype": "sdist",
            "python_version": "source",
            "requires_python": ">=3.8",
            "size": 10934,
            "upload_time": "2024-02-19T07:15:09",
            "upload_time_iso_8601": "2024-02-19T07:15:09.819462Z",
            "url": "https://files.pythonhosted.org/packages/59/85/ee3f92b666db960499d8214622b0f8e9fdb4f6f252d1db29a2eccd753932/jk_prettyprintobj-0.2024.2.18.tar.gz",
            "yanked": false,
            "yanked_reason": null
        }
    ],
    "upload_time": "2024-02-19 07:15:09",
    "github": false,
    "gitlab": false,
    "bitbucket": false,
    "codeberg": false,
    "lcname": "jk_prettyprintobj"
}
        
Elapsed time: 0.23787s