visitor


Namevisitor JSON
Version 0.1.3 PyPI version JSON
download
home_pagehttp://github.com/mbr/visitor
SummaryA tiny pythonic visitor implementation.
upload_time2016-05-18 19:27:53
maintainerNone
docs_urlNone
authorMarc Brinkmann
requires_pythonNone
licenseMIT
keywords
VCS
bugtrack_url
requirements No requirements were recorded.
Travis-CI No Travis.
coveralls test coverage No coveralls.
            visitor
=======

A tiny library to facilitate `visitor
<https://en.wikipedia.org/wiki/Visitor_pattern>`_ implementation in Python
(which are slightly peculiar due to dynamic typing). In fact, it is so small,
you may just be better off copy & pasting the source straight into your
project...


Example use
-----------

A simple JSON-encoder:

.. code-block:: python

    from visitor import Visitor


    class JSONEncoder(Visitor):
        def __init__(self):
            self.indent = 0

        def escape_str(self, s):
            # note: this is not a good escape function, do not use this in
            # production!
            s = s.replace('\\', '\\\\')
            s = s.replace('"', '\\"')
            return '"' + s + '"'

        def visit_list(self, node):
            self.indent += 1
            s = '[\n' + '  ' * self.indent
            s += (',\n' + '  ' * self.indent).join(self.visit(item)
                                                   for item in node)
            self.indent -= 1
            s += '\n' + '  ' * self.indent + ']'
            return s

        def visit_str(self, node):
            return self.escape_str(node)

        def visit_int(self, node):
            return str(node)

        def visit_bool(self, node):
            return 'true' if node else 'false'

        def visit_dict(self, node):
            self.indent += 1
            s = '{\n' + '  ' * self.indent
            s += (',\n' + '  ' * self.indent).join(
                '{}: {}'.format(self.escape_str(key), self.visit(value))
                for key, value in sorted(node.items())
            )
            self.indent -= 1
            s += '\n' + '  ' * self.indent + '}'
            return s


    data = [
        'List', 'of', 42, 'items', True, {
            'sub1': 'some string',
            'sub2': {
                'sub2sub1': False,
                'sub2sub2': 123,
            }
        }
    ]

    print(JSONEncoder().visit(data))



Output::

    [
      "List",
      "of",
      42,
      "items",
      true,
      {
        "sub1": "some string",
        "sub2": {
          "sub2sub1": false,
          "sub2sub2": 123
        }
      }
    ]
            

Raw data

            {
    "_id": null,
    "home_page": "http://github.com/mbr/visitor",
    "name": "visitor",
    "maintainer": null,
    "docs_url": null,
    "requires_python": null,
    "maintainer_email": null,
    "keywords": null,
    "author": "Marc Brinkmann",
    "author_email": "git@marcbrinkmann.de",
    "download_url": "https://files.pythonhosted.org/packages/d7/58/785fcd6de4210049da5fafe62301b197f044f3835393594be368547142b0/visitor-0.1.3.tar.gz",
    "platform": "UNKNOWN",
    "description": "visitor\n=======\n\nA tiny library to facilitate `visitor\n<https://en.wikipedia.org/wiki/Visitor_pattern>`_ implementation in Python\n(which are slightly peculiar due to dynamic typing). In fact, it is so small,\nyou may just be better off copy & pasting the source straight into your\nproject...\n\n\nExample use\n-----------\n\nA simple JSON-encoder:\n\n.. code-block:: python\n\n    from visitor import Visitor\n\n\n    class JSONEncoder(Visitor):\n        def __init__(self):\n            self.indent = 0\n\n        def escape_str(self, s):\n            # note: this is not a good escape function, do not use this in\n            # production!\n            s = s.replace('\\\\', '\\\\\\\\')\n            s = s.replace('\"', '\\\\\"')\n            return '\"' + s + '\"'\n\n        def visit_list(self, node):\n            self.indent += 1\n            s = '[\\n' + '  ' * self.indent\n            s += (',\\n' + '  ' * self.indent).join(self.visit(item)\n                                                   for item in node)\n            self.indent -= 1\n            s += '\\n' + '  ' * self.indent + ']'\n            return s\n\n        def visit_str(self, node):\n            return self.escape_str(node)\n\n        def visit_int(self, node):\n            return str(node)\n\n        def visit_bool(self, node):\n            return 'true' if node else 'false'\n\n        def visit_dict(self, node):\n            self.indent += 1\n            s = '{\\n' + '  ' * self.indent\n            s += (',\\n' + '  ' * self.indent).join(\n                '{}: {}'.format(self.escape_str(key), self.visit(value))\n                for key, value in sorted(node.items())\n            )\n            self.indent -= 1\n            s += '\\n' + '  ' * self.indent + '}'\n            return s\n\n\n    data = [\n        'List', 'of', 42, 'items', True, {\n            'sub1': 'some string',\n            'sub2': {\n                'sub2sub1': False,\n                'sub2sub2': 123,\n            }\n        }\n    ]\n\n    print(JSONEncoder().visit(data))\n\n\n\nOutput::\n\n    [\n      \"List\",\n      \"of\",\n      42,\n      \"items\",\n      true,\n      {\n        \"sub1\": \"some string\",\n        \"sub2\": {\n          \"sub2sub1\": false,\n          \"sub2sub2\": 123\n        }\n      }\n    ]",
    "bugtrack_url": null,
    "license": "MIT",
    "summary": "A tiny pythonic visitor implementation.",
    "version": "0.1.3",
    "split_keywords": [],
    "urls": [
        {
            "comment_text": "",
            "digests": {
                "blake2b_256": "d758785fcd6de4210049da5fafe62301b197f044f3835393594be368547142b0",
                "md5": "94a024ed0ec1b02b4497c15267d319ca",
                "sha256": "2c737903b2b6864ebc6167eef7cf3b997126f1aa94bdf590f90f1436d23e480a"
            },
            "downloads": -1,
            "filename": "visitor-0.1.3.tar.gz",
            "has_sig": true,
            "md5_digest": "94a024ed0ec1b02b4497c15267d319ca",
            "packagetype": "sdist",
            "python_version": "source",
            "requires_python": null,
            "size": 3260,
            "upload_time": "2016-05-18T19:27:53",
            "upload_time_iso_8601": "2016-05-18T19:27:53.383175Z",
            "url": "https://files.pythonhosted.org/packages/d7/58/785fcd6de4210049da5fafe62301b197f044f3835393594be368547142b0/visitor-0.1.3.tar.gz",
            "yanked": false,
            "yanked_reason": null
        }
    ],
    "upload_time": "2016-05-18 19:27:53",
    "github": true,
    "gitlab": false,
    "bitbucket": false,
    "github_user": "mbr",
    "github_project": "visitor",
    "travis_ci": false,
    "coveralls": false,
    "github_actions": false,
    "tox": true,
    "lcname": "visitor"
}
        
Elapsed time: 0.40823s