{"id":13738447,"url":"https://github.com/breuleux/hrepr","last_synced_at":"2025-04-14T20:09:06.386Z","repository":{"id":44745022,"uuid":"97875322","full_name":"breuleux/hrepr","owner":"breuleux","description":"HTML representation for Python objects.","archived":false,"fork":false,"pushed_at":"2024-10-31T17:41:11.000Z","size":1127,"stargazers_count":16,"open_issues_count":0,"forks_count":2,"subscribers_count":3,"default_branch":"master","last_synced_at":"2025-04-14T20:08:52.657Z","etag":null,"topics":[],"latest_commit_sha":null,"homepage":null,"language":"HTML","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/breuleux.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null}},"created_at":"2017-07-20T20:24:02.000Z","updated_at":"2024-11-04T16:43:04.000Z","dependencies_parsed_at":"2023-12-13T20:07:05.535Z","dependency_job_id":"f9ccc04f-f462-403a-b97e-43beee0b4ed5","html_url":"https://github.com/breuleux/hrepr","commit_stats":{"total_commits":190,"total_committers":2,"mean_commits":95.0,"dds":"0.010526315789473717","last_synced_commit":"2c71b542389138c2191689217dd8c12669f57fb1"},"previous_names":[],"tags_count":28,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/breuleux%2Fhrepr","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/breuleux%2Fhrepr/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/breuleux%2Fhrepr/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/breuleux%2Fhrepr/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/breuleux","download_url":"https://codeload.github.com/breuleux/hrepr/tar.gz/refs/heads/master","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":248952350,"owners_count":21188426,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":[],"created_at":"2024-08-03T03:02:22.725Z","updated_at":"2025-04-14T20:09:06.346Z","avatar_url":"https://github.com/breuleux.png","language":"HTML","funding_links":[],"categories":["Python"],"sub_categories":[],"readme":"# hrepr\n\n`hrepr` outputs HTML/pretty representations for Python objects.\n\n✅ Nice, colourful representations of lists, dicts, dataclasses, booleans...\u003cbr/\u003e\n✅ Ridiculously extensible and configurable\u003cbr/\u003e\n✅ Handles recursive data structures\u003cbr/\u003e\n✅ Compatible with Jupyter notebooks\u003cbr/\u003e\n\n\u003cimg src=\"https://raw.githubusercontent.com/breuleux/hrepr/master/images/hrepr1.png\" width=\"400px\"\u003e\u003cimg src=\"https://raw.githubusercontent.com/breuleux/hrepr/master/images/hrepr2.png\" width=\"400px\"\u003e\n\nI suggest studying the example file to learn `hrepr`:\n\n* `python examples/exhibit.py \u003e exhibit.html` (and then view the HTML file)\n\nAlso see the Jupyter notebook at `examples/Basics.ipynb`, but keep in mind that GitHub can't display it properly because of the injected styles/scripts.\n\n\n## Install\n\n```python\npip install hrepr\n```\n\n\n## Usage\n\n```python\nfrom hrepr import hrepr\nobj = {'potatoes': [1, 2, 3], 'bananas': {'cantaloups': 8}}\n\n# Print the HTML representation of obj\nprint(hrepr(obj))\n\n# Wrap the representation in \u003chtml\u003e\u003cbody\u003e tags and embed the default\n# css style files in a standalone page, which is saved to obj.html\nhrepr.page(obj, file=\"obj.html\")\n```\n\nIn a Jupyter Notebook, you can return `hrepr(obj)` from any cell and it will show its representation for you. You can also write `display_html(hrepr(obj))`.\n\n\n## Custom representations\n\nA custom representation for an object can be defined using the following three methods (it is not necessary to define all of them, only those that are relevant to your case):\n\n* `__hrepr__(self, H, hrepr)` returns the normal HTML representation.\n    * Use `H.span[\"some-class\"](some-content, some_attr=some_value)` to generate HTML.\n    * Use `hrepr(self.x)` to generate the representation for some subfield `x`.\n    * `hrepr.config` contains any keyword arguments given in the top level call to `hrepr`. For instance, if you call `hrepr(obj, blah=3)`, then `hrepr.config.blah == 3` in all calls to `__hrepr__` down the line (the default value for all keys is `None`).\n* `__hrepr_short__(self, H, hrepr)` returns a *short* representation, ideally of a constant size.\n    * The output of this method is used when we hit max depth, or for repeated references.\n    * Only include bare minimum information. Short means short.\n* `__hrepr_resources__(cls, H)` is a **classmethod** that returns resources common to all instances of the class (typically a stylesheet or a script).\n    * When generating a page, the resources will go in `\u003chead\u003e`.\n    * You can return a list of resources.\n\nNo dependency on `hrepr` is necessary.\n\nFor example:\n\n```python\nclass Person:\n    def __init__(self, name, age, job):\n        self.name = name\n        self.age = age\n        self.job = job\n\n    @classmethod\n    def __hrepr_resources__(cls, H):\n        # Note: you might need to add \"!important\" next to some rules if\n        # they conflict with defaults from hrepr's own CSS.\n        return H.style(\"\"\"\n            .person {\n                background: magenta !important;\n                border-color: magenta !important;\n            }\n            .person-short { font-weight: bold; color: green; }\n        \"\"\")\n\n    def __hrepr__(self, H, hrepr):\n        # hrepr.make.instance is a helper to show a table with a header that\n        # describes some kind of object\n        return hrepr.make.instance(\n            title=self.name,\n            fields=[[\"age\", self.age], [\"job\", self.job]],\n            delimiter=\" ↦ \",\n            type=\"person\",\n        )\n\n    def __hrepr_short__(self, H, hrepr):\n        return H.span[\"person-short\"](self.name)\n```\n\n\u003cimg src=\"https://raw.githubusercontent.com/breuleux/hrepr/master/images/hrepr3.png\" width=\"600px\"\u003e\n\n\n## References\n\n`hrepr` can handle circular references. Furthermore, if an object is found at several places in a structure, only the first occurrence will be printed in full, and any other will be a numeric reference mapped to the short representation for the object. It looks like this:\n\n\u003cimg src=\"https://raw.githubusercontent.com/breuleux/hrepr/master/images/hrepr4.png\" width=\"600px\"\u003e\n\nThe `shortrefs` and `norefs` configuration keys control the representation of references:\n\n\u003cimg src=\"https://raw.githubusercontent.com/breuleux/hrepr/master/images/hrepr5.png\" width=\"600px\"\u003e\n\n`norefs` is ignored when there are circular references.\n\n\n## HTML generation\n\nGenerate HTML using the `H` parameter to `__hrepr__`, or import it and use it directly:\n\n```python\nfrom hrepr import H\nhtml = H.span[\"bear\"](\n    \"Only \", H.b(\"YOU\"), \" can prevent forest fires!\",\n    style=\"color: brown;\"\n)\nprint(html)\n# \u003cspan class=\"bear\" style=\"color: brown;\"\u003eOnly \u003cb\u003eYOU\u003c/b\u003e can prevent forest fires!\u003c/span\u003e\n```\n\n`H` can be built incrementally: if you have an element, you can call it to add children, index it to add classes, and so on. For instance:\n\n```python\nfrom hrepr import H\nhtml = H.span()\nhtml = html(\"Only \")\nhtml = html(style=\"color: brown;\")[\"bear\"]\nhtml = html(H.b(\"YOU\"), \" can prevent forest fires!\")\nprint(html)\n# \u003cspan class=\"bear\" style=\"color: brown;\"\u003eOnly \u003cb\u003eYOU\u003c/b\u003e can prevent forest fires!\u003c/span\u003e\n```\n\nThis can be handy if you want to tweak generated HTML a little. For example, `hrepr(obj)[\"fox\"]` will tack on the class `fox` to the representation of the object.\n\n\n### Helpers\n\n* `hrepr.make.instance(title, fields, delimiter=None, type=None)`: formats the fields like a dataclass, with title on top.\n* `hrepr.make.bracketed(body, start, end, type=None)`: formats the body with the specified start/end bracket.\n\n\n### Using JavaScript libraries\n\nThe `J` function lets you create JavaScript expressions. If an expression takes an HTML element as an argument, you can create one and pass it along with the `returns()` statement, which tells hrepr to insert it where the `J()` expression is located.\n\nFor example, you can load Plotly and create a plot like this:\n\n```python\nfrom hrepr import H, J, returns\n\ndef plot(data):\n    Plotly = J(src=\"https://cdn.plot.ly/plotly-latest.min.js\").Plotly\n    return Plotly.newPlot(\n        returns(H.div()),\n        [{\"x\": list(range(len(data))), \"y\": list(data)}],\n    )\n\nprint(plot([math.sin(x / 10) for x in range(100)]).as_page())\n```\n\nThe above will:\n\n* Put the specified script in the `\u003chead\u003e` element of the page (hence why you need the `as_page()` call for it to work).\n* Insert some hrepr library code.\n* Insert a `\u003cdiv\u003e`, as specified in `returns(H.div())`, where the `J()` call is, with an auto-generated ID.\n* Get the `Plotly.newPlot` function in the global namespace.\n* Call it with the `div` element as the first argument, and any other arguments given (as long as they can be serialized to JSON).\n\nIt will look like this:\n\n\u003cimg src=\"https://raw.githubusercontent.com/breuleux/hrepr/master/images/hrepr6.png\" width=\"600px\"\u003e\n\nYou can, of course, nest `J` inside `H`, e.g. `H.body(H.h1(...), H.div(J(...)))`, as much as you'd like, so you can easily combine multiple libraries. Note that if a JavaScript has no `returns()` argument, it may to return some HTML element to insert in its stead (a placeholder will be created automatically).\n\nBe careful with `J` objects: since they override `__getattr__` and `__call__`, they will almost never raise exceptions and it is easy to accidentally generate improper expressions.\n\n\n### Modules\n\nAnother example, this time using ESM (modules):\n\n```python\ncystyle = [{\"selector\": \"node\",\"style\": {\"background-color\": \"#800\", \"label\": \"data(id)\"},},{\"selector\": \"edge\",\"style\": {\"width\": 3,\"line-color\": \"#ccc\",\"target-arrow-color\": \"#ccc\",\"target-arrow-shape\": \"triangle\",\"curve-style\": \"bezier\"}}]\n\ncytoscape = J(module=\"https://cdnjs.cloudflare.com/ajax/libs/cytoscape/3.23.0/cytoscape.esm.min.js\")\nj = cytoscape(\n    container=returns(H.div(style=\"width:500px;height:500px;border:1px solid black;\")),\n    elements=[\n        {\"data\": {\"id\": \"A\"}},\n        {\"data\": {\"id\": \"B\"}},\n        {\"data\": {\"id\": \"C\"}},\n        {\"data\": {\"source\": \"A\", \"target\": \"B\"}},\n        {\"data\": {\"source\": \"B\", \"target\": \"C\"}},\n        {\"data\": {\"source\": \"C\", \"target\": \"A\"}},\n    ],\n    style=cystyle,\n    layout={\"name\": \"cose\"},\n)\nprint(j.as_page())\n```\n\nThe above will work like the previous example, with the following differences:\n\n* Import the specified module.\n* All keyword arguments are packed into an object, which will be passed as the last (in this cas, only) argument to the module's default export.\n\nIf you wish to use a non-default export, use `namespace=` instead of `module=`. For example, if you want to use the JavaScript import `import {fn} from \"xxx\"`, use `J(namespace=\"xxx\").fn(...)`.\n\n\n## Customize hrepr\n\n### Mixins\n\nIf you want to *really* customize hrepr, you can use mixins. They look like a bit of black magic, but they're simple enough:\n\n```python\n# ovld is one of the dependencies of hrepr\nfrom ovld import ovld, extend_super, has_attribute, OvldMC\nfrom hrepr import hrepr\n\nclass MyMixin(metaclass=OvldMC):\n    # Change the representation of integers\n\n    @extend_super\n    def hrepr_resources(self, cls: int):\n        # Note: in hrepr_resources, cls is the int type, not an integer\n        return self.H.style(\".my-integer { color: fuchsia; }\")\n\n    @extend_super\n    def hrepr(self, n: int):\n        return self.H.span[\"my-integer\"](\"The number \", str(n))\n\n    # Specially handle any object with a \"quack\" method\n\n    def hrepr(self, duck: has_attribute(\"quack\")):\n        return self.H.span(\"🦆\")\n```\n\n\u003cimg src=\"https://raw.githubusercontent.com/breuleux/hrepr/master/images/hrepr7.png\" width=\"600px\"\u003e\n\nThe annotation for a rule can either be a type, `ovld.has_attribute`, or pretty much any function wrapped with the `ovld.meta` decorator, as long as the function operates on classes. See the documentation for [ovld](https://github.com/breuleux/ovld#other-features) for more information.\n\nAnd yes, you can define `hrepr` multiple times inside the class, as long as they have distinct annotations and you inherit from `Hrepr`. You can also define `hrepr_short` or `hrepr_resources` the same way.\n\n### Postprocessors\n\n`hrepr` can be given a postprocessor that is called on the representation of any object. You can use this to do things like highlighting specific objects:\n\n```python\nfrom hrepr import H\n\nstyle = H.style(\".highlight { border: 3px solid red !important; }\")\n\ndef highlight(x):\n    def postprocess(element, obj, hrepr):\n        if obj == x:\n            # Adds the \"highlight\" class and attaches a style\n            return element[\"highlight\"].fill(resources=style)\n        else:\n            return element\n\n    return postprocess\n\nhrepr([1, 2, [3, 4, 2]], postprocess=highlight(2))\n```\n\n\u003cimg src=\"https://raw.githubusercontent.com/breuleux/hrepr/master/images/hrepr8.png\" width=\"600px\"\u003e\n\n\n### hrepr variants\n\nTo put this all together, you can create a *variant* of `hrepr`:\n\n```python\nhrepr2 = hrepr.variant(mixins=MyMixin, postprocess=highlight(2))\nhrepr2([1, 2, 3])  # Will use the mixins and postprocessor\n```\n\n\n### Configure the hrepr function itself\n\nAlternatively, you can configure the main `hrepr`:\n\n```python\nhrepr.configure(mixins=MyMixin, postprocess=highlight(2))\n```\n\nBut keep in mind that unlike the variant, the above will modify `hrepr` for everything else as well.\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fbreuleux%2Fhrepr","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fbreuleux%2Fhrepr","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fbreuleux%2Fhrepr/lists"}