├── .circleci └── config.yml ├── .editorconfig ├── .github └── ISSUE_TEMPLATE.md ├── .gitignore ├── AUTHORS.rst ├── HISTORY.rst ├── LICENSE ├── MANIFEST.in ├── Makefile ├── README.rst ├── docs ├── .gitignore ├── Makefile ├── api_reference.rst ├── authors.rst ├── conf.py ├── history.rst ├── index.rst ├── make.bat └── usage.rst ├── prettyprinter ├── __init__.py ├── color.py ├── doc.py ├── doctypes.py ├── extras │ ├── __init__.py │ ├── attrs.py │ ├── dataclasses.py │ ├── django.py │ ├── ipython.py │ ├── ipython_repr_pretty.py │ ├── numpy.py │ ├── python.py │ └── requests.py ├── layout.py ├── pretty_stdlib.py ├── prettyprinter.py ├── render.py ├── sdoctypes.py ├── syntax.py └── utils.py ├── prettyprinterlightscreenshot.png ├── prettyprinterscreenshot.png ├── requirements_dev.txt ├── setup.cfg ├── setup.py ├── tests ├── __init__.py ├── conftest.py ├── perf.py ├── sample_json.json ├── test_ast.py ├── test_attrs.py ├── test_dataclasses.py ├── test_django │ ├── __init__.py │ ├── coreapp │ │ ├── __init__.py │ │ ├── models.py │ │ └── test_prettyprinter_definitions.py │ ├── manage.py │ └── prettyprinter_testproject │ │ ├── __init__.py │ │ ├── settings.py │ │ ├── urls.py │ │ └── wsgi.py ├── test_ipython_repr_pretty.py ├── test_numpy.py ├── test_prettyprinter.py ├── test_requests.py └── test_stdlib_definitions.py └── tox.ini /.circleci/config.yml: -------------------------------------------------------------------------------- 1 | # Python CircleCI 2.0 configuration file 2 | # 3 | # Check https://circleci.com/docs/2.0/language-python/ for more details 4 | # 5 | version: 2 6 | jobs: 7 | build: 8 | docker: 9 | # specify the version you desire here 10 | # use `-browsers` prefix for selenium tests, e.g. `3.6.1-browsers` 11 | - image: circleci/python:3.6.1 12 | 13 | working_directory: ~/repo 14 | 15 | steps: 16 | - checkout 17 | 18 | - restore_cache: 19 | keys: 20 | - v1-python-versions 21 | 22 | - run: 23 | name: install Python versions 24 | command: | 25 | [ ! -d "/home/circleci/.pyenv" ] && curl -L https://raw.githubusercontent.com/pyenv/pyenv-installer/master/bin/pyenv-installer | bash 26 | export PATH="/home/circleci/.pyenv/bin:$PATH" 27 | eval "$(pyenv init -)" 28 | pyenv install 3.5.4 --skip-existing 29 | pyenv install 3.6.3 --skip-existing 30 | pyenv global 3.6.3 3.5.4 31 | echo "Installed Python versions" 32 | 33 | - save_cache: 34 | paths: 35 | - /home/circleci/.pyenv/ 36 | key: v1-python-versions 37 | 38 | # Download and cache dependencies 39 | - restore_cache: 40 | keys: 41 | - v3-dependencies-{{ checksum "requirements_dev.txt" }} 42 | 43 | - run: 44 | name: install dependencies 45 | command: | 46 | export PATH="/home/circleci/.pyenv/bin:$PATH" 47 | eval "$(pyenv init -)" 48 | pip install 'tox==2.9.1' 49 | tox -vv --notest 50 | 51 | - save_cache: 52 | paths: 53 | - ./.tox/ 54 | key: v3-dependencies-{{ checksum "requirements_dev.txt" }} 55 | 56 | # run tests! 57 | - run: 58 | name: run tests 59 | command: | 60 | export PATH="/home/circleci/.pyenv/bin:$PATH" 61 | eval "$(pyenv init -)" 62 | tox 63 | 64 | - store_artifacts: 65 | path: test-reports 66 | destination: test-reports -------------------------------------------------------------------------------- /.editorconfig: -------------------------------------------------------------------------------- 1 | # http://editorconfig.org 2 | 3 | root = true 4 | 5 | [*] 6 | indent_style = space 7 | indent_size = 4 8 | trim_trailing_whitespace = true 9 | insert_final_newline = true 10 | charset = utf-8 11 | end_of_line = lf 12 | 13 | [*.bat] 14 | indent_style = tab 15 | end_of_line = crlf 16 | 17 | [LICENSE] 18 | insert_final_newline = false 19 | 20 | [Makefile] 21 | indent_style = tab 22 | -------------------------------------------------------------------------------- /.github/ISSUE_TEMPLATE.md: -------------------------------------------------------------------------------- 1 | * PrettyPrinter version: 2 | * Python version: 3 | * Operating System: 4 | 5 | ### Description 6 | 7 | Describe what you were trying to get done. 8 | Tell us what happened, what went wrong, and what you expected to happen. 9 | 10 | ### What I Did 11 | 12 | ``` 13 | Paste the command(s) you ran and the output. 14 | If there was a crash, please include the traceback here. 15 | ``` 16 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Byte-compiled / optimized / DLL files 2 | __pycache__/ 3 | *.py[cod] 4 | *$py.class 5 | 6 | # C extensions 7 | *.so 8 | 9 | # Distribution / packaging 10 | .Python 11 | env/ 12 | build/ 13 | develop-eggs/ 14 | dist/ 15 | downloads/ 16 | eggs/ 17 | .eggs/ 18 | lib/ 19 | lib64/ 20 | parts/ 21 | sdist/ 22 | var/ 23 | *.egg-info/ 24 | .installed.cfg 25 | *.egg 26 | 27 | # PyInstaller 28 | # Usually these files are written by a python script from a template 29 | # before PyInstaller builds the exe, so as to inject date/other infos into it. 30 | *.manifest 31 | *.spec 32 | 33 | # Installer logs 34 | pip-log.txt 35 | pip-delete-this-directory.txt 36 | 37 | # Unit test / coverage reports 38 | htmlcov/ 39 | .tox/ 40 | .coverage 41 | .coverage.* 42 | .cache 43 | nosetests.xml 44 | coverage.xml 45 | *,cover 46 | .hypothesis/ 47 | 48 | # Translations 49 | *.mo 50 | *.pot 51 | 52 | # Django stuff: 53 | *.log 54 | 55 | # Sphinx documentation 56 | docs/_build/ 57 | 58 | # PyBuilder 59 | target/ 60 | 61 | # pyenv python configuration file 62 | .python-version 63 | 64 | # Sublime Text 65 | *.sublime-project 66 | *.sublime-workspace 67 | 68 | # Vim 69 | .*.swp 70 | 71 | .DS_Store 72 | 73 | # VSCode 74 | .vscode -------------------------------------------------------------------------------- /AUTHORS.rst: -------------------------------------------------------------------------------- 1 | ======= 2 | Credits 3 | ======= 4 | 5 | * Tommi Kaikkonen 6 | * GitHub user `Cologler `_ 7 | * GitHub user `johnnoone `_ 8 | * GitHub user `dangirsh `_ 9 | * GitHub user `RazerM `_ 10 | * GitHub user `jdanbrown `_ 11 | * GitHub user `@anntzer `_ 12 | * GitHub user `@crowsonkb `_ 13 | -------------------------------------------------------------------------------- /HISTORY.rst: -------------------------------------------------------------------------------- 1 | ======= 2 | History 3 | ======= 4 | 5 | 0.18.0 (2019-06-21) 6 | ------------------- 7 | 8 | * `Improve prettyprinting of builtin bound methods. `_ by `@anntzer `_ 9 | * `Fix test suite compatibility with hypothesis4. `_ by `@anntzer `_ 10 | * `Use $COLORFGBG to help decide whether to use a dark or light style `_ by `@crowsonkb `_ 11 | * `Truncate numpy arrays with ndim >= 2 so that the total printed does not exceed max_seq_len `_ by `@crowsonkb `_ 12 | * Fixed ipython_repr_pretty extra raising an exception when printing Mock instances (GH #61) 13 | * Added support for pretty printing types.SimpleNamespace (GH #60) 14 | * Fixed dictionary pretty printing indentation when the value had a comment on the line above (GH #59) 15 | 16 | 17 | 0.17.0 (2019-03-14) 18 | ------------------- 19 | 20 | * `Add prettyprinter for numpy ndarrays. `_ by `@anntzer `_ 21 | * `Add helper to apply default config. `_ by `@anntzer `_ 22 | * A number of docs and CI improvements: `#43 `_, `#44 `_, `#45 `_ .Thanks `@anntzer `_ 23 | * `Add support for functools.partialmethod. `_ by `@anntzer `_ 24 | * `Fix typo in changelog. `_ Thanks `@Vlad-Shcherbina `_ 25 | 26 | 0.16.0 (2019-02-27) 27 | ------------------- 28 | 29 | * `Adds a new extra for numpy. `_ The extra currently registers pretty printers for numpy scalar types. Enable it with ``import prettyprinter; prettyprinter.install_extras(['numpy'])``. Thanks `@anntzer `_ 30 | * `C-API named tuples are now automatically prettyprinted. `_ C-API named tuples are returned from expressions such as ``sys.flags``, ``time.strptime(...)``, and ``os.stat(...)``. The fieldname of each tuple element is annotated using a comment in the output. 31 | 32 | 0.15.0 (2019-02-25) 33 | ------------------- 34 | 35 | This release brings bugfixes, an enhancement to pathlib prettyprinting (thanks `@anntzer `_ ) and a nice performance boost. There was an redundant subtree call in a tree normalization procedure that caused exponential runtime, worsening quickly if data was highly nested. That extra call is now removed. 36 | 37 | * `Fix exponential runtime in highly nested data `_ 38 | * `Fix infinite loop when rendering strings in highly nested data `_ 39 | * `Only split Path prettyprints on "/", not on "-" or other nonword chars. `_ , thanks `@anntzer `_ 40 | * `Add vim swapfiles to gitignore `_ , thanks `@anntzer `_ 41 | * `Fix typo `_ , thanks `@anntzer `_ 42 | 43 | 0.14.0 (2018-07-25) 44 | ------------------- 45 | 46 | Most likely no breaking changes. 47 | 48 | * Added definitions for ``pathlib`` standard library module thanks to GitHub user ``RazerM`` 49 | * Fixed unexpected error output inside Jupyter notebooks thanks to GitHub user ``jdanbrown`` 50 | * Fixed missing commas in ``setup.py`` requirements list 51 | 52 | 0.13.2 (2018-05-29) 53 | ------------------- 54 | 55 | No breaking changes. 56 | 57 | * Fixed the dataclasses pretty printer that had regressed after changes to the dataclasses API. Fix was contributed by GitHub user ``dangirsh``. 58 | 59 | 0.13.1 (2018-02-03) 60 | ------------------- 61 | 62 | No breaking changes. 63 | 64 | * Fixed GH issue #17 where Django models showed an incorrect display name for fields with choices. 65 | 66 | 0.13.0 (2018-02-03) 67 | ------------------- 68 | 69 | No breaking changes. 70 | 71 | * Added definitions for the ``ast`` standard library module thanks to GitHub user ``johnnoone``. 72 | 73 | 0.12.0 (2018-01-22) 74 | ------------------- 75 | 76 | No breaking changes. 77 | 78 | * Added a definition for classes that look like they were built with ``collections.namedtuple`` 79 | * If a pretty printer raises an exception, it is caught and emitted as a warning, and the default repr implementation will be used instead. 80 | * Added definitions for ``collections.ChainMap``, ``collections.defaultdict``, ``collections.deque``, ``functools.partial``, and for exception objects. 81 | * Made pretty printers for primitive types (dict, list, set, etc.) render a subclass constructor around them 82 | 83 | 84 | 0.11.0 (2018-01-20) 85 | ------------------- 86 | 87 | No breaking changes. 88 | 89 | * Added Python 3.5 support 90 | * Added ``pretty_call_alt`` function that doesn't depend on ``dict`` maintaining insertion order 91 | * Fixed bug in ``set_default_config`` where most configuration values were not updated 92 | * Added ``get_default_config`` 93 | 94 | 0.10.1 (2018-01-10) 95 | ------------------- 96 | 97 | No breaking changes. 98 | 99 | * Fixed regression with types.MappingProxyType not being properly registered. 100 | 101 | 0.10.0 (2018-01-09) 102 | ------------------- 103 | 104 | No breaking changes. 105 | 106 | * Added support for deferred printer registration, where instead of a concrete type value, you can pass a qualified path to a type as a ``str`` to ``register_pretty``. For an example, see `the deferred printer registration for uuid.UUID `_ 107 | 108 | 0.9.0 (2018-01-03) 109 | ------------------ 110 | 111 | No breaking changes. 112 | 113 | * Added pretty printer definition for ``types.MappingProxyType`` thanks to GitHub user `Cologler `_ 114 | * Added support for ``_repr_pretty_`` in the extra ``ipython_repr_pretty``. 115 | 116 | 117 | 0.8.1 (2018-01-01) 118 | ------------------ 119 | 120 | * Fixed issue #7 where having a ``str`` value for IPython's ``highlighting_style`` setting was not properly handled in ``prettyprinter``'s IPython integration, and raised an exception when trying to print data. 121 | 122 | 0.8.0 (2017-12-31) 123 | ------------------ 124 | 125 | Breaking changes: 126 | 127 | * by default, ``dict`` keys are printed in the default order (insertion order in CPython 3.6+). Previously they were sorted like in the ``pprint`` standard library module. To let the user control this, an additional keyword argument ``sort_dict_keys`` was added to ``cpprint``, ``pprint``, and ``pformat``. Pretty printer definitions can control ``dict`` key sorting with the ``PrettyContext`` instance passed to each pretty printer function. 128 | 129 | Non-breaking changes: 130 | 131 | * Improved performance of rendering colorized output by caching colors. 132 | * Added ``prettyprinter.pretty_repr`` that is assignable to ``__repr__`` dunder methods, so you don't need to write it separately from the pretty printer definition. 133 | * Deprecated use of ``PrettyContext.set`` in favor of less misleading ``PrettyContext.assoc`` 134 | * Defined pretty printing for instances of ``type``, i.e. classes. 135 | * Defined pretty printing for functions 136 | 137 | 138 | 139 | 0.7.0 (2017-12-23) 140 | ------------------ 141 | 142 | Breaking change: instances of lists, sets, frozensets, tuples and dicts will be truncated to 1000 elements by default when printing. 143 | 144 | * Added pretty printing definitions for ``dataclasses`` 145 | * Improved performance of splitting strings to multiple lines by ~15% 146 | * Added a maximum sequence length that applies to subclasses of lists, sets, frozensets, tuples and dicts. The default is 1000. There is a trailing comment that indicates the number of truncated elements. To remove truncation, you can set ``max_seq_len`` to ``None`` using ``set_default_config`` explained below. 147 | * Added ability to change the default global configuration using ``set_default_config``. The functions accepts zero to many keyword arguments and replaces those values in the global configuration with the ones provided. 148 | 149 | .. code:: python 150 | 151 | from prettyprinter import set_default_config 152 | 153 | set_default_config( 154 | style='dark', 155 | max_seq_len=1000, 156 | width=79, 157 | ribbon_width=71, 158 | depth=None, 159 | ) 160 | 161 | 0.6.0 (2017-12-21) 162 | ------------------ 163 | 164 | No backwards incompatible changes. 165 | 166 | * Added pretty printer definitions for the ``requests`` library. To use it, include ``'requests'`` in your ``install_extras`` call: ``prettyprinter.install_extras(include=['requests'])``. 167 | 168 | 0.5.0 (2017-12-21) 169 | ------------------ 170 | 171 | No backwards incompatible changes. 172 | 173 | * Added integration for the default Python shell 174 | * Wrote docs to explain integration with the default Python shell 175 | * Check ``install_extras`` arguments for unknown extras 176 | 177 | 0.4.0 (2017-12-14) 178 | ------------------ 179 | 180 | * Revised ``comment`` to accept both normal Python values and Docs, and reversed the argument order to be more Pythonic 181 | 182 | 0.3.0 (2017-12-12) 183 | ------------------ 184 | 185 | * Add ``set_default_style`` function, improve docs on working with a light background 186 | 187 | 0.2.0 (2017-12-12) 188 | ------------------ 189 | 190 | * Numerous API changes and improvements. 191 | 192 | 193 | 0.1.0 (2017-12-07) 194 | ------------------ 195 | 196 | * First release on PyPI. 197 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | 2 | MIT License 3 | 4 | Copyright (c) 2017, Tommi Kaikkonen 5 | 6 | Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: 7 | 8 | The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. 9 | 10 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. 11 | 12 | -------------------------------------------------------------------------------- /MANIFEST.in: -------------------------------------------------------------------------------- 1 | include AUTHORS.rst 2 | include CONTRIBUTING.rst 3 | include HISTORY.rst 4 | include LICENSE 5 | include README.rst 6 | 7 | recursive-include tests * 8 | recursive-exclude * __pycache__ 9 | recursive-exclude * *.py[co] 10 | 11 | recursive-include docs *.rst conf.py Makefile make.bat *.jpg *.png *.gif 12 | -------------------------------------------------------------------------------- /Makefile: -------------------------------------------------------------------------------- 1 | .PHONY: clean clean-test clean-pyc clean-build docs help 2 | .DEFAULT_GOAL := help 3 | define BROWSER_PYSCRIPT 4 | import os, webbrowser, sys 5 | try: 6 | from urllib import pathname2url 7 | except: 8 | from urllib.request import pathname2url 9 | 10 | webbrowser.open("file://" + pathname2url(os.path.abspath(sys.argv[1]))) 11 | endef 12 | export BROWSER_PYSCRIPT 13 | 14 | define PRINT_HELP_PYSCRIPT 15 | import re, sys 16 | 17 | for line in sys.stdin: 18 | match = re.match(r'^([a-zA-Z_-]+):.*?## (.*)$$', line) 19 | if match: 20 | target, help = match.groups() 21 | print("%-20s %s" % (target, help)) 22 | endef 23 | export PRINT_HELP_PYSCRIPT 24 | BROWSER := python -c "$$BROWSER_PYSCRIPT" 25 | 26 | help: 27 | @python -c "$$PRINT_HELP_PYSCRIPT" < $(MAKEFILE_LIST) 28 | 29 | clean: clean-build clean-pyc clean-test ## remove all build, test, coverage and Python artifacts 30 | 31 | 32 | clean-build: ## remove build artifacts 33 | rm -fr build/ 34 | rm -fr dist/ 35 | rm -fr .eggs/ 36 | find . -name '*.egg-info' -exec rm -fr {} + 37 | find . -name '*.egg' -exec rm -f {} + 38 | 39 | clean-pyc: ## remove Python file artifacts 40 | find . -name '*.pyc' -exec rm -f {} + 41 | find . -name '*.pyo' -exec rm -f {} + 42 | find . -name '*~' -exec rm -f {} + 43 | find . -name '__pycache__' -exec rm -fr {} + 44 | 45 | clean-test: ## remove test and coverage artifacts 46 | rm -fr .tox/ 47 | rm -f .coverage 48 | rm -fr htmlcov/ 49 | 50 | lint: ## check style with flake8 51 | flake8 prettyprinter tests 52 | 53 | test: ## run tests quickly with the default Python 54 | py.test 55 | 56 | 57 | test-all: ## run tests on every Python version with tox 58 | tox 59 | 60 | coverage: ## check code coverage quickly with the default Python 61 | coverage run --source prettyprinter -m pytest 62 | coverage report -m 63 | coverage html 64 | $(BROWSER) htmlcov/index.html 65 | 66 | docs: ## generate Sphinx HTML documentation, including API docs 67 | $(MAKE) -C docs clean 68 | $(MAKE) -C docs html 69 | $(BROWSER) docs/_build/html/index.html 70 | 71 | servedocs: docs ## compile the docs watching for changes 72 | watchmedo shell-command -p '*.rst;*.py' -c '$(MAKE) -C docs html' -R -D . 73 | 74 | release: clean ## package and upload a release 75 | python setup.py sdist upload 76 | python setup.py bdist_wheel upload 77 | 78 | dist: clean ## builds source and wheel package 79 | python setup.py sdist 80 | python setup.py bdist_wheel 81 | ls -l dist 82 | 83 | install: clean ## install the package to the active Python's site-packages 84 | python setup.py install 85 | -------------------------------------------------------------------------------- /README.rst: -------------------------------------------------------------------------------- 1 | ============= 2 | PrettyPrinter 3 | ============= 4 | 5 | Documentation_ 6 | 7 | Syntax-highlighting, declarative and composable pretty printer for Python 3.5+ 8 | 9 | .. code:: bash 10 | 11 | pip install prettyprinter 12 | 13 | - Drop in replacement for the standard library ``pprint``: just rename ``pprint`` to ``prettyprinter`` in your imports. 14 | - Uses a modified Wadler-Leijen layout algorithm for optimal formatting 15 | - Write pretty printers for your own types with a dead simple, declarative interface 16 | 17 | .. image:: prettyprinterscreenshot.png 18 | :alt: 19 | 20 | .. image:: ../prettyprinterscreenshot.png 21 | :alt: 22 | 23 | .. image:: prettyprinterlightscreenshot.png 24 | :alt: 25 | 26 | .. image:: ../prettyprinterlightscreenshot.png 27 | :alt: 28 | 29 | Pretty print common Python values: 30 | 31 | .. code:: python 32 | 33 | >>> from datetime import datetime 34 | >>> from prettyprinter import pprint 35 | >>> pprint({'beautiful output': datetime.now()}) 36 | { 37 | 'beautiful output': datetime.datetime( 38 | year=2017, 39 | month=12, 40 | day=12, 41 | hour=0, 42 | minute=43, 43 | second=4, 44 | microsecond=752094 45 | ) 46 | } 47 | 48 | As well as your own, without any manual string formatting: 49 | 50 | .. code:: python 51 | 52 | >>> class MyClass: 53 | ... def __init__(self, one, two): 54 | ... self.one = one 55 | ... self.two = two 56 | 57 | >>> from prettyprinter import register_pretty, pretty_call 58 | 59 | >>> @register_pretty(MyClass) 60 | ... def pretty_myclass(value, ctx): 61 | ... return pretty_call(ctx, MyClass, one=value.one, two=value.two) 62 | 63 | >>> pprint(MyClass((1, 2, 3), {'a': 1, 'b': 2})) 64 | MyClass(one=(1, 2, 3), two={'a': 1, 'b': 2}) 65 | 66 | >>> pprint({'beautiful output': datetime.now(), 'beautiful MyClass instance': MyClass((1, 2, 3), {'a': 1, 'b': 2})}) 67 | { 68 | 'beautiful MyClass instance': MyClass( 69 | one=(1, 2, 3), 70 | two={'a': 1, 'b': 2} 71 | ), 72 | 'beautiful output': datetime.datetime( 73 | year=2017, 74 | month=12, 75 | day=12, 76 | hour=0, 77 | minute=44, 78 | second=18, 79 | microsecond=384219 80 | ) 81 | } 82 | 83 | Comes packaged with the following pretty printer definitions, which you can enable by calling ``prettyprinter.install_extras()``: 84 | 85 | - ``datetime`` - (installed by default) 86 | - ``enum`` - (installed by default) 87 | - ``pytz`` - (installed by default) 88 | - ``dataclasses`` - any new class you create will be pretty printed automatically 89 | - ``attrs`` - pretty prints any new class you create with ``attrs`` 90 | - ``django`` - pretty prints your Models and QuerySets 91 | - ``numpy`` - pretty prints numpy scalars with explicit types 92 | - ``requests`` - pretty prints Requests, Responses, Sessions, and more from the ``requests`` library 93 | 94 | * Free software: MIT license 95 | * Documentation: Documentation_. 96 | 97 | .. _Documentation: https://prettyprinter.readthedocs.io 98 | -------------------------------------------------------------------------------- /docs/.gitignore: -------------------------------------------------------------------------------- 1 | /prettyprinter.rst 2 | /prettyprinter.*.rst 3 | /modules.rst 4 | -------------------------------------------------------------------------------- /docs/Makefile: -------------------------------------------------------------------------------- 1 | # Makefile for Sphinx documentation 2 | # 3 | 4 | # You can set these variables from the command line. 5 | SPHINXOPTS = 6 | SPHINXBUILD = sphinx-build 7 | PAPER = 8 | BUILDDIR = _build 9 | 10 | # User-friendly check for sphinx-build 11 | ifeq ($(shell which $(SPHINXBUILD) >/dev/null 2>&1; echo $$?), 1) 12 | $(error The '$(SPHINXBUILD)' command was not found. Make sure you have Sphinx installed, then set the SPHINXBUILD environment variable to point to the full path of the '$(SPHINXBUILD)' executable. Alternatively you can add the directory with the executable to your PATH. If you don't have Sphinx installed, grab it from http://sphinx-doc.org/) 13 | endif 14 | 15 | # Internal variables. 16 | PAPEROPT_a4 = -D latex_paper_size=a4 17 | PAPEROPT_letter = -D latex_paper_size=letter 18 | ALLSPHINXOPTS = -d $(BUILDDIR)/doctrees $(PAPEROPT_$(PAPER)) $(SPHINXOPTS) . 19 | # the i18n builder cannot share the environment and doctrees with the others 20 | I18NSPHINXOPTS = $(PAPEROPT_$(PAPER)) $(SPHINXOPTS) . 21 | 22 | .PHONY: help clean html dirhtml singlehtml pickle json htmlhelp qthelp devhelp epub latex latexpdf text man changes linkcheck doctest gettext 23 | 24 | help: 25 | @echo "Please use \`make ' where is one of" 26 | @echo " html to make standalone HTML files" 27 | @echo " dirhtml to make HTML files named index.html in directories" 28 | @echo " singlehtml to make a single large HTML file" 29 | @echo " pickle to make pickle files" 30 | @echo " json to make JSON files" 31 | @echo " htmlhelp to make HTML files and a HTML help project" 32 | @echo " qthelp to make HTML files and a qthelp project" 33 | @echo " devhelp to make HTML files and a Devhelp project" 34 | @echo " epub to make an epub" 35 | @echo " latex to make LaTeX files, you can set PAPER=a4 or PAPER=letter" 36 | @echo " latexpdf to make LaTeX files and run them through pdflatex" 37 | @echo " latexpdfja to make LaTeX files and run them through platex/dvipdfmx" 38 | @echo " text to make text files" 39 | @echo " man to make manual pages" 40 | @echo " texinfo to make Texinfo files" 41 | @echo " info to make Texinfo files and run them through makeinfo" 42 | @echo " gettext to make PO message catalogs" 43 | @echo " changes to make an overview of all changed/added/deprecated items" 44 | @echo " xml to make Docutils-native XML files" 45 | @echo " pseudoxml to make pseudoxml-XML files for display purposes" 46 | @echo " linkcheck to check all external links for integrity" 47 | @echo " doctest to run all doctests embedded in the documentation (if enabled)" 48 | 49 | clean: 50 | rm -rf $(BUILDDIR)/* 51 | 52 | html: 53 | $(SPHINXBUILD) -b html $(ALLSPHINXOPTS) $(BUILDDIR)/html 54 | @echo 55 | @echo "Build finished. The HTML pages are in $(BUILDDIR)/html." 56 | 57 | dirhtml: 58 | $(SPHINXBUILD) -b dirhtml $(ALLSPHINXOPTS) $(BUILDDIR)/dirhtml 59 | @echo 60 | @echo "Build finished. The HTML pages are in $(BUILDDIR)/dirhtml." 61 | 62 | singlehtml: 63 | $(SPHINXBUILD) -b singlehtml $(ALLSPHINXOPTS) $(BUILDDIR)/singlehtml 64 | @echo 65 | @echo "Build finished. The HTML page is in $(BUILDDIR)/singlehtml." 66 | 67 | pickle: 68 | $(SPHINXBUILD) -b pickle $(ALLSPHINXOPTS) $(BUILDDIR)/pickle 69 | @echo 70 | @echo "Build finished; now you can process the pickle files." 71 | 72 | json: 73 | $(SPHINXBUILD) -b json $(ALLSPHINXOPTS) $(BUILDDIR)/json 74 | @echo 75 | @echo "Build finished; now you can process the JSON files." 76 | 77 | htmlhelp: 78 | $(SPHINXBUILD) -b htmlhelp $(ALLSPHINXOPTS) $(BUILDDIR)/htmlhelp 79 | @echo 80 | @echo "Build finished; now you can run HTML Help Workshop with the" \ 81 | ".hhp project file in $(BUILDDIR)/htmlhelp." 82 | 83 | qthelp: 84 | $(SPHINXBUILD) -b qthelp $(ALLSPHINXOPTS) $(BUILDDIR)/qthelp 85 | @echo 86 | @echo "Build finished; now you can run "qcollectiongenerator" with the" \ 87 | ".qhcp project file in $(BUILDDIR)/qthelp, like this:" 88 | @echo "# qcollectiongenerator $(BUILDDIR)/qthelp/prettyprinter.qhcp" 89 | @echo "To view the help file:" 90 | @echo "# assistant -collectionFile $(BUILDDIR)/qthelp/prettyprinter.qhc" 91 | 92 | devhelp: 93 | $(SPHINXBUILD) -b devhelp $(ALLSPHINXOPTS) $(BUILDDIR)/devhelp 94 | @echo 95 | @echo "Build finished." 96 | @echo "To view the help file:" 97 | @echo "# mkdir -p $$HOME/.local/share/devhelp/prettyprinter" 98 | @echo "# ln -s $(BUILDDIR)/devhelp $$HOME/.local/share/devhelp/prettyprinter" 99 | @echo "# devhelp" 100 | 101 | epub: 102 | $(SPHINXBUILD) -b epub $(ALLSPHINXOPTS) $(BUILDDIR)/epub 103 | @echo 104 | @echo "Build finished. The epub file is in $(BUILDDIR)/epub." 105 | 106 | latex: 107 | $(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex 108 | @echo 109 | @echo "Build finished; the LaTeX files are in $(BUILDDIR)/latex." 110 | @echo "Run \`make' in that directory to run these through (pdf)latex" \ 111 | "(use \`make latexpdf' here to do that automatically)." 112 | 113 | latexpdf: 114 | $(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex 115 | @echo "Running LaTeX files through pdflatex..." 116 | $(MAKE) -C $(BUILDDIR)/latex all-pdf 117 | @echo "pdflatex finished; the PDF files are in $(BUILDDIR)/latex." 118 | 119 | latexpdfja: 120 | $(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex 121 | @echo "Running LaTeX files through platex and dvipdfmx..." 122 | $(MAKE) -C $(BUILDDIR)/latex all-pdf-ja 123 | @echo "pdflatex finished; the PDF files are in $(BUILDDIR)/latex." 124 | 125 | text: 126 | $(SPHINXBUILD) -b text $(ALLSPHINXOPTS) $(BUILDDIR)/text 127 | @echo 128 | @echo "Build finished. The text files are in $(BUILDDIR)/text." 129 | 130 | man: 131 | $(SPHINXBUILD) -b man $(ALLSPHINXOPTS) $(BUILDDIR)/man 132 | @echo 133 | @echo "Build finished. The manual pages are in $(BUILDDIR)/man." 134 | 135 | texinfo: 136 | $(SPHINXBUILD) -b texinfo $(ALLSPHINXOPTS) $(BUILDDIR)/texinfo 137 | @echo 138 | @echo "Build finished. The Texinfo files are in $(BUILDDIR)/texinfo." 139 | @echo "Run \`make' in that directory to run these through makeinfo" \ 140 | "(use \`make info' here to do that automatically)." 141 | 142 | info: 143 | $(SPHINXBUILD) -b texinfo $(ALLSPHINXOPTS) $(BUILDDIR)/texinfo 144 | @echo "Running Texinfo files through makeinfo..." 145 | make -C $(BUILDDIR)/texinfo info 146 | @echo "makeinfo finished; the Info files are in $(BUILDDIR)/texinfo." 147 | 148 | gettext: 149 | $(SPHINXBUILD) -b gettext $(I18NSPHINXOPTS) $(BUILDDIR)/locale 150 | @echo 151 | @echo "Build finished. The message catalogs are in $(BUILDDIR)/locale." 152 | 153 | changes: 154 | $(SPHINXBUILD) -b changes $(ALLSPHINXOPTS) $(BUILDDIR)/changes 155 | @echo 156 | @echo "The overview file is in $(BUILDDIR)/changes." 157 | 158 | linkcheck: 159 | $(SPHINXBUILD) -b linkcheck $(ALLSPHINXOPTS) $(BUILDDIR)/linkcheck 160 | @echo 161 | @echo "Link check complete; look for any errors in the above output " \ 162 | "or in $(BUILDDIR)/linkcheck/output.txt." 163 | 164 | doctest: 165 | $(SPHINXBUILD) -b doctest $(ALLSPHINXOPTS) $(BUILDDIR)/doctest 166 | @echo "Testing of doctests in the sources finished, look at the " \ 167 | "results in $(BUILDDIR)/doctest/output.txt." 168 | 169 | xml: 170 | $(SPHINXBUILD) -b xml $(ALLSPHINXOPTS) $(BUILDDIR)/xml 171 | @echo 172 | @echo "Build finished. The XML files are in $(BUILDDIR)/xml." 173 | 174 | pseudoxml: 175 | $(SPHINXBUILD) -b pseudoxml $(ALLSPHINXOPTS) $(BUILDDIR)/pseudoxml 176 | @echo 177 | @echo "Build finished. The pseudo-XML files are in $(BUILDDIR)/pseudoxml." 178 | -------------------------------------------------------------------------------- /docs/api_reference.rst: -------------------------------------------------------------------------------- 1 | API Reference 2 | ===================== 3 | 4 | .. automodule:: prettyprinter 5 | :members: 6 | :undoc-members: 7 | :show-inheritance: 8 | -------------------------------------------------------------------------------- /docs/authors.rst: -------------------------------------------------------------------------------- 1 | .. include:: ../AUTHORS.rst 2 | -------------------------------------------------------------------------------- /docs/conf.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # -*- coding: utf-8 -*- 3 | # 4 | # prettyprinter documentation build configuration file, created by 5 | # sphinx-quickstart on Tue Jul 9 22:26:36 2013. 6 | # 7 | # This file is execfile()d with the current directory set to its 8 | # containing dir. 9 | # 10 | # Note that not all possible configuration values are present in this 11 | # autogenerated file. 12 | # 13 | # All configuration values have a default; values that are commented out 14 | # serve to show the default. 15 | 16 | import sys 17 | import os 18 | 19 | # If extensions (or modules to document with autodoc) are in another 20 | # directory, add these directories to sys.path here. If the directory is 21 | # relative to the documentation root, use os.path.abspath to make it 22 | # absolute, like shown here. 23 | #sys.path.insert(0, os.path.abspath('.')) 24 | 25 | # Get the project root dir, which is the parent dir of this 26 | cwd = os.getcwd() 27 | project_root = os.path.dirname(cwd) 28 | 29 | # Insert the project root dir as the first element in the PYTHONPATH. 30 | # This lets us ensure that the source package is imported, and that its 31 | # version is used. 32 | sys.path.insert(0, project_root) 33 | 34 | import prettyprinter 35 | 36 | # -- General configuration --------------------------------------------- 37 | 38 | # If your documentation needs a minimal Sphinx version, state it here. 39 | #needs_sphinx = '1.0' 40 | 41 | # Add any Sphinx extension module names here, as strings. They can be 42 | # extensions coming with Sphinx (named 'sphinx.ext.*') or your custom ones. 43 | extensions = ['sphinx.ext.autodoc', 'sphinx.ext.viewcode'] 44 | 45 | # Add any paths that contain templates here, relative to this directory. 46 | templates_path = ['_templates'] 47 | 48 | # The suffix of source filenames. 49 | source_suffix = ['.rst', '.png'] 50 | 51 | # The encoding of source files. 52 | #source_encoding = 'utf-8-sig' 53 | 54 | # The master toctree document. 55 | master_doc = 'index' 56 | 57 | # General information about the project. 58 | project = u'PrettyPrinter' 59 | copyright = u"2017, Tommi Kaikkonen" 60 | 61 | # The version info for the project you're documenting, acts as replacement 62 | # for |version| and |release|, also used in various other places throughout 63 | # the built documents. 64 | # 65 | # The short X.Y version. 66 | version = prettyprinter.__version__ 67 | # The full version, including alpha/beta/rc tags. 68 | release = prettyprinter.__version__ 69 | 70 | # The language for content autogenerated by Sphinx. Refer to documentation 71 | # for a list of supported languages. 72 | #language = None 73 | 74 | # There are two options for replacing |today|: either, you set today to 75 | # some non-false value, then it is used: 76 | #today = '' 77 | # Else, today_fmt is used as the format for a strftime call. 78 | #today_fmt = '%B %d, %Y' 79 | 80 | # List of patterns, relative to source directory, that match files and 81 | # directories to ignore when looking for source files. 82 | exclude_patterns = ['_build'] 83 | 84 | # The reST default role (used for this markup: `text`) to use for all 85 | # documents. 86 | #default_role = None 87 | 88 | # If true, '()' will be appended to :func: etc. cross-reference text. 89 | #add_function_parentheses = True 90 | 91 | # If true, the current module name will be prepended to all description 92 | # unit titles (such as .. function::). 93 | #add_module_names = True 94 | 95 | # If true, sectionauthor and moduleauthor directives will be shown in the 96 | # output. They are ignored by default. 97 | #show_authors = False 98 | 99 | # The name of the Pygments (syntax highlighting) style to use. 100 | pygments_style = 'sphinx' 101 | 102 | # A list of ignored prefixes for module index sorting. 103 | #modindex_common_prefix = [] 104 | 105 | # If true, keep warnings as "system message" paragraphs in the built 106 | # documents. 107 | #keep_warnings = False 108 | 109 | 110 | # -- Options for HTML output ------------------------------------------- 111 | 112 | # The theme to use for HTML and HTML Help pages. See the documentation for 113 | # a list of builtin themes. 114 | html_theme = 'alabaster' 115 | 116 | # Theme options are theme-specific and customize the look and feel of a 117 | # theme further. For a list of options available for each theme, see the 118 | # documentation. 119 | #html_theme_options = {} 120 | 121 | # Add any paths that contain custom themes here, relative to this directory. 122 | #html_theme_path = [] 123 | 124 | # The name for this set of Sphinx documents. If None, it defaults to 125 | # " v documentation". 126 | #html_title = None 127 | 128 | # A shorter title for the navigation bar. Default is the same as 129 | # html_title. 130 | #html_short_title = None 131 | 132 | # The name of an image file (relative to this directory) to place at the 133 | # top of the sidebar. 134 | #html_logo = None 135 | 136 | # The name of an image file (within the static path) to use as favicon 137 | # of the docs. This file should be a Windows icon file (.ico) being 138 | # 16x16 or 32x32 pixels large. 139 | #html_favicon = None 140 | 141 | # Add any paths that contain custom static files (such as style sheets) 142 | # here, relative to this directory. They are copied after the builtin 143 | # static files, so a file named "default.css" will overwrite the builtin 144 | # "default.css". 145 | html_static_path = [ 146 | '../prettyprinterscreenshot.png', 147 | '../prettyprinterlightscreenshot.png' 148 | ] 149 | 150 | # If not '', a 'Last updated on:' timestamp is inserted at every page 151 | # bottom, using the given strftime format. 152 | #html_last_updated_fmt = '%b %d, %Y' 153 | 154 | # If true, SmartyPants will be used to convert quotes and dashes to 155 | # typographically correct entities. 156 | #html_use_smartypants = True 157 | 158 | # Custom sidebar templates, maps document names to template names. 159 | #html_sidebars = {} 160 | 161 | # Additional templates that should be rendered to pages, maps page names 162 | # to template names. 163 | #html_additional_pages = {} 164 | 165 | # If false, no module index is generated. 166 | #html_domain_indices = True 167 | 168 | # If false, no index is generated. 169 | #html_use_index = True 170 | 171 | # If true, the index is split into individual pages for each letter. 172 | #html_split_index = False 173 | 174 | # If true, links to the reST sources are added to the pages. 175 | #html_show_sourcelink = True 176 | 177 | # If true, "Created using Sphinx" is shown in the HTML footer. 178 | # Default is True. 179 | #html_show_sphinx = True 180 | 181 | # If true, "(C) Copyright ..." is shown in the HTML footer. 182 | # Default is True. 183 | #html_show_copyright = True 184 | 185 | # If true, an OpenSearch description file will be output, and all pages 186 | # will contain a tag referring to it. The value of this option 187 | # must be the base URL from which the finished HTML is served. 188 | #html_use_opensearch = '' 189 | 190 | # This is the file name suffix for HTML files (e.g. ".xhtml"). 191 | #html_file_suffix = None 192 | 193 | # Output file base name for HTML help builder. 194 | htmlhelp_basename = 'prettyprinterdoc' 195 | 196 | 197 | # -- Options for LaTeX output ------------------------------------------ 198 | 199 | latex_elements = { 200 | # The paper size ('letterpaper' or 'a4paper'). 201 | #'papersize': 'letterpaper', 202 | 203 | # The font size ('10pt', '11pt' or '12pt'). 204 | #'pointsize': '10pt', 205 | 206 | # Additional stuff for the LaTeX preamble. 207 | #'preamble': '', 208 | } 209 | 210 | # Grouping the document tree into LaTeX files. List of tuples 211 | # (source start file, target name, title, author, documentclass 212 | # [howto/manual]). 213 | latex_documents = [ 214 | ('index', 'prettyprinter.tex', 215 | u'PrettyPrinter Documentation', 216 | u'Tommi Kaikkonen', 'manual'), 217 | ] 218 | 219 | # The name of an image file (relative to this directory) to place at 220 | # the top of the title page. 221 | #latex_logo = None 222 | 223 | # For "manual" documents, if this is true, then toplevel headings 224 | # are parts, not chapters. 225 | #latex_use_parts = False 226 | 227 | # If true, show page references after internal links. 228 | #latex_show_pagerefs = False 229 | 230 | # If true, show URL addresses after external links. 231 | #latex_show_urls = False 232 | 233 | # Documents to append as an appendix to all manuals. 234 | #latex_appendices = [] 235 | 236 | # If false, no module index is generated. 237 | #latex_domain_indices = True 238 | 239 | 240 | # -- Options for manual page output ------------------------------------ 241 | 242 | # One entry per manual page. List of tuples 243 | # (source start file, name, description, authors, manual section). 244 | man_pages = [ 245 | ('index', 'prettyprinter', 246 | u'PrettyPrinter Documentation', 247 | [u'Tommi Kaikkonen'], 1) 248 | ] 249 | 250 | # If true, show URL addresses after external links. 251 | #man_show_urls = False 252 | 253 | 254 | # -- Options for Texinfo output ---------------------------------------- 255 | 256 | # Grouping the document tree into Texinfo files. List of tuples 257 | # (source start file, target name, title, author, 258 | # dir menu entry, description, category) 259 | texinfo_documents = [ 260 | ('index', 'prettyprinter', 261 | u'PrettyPrinter Documentation', 262 | u'Tommi Kaikkonen', 263 | 'prettyprinter', 264 | 'One line description of project.', 265 | 'Miscellaneous'), 266 | ] 267 | 268 | # Documents to append as an appendix to all manuals. 269 | #texinfo_appendices = [] 270 | 271 | # If false, no module index is generated. 272 | #texinfo_domain_indices = True 273 | 274 | # How to display URL addresses: 'footnote', 'no', or 'inline'. 275 | #texinfo_show_urls = 'footnote' 276 | 277 | # If true, do not generate a @detailmenu in the "Top" node's menu. 278 | #texinfo_no_detailmenu = False 279 | -------------------------------------------------------------------------------- /docs/history.rst: -------------------------------------------------------------------------------- 1 | .. include:: ../HISTORY.rst 2 | -------------------------------------------------------------------------------- /docs/index.rst: -------------------------------------------------------------------------------- 1 | Welcome to PrettyPrinter's documentation! 2 | ========================================= 3 | 4 | .. include:: ../README.rst 5 | 6 | User Guide 7 | ---------- 8 | 9 | .. toctree:: 10 | :maxdepth: 2 11 | 12 | usage 13 | 14 | API Reference 15 | ------------- 16 | 17 | .. toctree:: 18 | :maxdepth: 2 19 | 20 | api_reference 21 | 22 | Meta 23 | ---- 24 | .. toctree:: 25 | :maxdepth: 1 26 | 27 | authors 28 | history 29 | -------------------------------------------------------------------------------- /docs/make.bat: -------------------------------------------------------------------------------- 1 | @ECHO OFF 2 | 3 | REM Command file for Sphinx documentation 4 | 5 | if "%SPHINXBUILD%" == "" ( 6 | set SPHINXBUILD=sphinx-build 7 | ) 8 | set BUILDDIR=_build 9 | set ALLSPHINXOPTS=-d %BUILDDIR%/doctrees %SPHINXOPTS% . 10 | set I18NSPHINXOPTS=%SPHINXOPTS% . 11 | if NOT "%PAPER%" == "" ( 12 | set ALLSPHINXOPTS=-D latex_paper_size=%PAPER% %ALLSPHINXOPTS% 13 | set I18NSPHINXOPTS=-D latex_paper_size=%PAPER% %I18NSPHINXOPTS% 14 | ) 15 | 16 | if "%1" == "" goto help 17 | 18 | if "%1" == "help" ( 19 | :help 20 | echo.Please use `make ^` where ^ is one of 21 | echo. html to make standalone HTML files 22 | echo. dirhtml to make HTML files named index.html in directories 23 | echo. singlehtml to make a single large HTML file 24 | echo. pickle to make pickle files 25 | echo. json to make JSON files 26 | echo. htmlhelp to make HTML files and a HTML help project 27 | echo. qthelp to make HTML files and a qthelp project 28 | echo. devhelp to make HTML files and a Devhelp project 29 | echo. epub to make an epub 30 | echo. latex to make LaTeX files, you can set PAPER=a4 or PAPER=letter 31 | echo. text to make text files 32 | echo. man to make manual pages 33 | echo. texinfo to make Texinfo files 34 | echo. gettext to make PO message catalogs 35 | echo. changes to make an overview over all changed/added/deprecated items 36 | echo. xml to make Docutils-native XML files 37 | echo. pseudoxml to make pseudoxml-XML files for display purposes 38 | echo. linkcheck to check all external links for integrity 39 | echo. doctest to run all doctests embedded in the documentation if enabled 40 | goto end 41 | ) 42 | 43 | if "%1" == "clean" ( 44 | for /d %%i in (%BUILDDIR%\*) do rmdir /q /s %%i 45 | del /q /s %BUILDDIR%\* 46 | goto end 47 | ) 48 | 49 | 50 | %SPHINXBUILD% 2> nul 51 | if errorlevel 9009 ( 52 | echo. 53 | echo.The 'sphinx-build' command was not found. Make sure you have Sphinx 54 | echo.installed, then set the SPHINXBUILD environment variable to point 55 | echo.to the full path of the 'sphinx-build' executable. Alternatively you 56 | echo.may add the Sphinx directory to PATH. 57 | echo. 58 | echo.If you don't have Sphinx installed, grab it from 59 | echo.http://sphinx-doc.org/ 60 | exit /b 1 61 | ) 62 | 63 | if "%1" == "html" ( 64 | %SPHINXBUILD% -b html %ALLSPHINXOPTS% %BUILDDIR%/html 65 | if errorlevel 1 exit /b 1 66 | echo. 67 | echo.Build finished. The HTML pages are in %BUILDDIR%/html. 68 | goto end 69 | ) 70 | 71 | if "%1" == "dirhtml" ( 72 | %SPHINXBUILD% -b dirhtml %ALLSPHINXOPTS% %BUILDDIR%/dirhtml 73 | if errorlevel 1 exit /b 1 74 | echo. 75 | echo.Build finished. The HTML pages are in %BUILDDIR%/dirhtml. 76 | goto end 77 | ) 78 | 79 | if "%1" == "singlehtml" ( 80 | %SPHINXBUILD% -b singlehtml %ALLSPHINXOPTS% %BUILDDIR%/singlehtml 81 | if errorlevel 1 exit /b 1 82 | echo. 83 | echo.Build finished. The HTML pages are in %BUILDDIR%/singlehtml. 84 | goto end 85 | ) 86 | 87 | if "%1" == "pickle" ( 88 | %SPHINXBUILD% -b pickle %ALLSPHINXOPTS% %BUILDDIR%/pickle 89 | if errorlevel 1 exit /b 1 90 | echo. 91 | echo.Build finished; now you can process the pickle files. 92 | goto end 93 | ) 94 | 95 | if "%1" == "json" ( 96 | %SPHINXBUILD% -b json %ALLSPHINXOPTS% %BUILDDIR%/json 97 | if errorlevel 1 exit /b 1 98 | echo. 99 | echo.Build finished; now you can process the JSON files. 100 | goto end 101 | ) 102 | 103 | if "%1" == "htmlhelp" ( 104 | %SPHINXBUILD% -b htmlhelp %ALLSPHINXOPTS% %BUILDDIR%/htmlhelp 105 | if errorlevel 1 exit /b 1 106 | echo. 107 | echo.Build finished; now you can run HTML Help Workshop with the ^ 108 | .hhp project file in %BUILDDIR%/htmlhelp. 109 | goto end 110 | ) 111 | 112 | if "%1" == "qthelp" ( 113 | %SPHINXBUILD% -b qthelp %ALLSPHINXOPTS% %BUILDDIR%/qthelp 114 | if errorlevel 1 exit /b 1 115 | echo. 116 | echo.Build finished; now you can run "qcollectiongenerator" with the ^ 117 | .qhcp project file in %BUILDDIR%/qthelp, like this: 118 | echo.^> qcollectiongenerator %BUILDDIR%\qthelp\prettyprinter.qhcp 119 | echo.To view the help file: 120 | echo.^> assistant -collectionFile %BUILDDIR%\qthelp\prettyprinter.ghc 121 | goto end 122 | ) 123 | 124 | if "%1" == "devhelp" ( 125 | %SPHINXBUILD% -b devhelp %ALLSPHINXOPTS% %BUILDDIR%/devhelp 126 | if errorlevel 1 exit /b 1 127 | echo. 128 | echo.Build finished. 129 | goto end 130 | ) 131 | 132 | if "%1" == "epub" ( 133 | %SPHINXBUILD% -b epub %ALLSPHINXOPTS% %BUILDDIR%/epub 134 | if errorlevel 1 exit /b 1 135 | echo. 136 | echo.Build finished. The epub file is in %BUILDDIR%/epub. 137 | goto end 138 | ) 139 | 140 | if "%1" == "latex" ( 141 | %SPHINXBUILD% -b latex %ALLSPHINXOPTS% %BUILDDIR%/latex 142 | if errorlevel 1 exit /b 1 143 | echo. 144 | echo.Build finished; the LaTeX files are in %BUILDDIR%/latex. 145 | goto end 146 | ) 147 | 148 | if "%1" == "latexpdf" ( 149 | %SPHINXBUILD% -b latex %ALLSPHINXOPTS% %BUILDDIR%/latex 150 | cd %BUILDDIR%/latex 151 | make all-pdf 152 | cd %BUILDDIR%/.. 153 | echo. 154 | echo.Build finished; the PDF files are in %BUILDDIR%/latex. 155 | goto end 156 | ) 157 | 158 | if "%1" == "latexpdfja" ( 159 | %SPHINXBUILD% -b latex %ALLSPHINXOPTS% %BUILDDIR%/latex 160 | cd %BUILDDIR%/latex 161 | make all-pdf-ja 162 | cd %BUILDDIR%/.. 163 | echo. 164 | echo.Build finished; the PDF files are in %BUILDDIR%/latex. 165 | goto end 166 | ) 167 | 168 | if "%1" == "text" ( 169 | %SPHINXBUILD% -b text %ALLSPHINXOPTS% %BUILDDIR%/text 170 | if errorlevel 1 exit /b 1 171 | echo. 172 | echo.Build finished. The text files are in %BUILDDIR%/text. 173 | goto end 174 | ) 175 | 176 | if "%1" == "man" ( 177 | %SPHINXBUILD% -b man %ALLSPHINXOPTS% %BUILDDIR%/man 178 | if errorlevel 1 exit /b 1 179 | echo. 180 | echo.Build finished. The manual pages are in %BUILDDIR%/man. 181 | goto end 182 | ) 183 | 184 | if "%1" == "texinfo" ( 185 | %SPHINXBUILD% -b texinfo %ALLSPHINXOPTS% %BUILDDIR%/texinfo 186 | if errorlevel 1 exit /b 1 187 | echo. 188 | echo.Build finished. The Texinfo files are in %BUILDDIR%/texinfo. 189 | goto end 190 | ) 191 | 192 | if "%1" == "gettext" ( 193 | %SPHINXBUILD% -b gettext %I18NSPHINXOPTS% %BUILDDIR%/locale 194 | if errorlevel 1 exit /b 1 195 | echo. 196 | echo.Build finished. The message catalogs are in %BUILDDIR%/locale. 197 | goto end 198 | ) 199 | 200 | if "%1" == "changes" ( 201 | %SPHINXBUILD% -b changes %ALLSPHINXOPTS% %BUILDDIR%/changes 202 | if errorlevel 1 exit /b 1 203 | echo. 204 | echo.The overview file is in %BUILDDIR%/changes. 205 | goto end 206 | ) 207 | 208 | if "%1" == "linkcheck" ( 209 | %SPHINXBUILD% -b linkcheck %ALLSPHINXOPTS% %BUILDDIR%/linkcheck 210 | if errorlevel 1 exit /b 1 211 | echo. 212 | echo.Link check complete; look for any errors in the above output ^ 213 | or in %BUILDDIR%/linkcheck/output.txt. 214 | goto end 215 | ) 216 | 217 | if "%1" == "doctest" ( 218 | %SPHINXBUILD% -b doctest %ALLSPHINXOPTS% %BUILDDIR%/doctest 219 | if errorlevel 1 exit /b 1 220 | echo. 221 | echo.Testing of doctests in the sources finished, look at the ^ 222 | results in %BUILDDIR%/doctest/output.txt. 223 | goto end 224 | ) 225 | 226 | if "%1" == "xml" ( 227 | %SPHINXBUILD% -b xml %ALLSPHINXOPTS% %BUILDDIR%/xml 228 | if errorlevel 1 exit /b 1 229 | echo. 230 | echo.Build finished. The XML files are in %BUILDDIR%/xml. 231 | goto end 232 | ) 233 | 234 | if "%1" == "pseudoxml" ( 235 | %SPHINXBUILD% -b pseudoxml %ALLSPHINXOPTS% %BUILDDIR%/pseudoxml 236 | if errorlevel 1 exit /b 1 237 | echo. 238 | echo.Build finished. The pseudo-XML files are in %BUILDDIR%/pseudoxml. 239 | goto end 240 | ) 241 | 242 | :end 243 | -------------------------------------------------------------------------------- /docs/usage.rst: -------------------------------------------------------------------------------- 1 | ===== 2 | Usage 3 | ===== 4 | 5 | Install the package with ``pip``: 6 | 7 | .. code:: bash 8 | 9 | pip install prettyprinter 10 | 11 | Then, instead of 12 | 13 | .. code:: python 14 | 15 | from pprint import pprint 16 | 17 | do 18 | 19 | .. code:: python 20 | 21 | from prettyprinter import cpprint 22 | 23 | for colored output. For colorless output, remove the ``c`` prefix from the function name: 24 | 25 | .. code:: python 26 | 27 | from prettyprinter import pprint 28 | 29 | 30 | 31 | Usage in Python code 32 | -------------------- 33 | 34 | Call :func:`~prettyprinter.cpprint` for colored output or :func:`~prettyprinter.pprint` for uncolored output, just like ``pprint.pprint``: 35 | 36 | .. code:: python 37 | 38 | >>> from prettyprinter import cpprint 39 | >>> cpprint({'a': 1, 'b': 2}) 40 | {'a': 1, 'b': 2} 41 | 42 | The default style is meant for a dark background. If you're on a light background, or want to set your own theme, you may do so with :func:`~prettyprinter.set_default_style` 43 | 44 | .. code:: python 45 | 46 | >>> from prettyprinter import set_default_style 47 | >>> set_default_style('light') 48 | 49 | Possible values are ``'light'``, ``'dark'``, and any subclass of ``pygments.styles.Style``. 50 | 51 | ++++++++++++++++++++++++++++++++++++++++++++++++++++++++ 52 | Adding a pretty printer function to the global namespace 53 | ++++++++++++++++++++++++++++++++++++++++++++++++++++++++ 54 | 55 | If you're so inclined, you could add :func:`~prettyprinter.cpprint` to the global namespace in your application so you can use it in a similar way as the built in ``print`` function: 56 | 57 | .. code:: python 58 | 59 | import builtins 60 | import prettyprinter 61 | builtins.pretty = prettyprinter.cpprint 62 | 63 | pretty([1, 2, 3]) 64 | 65 | You'll want to add this to a file that is executed during application initialization. 66 | 67 | 68 | Usage with IPython 69 | ------------------ 70 | 71 | You can use prettyprinter with IPython so that values in the REPL will be printed with ``prettyprinter`` using syntax highlighting. You need to call ``prettyprinter`` initialization functions at the start of an IPython session, which IPython facilitates with `profile startup files`_. To initialize prettyprinter in your default profile, add and edit a new startup file with the following commands: 72 | 73 | .. code:: bash 74 | 75 | touch "`ipython locate profile default`/startup/init_prettyprinter.py" 76 | nano "`ipython locate profile default`/startup/init_prettyprinter.py" 77 | 78 | 79 | The code in this file will be run upon entering the shell. Add these lines and comment out any extra packages you don't need: 80 | 81 | .. code:: python 82 | 83 | # Specify syntax higlighting theme in IPython; 84 | # will be picked up by prettyprinter. 85 | from pygments import styles 86 | 87 | # For light terminal backgrounds. 88 | from prettyprinter.color import GitHubLightStyle 89 | ipy = get_ipython() 90 | ipy.colors = 'LightBG' 91 | ipy.highlighting_style = GitHubLightStyle 92 | 93 | # For dark terminal background. 94 | ipy = get_ipython() 95 | ipy.colors = 'linux' 96 | ipy.highlighting_style = styles.get_style_by_name('monokai') 97 | 98 | import prettyprinter 99 | 100 | prettyprinter.install_extras( 101 | # Comment out any packages you are not using. 102 | include=[ 103 | 'ipython', 104 | 'ipython_repr_pretty', 105 | 'attrs', 106 | 'django', 107 | 'requests', 108 | 'dataclasses', 109 | ], 110 | warn_on_error=True 111 | ) 112 | 113 | 114 | Usage in the default Python shell 115 | --------------------------------- 116 | 117 | PrettyPrinter integrates with the default shell by overriding ``sys.displayhook``, so that values evaluated in the prompt will be printed using PrettyPrinter. The integration is set up as follows: 118 | 119 | .. code:: python 120 | 121 | >>> from prettyprinter import install_extras 122 | >>> install_extras(['python']) 123 | >>> {'a': 1, 'b': 2} 124 | {'a': 1, 'b': 2} # <- this will be colored when run in a terminal. 125 | 126 | If you don't want to run this every time you open a shell, create a Python startup file that executes the above statements and point the environment variable ``PYTHONSTARTUP`` to that file in your shell initialization file (such as ``~/.bashrc``), and rerun ``~/.bashrc`` to assign the correct ``PYTHONSTARTUP`` value in your current shell session. Here's a bash script to do that for you: 127 | 128 | .. code:: bash 129 | 130 | echo 'import prettyprinter; prettyprinter.install_extras(["python"])\n' >> ~/python_startup.py 131 | echo "\nexport PYTHONSTARTUP=~/python_startup.py" >> ~/.bashrc 132 | source ~/.bashrc 133 | 134 | If you're using a light background in your terminal, run this to add a line to the Python startup file to change the color theme PrettyPrinter uses: 135 | 136 | .. code:: bash 137 | 138 | echo '\nprettyprinter.set_default_style("light")' >> ~/python_startup.py 139 | 140 | 141 | Then, after starting the ``python`` shell, 142 | 143 | .. code:: bash 144 | 145 | python 146 | 147 | values evaluated in the shell should be printed with PrettyPrinter without any other setup. 148 | 149 | .. code:: python 150 | 151 | >>> {'a': 1, 'b': 2} 152 | {'a': 1, 'b': 2} # <- the output should be colored when run in a terminal. 153 | 154 | 155 | Pretty printing your own types 156 | ------------------------------ 157 | 158 | Given a custom class: 159 | 160 | .. code:: python 161 | 162 | class MyClass(object): 163 | def __init__(self, one, two): 164 | self.one = one 165 | self.two = two 166 | 167 | 168 | You can register a pretty printer: 169 | 170 | .. code:: python 171 | 172 | from prettyprinter import register_pretty, pretty_call 173 | 174 | @register_pretty(MyClass) 175 | def pretty_myclass(value, ctx): 176 | return pretty_call( 177 | ctx, 178 | MyClass, 179 | one=value.one, 180 | two=value.two 181 | ) 182 | 183 | 184 | To get an output like this with simple data: 185 | 186 | .. code:: python 187 | 188 | >>> prettyprinter.pprint(MyClass(1, 2)) 189 | MyClass(one=1, two=2) 190 | 191 | The real utility is in how nested data pretty printing is handled for you, and how the function call is broken to multiple lines for easier legibility: 192 | 193 | .. code:: python 194 | 195 | >>> prettyprinter.pprint(MyClass({'abc': 1, 'defg': 2, 'hijk': 3}, [1, 2])) 196 | MyClass( 197 | one={ 198 | 'abc': 1, 199 | 'defg': 2, 200 | 'hijk': 3 201 | }, 202 | two=[1, 2] 203 | ) 204 | 205 | :func:`@register_pretty ` is a decorator that takes the type to register. Internally, :class:`functools.singledispatch` is used to handle dispatch to the correct pretty printer. This means that any subclasses will also use the same printer. 206 | 207 | The decorated function must accept exactly two positional arguments: 208 | 209 | - ``value`` to pretty print, and 210 | - ``ctx``, a context value. 211 | 212 | In most cases, you don't need need to do anything with the context, except pass it along in nested calls. It can be used to affect rendering of nested data. 213 | 214 | The function must return a :class:`~prettyprinter.doc.Doc`, which is either an instance of :class:`~prettyprinter.doc.Doc` or a :class:`str`. :func:`~prettyprinter.pretty_call` returns a :class:`~prettyprinter.doc.Doc` that represents a function call. Given an arbitrary context ``ctx`` 215 | 216 | .. code:: python 217 | 218 | pretty_call(ctx, round, 1.5) 219 | 220 | Will be printed out as 221 | 222 | .. code:: python 223 | 224 | round(1.5) 225 | 226 | with syntax highlighting. 227 | 228 | 229 | .. _`profile startup files`: http://ipython.readthedocs.io/en/stable/config/intro.html#profiles 230 | .. _colorful: https://github.com/timofurrer/colorful 231 | .. _pygments: https://pypi.python.org/pypi/Pygments 232 | -------------------------------------------------------------------------------- /prettyprinter/__init__.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | 3 | """Top-level package for prettyprinter.""" 4 | 5 | __author__ = """Tommi Kaikkonen""" 6 | __email__ = 'kaikkonentommi@gmail.com' 7 | __version__ = '0.18.0' 8 | 9 | from io import StringIO 10 | from importlib import import_module 11 | from types import MappingProxyType 12 | import sys 13 | import warnings 14 | 15 | from pprint import isrecursive, isreadable, saferepr 16 | from .color import colored_render_to_stream, set_default_style 17 | from .prettyprinter import ( 18 | is_registered, 19 | python_to_sdocs, 20 | register_pretty, 21 | pretty_call, 22 | pretty_call_alt, 23 | comment, 24 | trailing_comment, 25 | ) 26 | from .render import default_render_to_stream 27 | 28 | # Registers standard library types 29 | # as a side effect 30 | import prettyprinter.pretty_stdlib # noqa 31 | 32 | 33 | __all__ = [ 34 | 'cpprint', 35 | 'pprint', 36 | 'pformat', 37 | 'pretty_repr', 38 | 'install_extras', 39 | 'set_default_style', 40 | 'set_default_config', 41 | 'get_default_config', 42 | 'register_pretty', 43 | 'pretty_call', 44 | 'pretty_call_alt', 45 | 'trailing_comment', 46 | 'comment', 47 | 'python_to_sdocs', 48 | 'default_render_to_stream', 49 | 'PrettyPrinter', 50 | 'saferepr', 51 | 'isreadable', 52 | 'isrecursive', 53 | ] 54 | 55 | 56 | class UnsetSentinel: 57 | def __repr__(self): 58 | return 'UNSET' 59 | 60 | __str__ = __repr__ 61 | 62 | 63 | _UNSET_SENTINEL = UnsetSentinel() 64 | 65 | 66 | _default_config = { 67 | 'indent': 4, 68 | 'width': 79, 69 | 'ribbon_width': 71, 70 | 'depth': None, 71 | 'max_seq_len': 1000, 72 | 'sort_dict_keys': False, 73 | } 74 | 75 | 76 | def _merge_defaults( 77 | *, indent, width, depth, ribbon_width, max_seq_len, sort_dict_keys 78 | ): 79 | kwargs = locals() 80 | return {key: kwargs[key] if kwargs[key] is not _UNSET_SENTINEL else default 81 | for key, default in _default_config.items()} 82 | 83 | 84 | def get_default_config(): 85 | """Returns a read-only view of the current configuration""" 86 | return MappingProxyType(_default_config) 87 | 88 | 89 | class PrettyPrinter: 90 | def __init__(self, *args, **kwargs): 91 | self._args = args 92 | self._kwargs = kwargs 93 | 94 | def pprint(self, object): 95 | pprint(*self._args, **self._kwargs) 96 | 97 | def pformat(self, object): 98 | return pformat(*self._args, **self._kwargs) 99 | 100 | def isrecursive(self, object): 101 | return isrecursive(object) 102 | 103 | def isreadable(self, object): 104 | return isreadable(object) 105 | 106 | def format(self, object): 107 | raise NotImplementedError 108 | 109 | 110 | def pformat( 111 | object, 112 | indent=_UNSET_SENTINEL, 113 | width=_UNSET_SENTINEL, 114 | depth=_UNSET_SENTINEL, 115 | *, 116 | ribbon_width=_UNSET_SENTINEL, 117 | max_seq_len=_UNSET_SENTINEL, 118 | compact=_UNSET_SENTINEL, 119 | sort_dict_keys=_UNSET_SENTINEL 120 | ): 121 | """ 122 | Returns a pretty printed representation of the object as a ``str``. 123 | Accepts the same parameters as :func:`~prettyprinter.pprint`. 124 | The output is not colored. 125 | """ 126 | sdocs = python_to_sdocs( 127 | object, 128 | **_merge_defaults( 129 | indent=indent, 130 | width=width, 131 | depth=depth, 132 | ribbon_width=ribbon_width, 133 | max_seq_len=max_seq_len, 134 | sort_dict_keys=sort_dict_keys, 135 | ) 136 | ) 137 | stream = StringIO() 138 | default_render_to_stream(stream, sdocs) 139 | return stream.getvalue() 140 | 141 | 142 | def pprint( 143 | object, 144 | stream=_UNSET_SENTINEL, 145 | indent=_UNSET_SENTINEL, 146 | width=_UNSET_SENTINEL, 147 | depth=_UNSET_SENTINEL, 148 | *, 149 | compact=False, 150 | ribbon_width=_UNSET_SENTINEL, 151 | max_seq_len=_UNSET_SENTINEL, 152 | sort_dict_keys=_UNSET_SENTINEL, 153 | end='\n' 154 | ): 155 | """Pretty print a Python value ``object`` to ``stream``, 156 | which defaults to ``sys.stdout``. The output will not be colored. 157 | 158 | :param indent: number of spaces to add for each level of nesting. 159 | :param stream: the output stream, defaults to ``sys.stdout`` 160 | :param width: a soft maximum allowed number of columns in the output, 161 | which the layout algorithm attempts to stay under. 162 | :param depth: maximum depth to print nested structures 163 | :param ribbon_width: a soft maximum allowed number of columns in the output, 164 | after indenting the line 165 | :param max_seq_len: a maximum sequence length that applies to subclasses of 166 | lists, sets, frozensets, tuples and dicts. A trailing 167 | comment that indicates the number of truncated elements. 168 | Setting max_seq_len to ``None`` disables truncation. 169 | :param sort_dict_keys: a ``bool`` value indicating if dict keys should be 170 | sorted in the output. Defaults to ``False``, in 171 | which case the default order is used, which is the 172 | insertion order in CPython 3.6+. 173 | """ 174 | sdocs = python_to_sdocs( 175 | object, 176 | **_merge_defaults( 177 | indent=indent, 178 | width=width, 179 | depth=depth, 180 | ribbon_width=ribbon_width, 181 | max_seq_len=max_seq_len, 182 | sort_dict_keys=sort_dict_keys, 183 | ) 184 | ) 185 | stream = ( 186 | # This is not in _default_config in case 187 | # sys.stdout changes. 188 | sys.stdout 189 | if stream is _UNSET_SENTINEL 190 | else stream 191 | ) 192 | 193 | default_render_to_stream(stream, sdocs) 194 | if end: 195 | stream.write(end) 196 | 197 | 198 | def cpprint( 199 | object, 200 | stream=_UNSET_SENTINEL, 201 | indent=_UNSET_SENTINEL, 202 | width=_UNSET_SENTINEL, 203 | depth=_UNSET_SENTINEL, 204 | *, 205 | compact=False, 206 | ribbon_width=_UNSET_SENTINEL, 207 | max_seq_len=_UNSET_SENTINEL, 208 | sort_dict_keys=_UNSET_SENTINEL, 209 | style=None, 210 | end='\n' 211 | ): 212 | """Pretty print a Python value ``object`` to ``stream``, 213 | which defaults to sys.stdout. The output will be colored and 214 | syntax highlighted. 215 | 216 | :param indent: number of spaces to add for each level of nesting. 217 | :param stream: the output stream, defaults to sys.stdout 218 | :param width: a soft maximum allowed number of columns in the output, 219 | which the layout algorithm attempts to stay under. 220 | :param depth: maximum depth to print nested structures 221 | :param ribbon_width: a soft maximum allowed number of columns in the output, 222 | after indenting the line 223 | :param max_seq_len: a maximum sequence length that applies to subclasses of 224 | lists, sets, frozensets, tuples and dicts. A trailing 225 | comment that indicates the number of truncated elements. 226 | Setting max_seq_len to ``None`` disables truncation. 227 | :param sort_dict_keys: a ``bool`` value indicating if dict keys should be 228 | sorted in the output. Defaults to ``False``, in 229 | which case the default order is used, which is the 230 | insertion order in CPython 3.6+. 231 | :param style: one of ``'light'``, ``'dark'`` or a subclass 232 | of ``pygments.styles.Style``. If omitted, 233 | will use the default style. If the default style 234 | is not changed by the user with :func:`~prettyprinter.set_default_style`, 235 | the default is ``'dark'``. 236 | """ 237 | sdocs = python_to_sdocs( 238 | object, 239 | **_merge_defaults( 240 | indent=indent, 241 | width=width, 242 | depth=depth, 243 | ribbon_width=ribbon_width, 244 | max_seq_len=max_seq_len, 245 | sort_dict_keys=sort_dict_keys, 246 | ) 247 | ) 248 | stream = ( 249 | # This is not in _default_config in case 250 | # sys.stdout changes. 251 | sys.stdout 252 | if stream is _UNSET_SENTINEL 253 | else stream 254 | ) 255 | colored_render_to_stream(stream, sdocs, style=style) 256 | if end: 257 | stream.write(end) 258 | 259 | 260 | ALL_EXTRAS = frozenset([ 261 | 'attrs', 262 | 'django', 263 | 'ipython', 264 | 'ipython_repr_pretty', 265 | 'numpy', 266 | 'python', 267 | 'requests', 268 | 'dataclasses', 269 | ]) 270 | EMPTY_SET = frozenset() 271 | 272 | 273 | def install_extras( 274 | include=ALL_EXTRAS, 275 | *, 276 | exclude=EMPTY_SET, 277 | raise_on_error=False, 278 | warn_on_error=True 279 | ): 280 | """Installs extras. 281 | 282 | Installing an extra means registering pretty printers for objects from third 283 | party libraries and/or enabling integrations with other python programs. 284 | 285 | - ``'attrs'`` - automatically pretty prints classes created using the ``attrs`` package. 286 | - ``'dataclasses'`` - automatically pretty prints classes created using the ``dataclasses`` 287 | module. 288 | - ``'django'`` - automatically pretty prints Model and QuerySet subclasses defined in your 289 | Django apps. 290 | - ``numpy`` - automatically pretty prints numpy scalars with explicit types, and, 291 | for numpy>=1.14, numpy arrays. 292 | - ``'requests'`` - automatically pretty prints Requests, Responses, Sessions, etc. 293 | - ``'ipython'`` - makes prettyprinter the default printer in the IPython shell. 294 | - ``'python'`` - makes prettyprinter the default printer in the default Python shell. 295 | - ``'ipython_repr_pretty'`` - automatically prints objects that define a ``_repr_pretty_`` 296 | method to integrate with `IPython.lib.pretty 297 | `_. 298 | 299 | :param include: an iterable of strs representing the extras to include. 300 | All extras are included by default. 301 | :param exclude: an iterable of strs representing the extras to exclude. 302 | """ # noqa 303 | include = set(include) 304 | exclude = set(exclude) 305 | 306 | unexisting_extras = (include | exclude) - ALL_EXTRAS 307 | 308 | if unexisting_extras: 309 | raise ValueError( 310 | "The following extras don't exist: {}".format( 311 | ', '.join(unexisting_extras) 312 | ) 313 | ) 314 | 315 | extras_to_install = (ALL_EXTRAS & include) - exclude 316 | 317 | for extra in extras_to_install: 318 | module_name = 'prettyprinter.extras.' + extra 319 | try: 320 | extra_module = import_module(module_name) 321 | except ImportError as e: 322 | if raise_on_error: 323 | raise e 324 | if warn_on_error: 325 | warnings.warn( 326 | "Failed to import '{0}' PrettyPrinter extra. " 327 | "If you don't need it, call install_extras with " 328 | "exclude=['{0}']".format(extra) 329 | ) 330 | else: 331 | try: 332 | extra_module.install() 333 | except Exception as exc: 334 | if raise_on_error: 335 | raise exc 336 | elif warn_on_error: 337 | warnings.warn( 338 | "Failed to install '{0}' PrettyPrinter extra. " 339 | "If you don't need it, call install_extras with " 340 | "exclude=['{0}']".format(extra) 341 | ) 342 | 343 | 344 | def set_default_config( 345 | *, 346 | style=_UNSET_SENTINEL, 347 | max_seq_len=_UNSET_SENTINEL, 348 | width=_UNSET_SENTINEL, 349 | ribbon_width=_UNSET_SENTINEL, 350 | depth=_UNSET_SENTINEL, 351 | sort_dict_keys=_UNSET_SENTINEL 352 | ): 353 | """ 354 | Sets the default configuration values used when calling 355 | `pprint`, `cpprint`, or `pformat`, if those values weren't 356 | explicitly provided. Only overrides the values provided in 357 | the keyword arguments. 358 | """ 359 | global _default_config 360 | 361 | if style is not _UNSET_SENTINEL: 362 | set_default_style(style) 363 | 364 | new_defaults = {**_default_config} 365 | 366 | if max_seq_len is not _UNSET_SENTINEL: 367 | new_defaults['max_seq_len'] = max_seq_len 368 | 369 | if width is not _UNSET_SENTINEL: 370 | new_defaults['width'] = width 371 | 372 | if ribbon_width is not _UNSET_SENTINEL: 373 | new_defaults['ribbon_width'] = ribbon_width 374 | 375 | if depth is not _UNSET_SENTINEL: 376 | new_defaults['depth'] = depth 377 | 378 | if sort_dict_keys is not _UNSET_SENTINEL: 379 | new_defaults['sort_dict_keys'] = sort_dict_keys 380 | 381 | _default_config = new_defaults 382 | return new_defaults 383 | 384 | 385 | def pretty_repr(instance): 386 | """ 387 | A function assignable to the ``__repr__`` dunder method, so that 388 | the ``prettyprinter`` definition for the type is used to provide 389 | repr output. Usage: 390 | 391 | .. code:: python 392 | 393 | from prettyprinter import pretty_repr 394 | 395 | class MyClass: 396 | __repr__ = pretty_repr 397 | 398 | """ 399 | 400 | instance_type = type(instance) 401 | if not is_registered( 402 | instance_type, 403 | check_superclasses=True, 404 | check_deferred=True, 405 | register_deferred=True 406 | ): 407 | warnings.warn( 408 | "pretty_repr is assigned as the __repr__ method of " 409 | "'{}'. However, no pretty printer is registered for that type, " 410 | "its superclasses or its subclasses. Falling back to the default " 411 | "repr implementation. To fix this warning, register a pretty " 412 | "printer using prettyprinter.register_pretty.".format( 413 | instance_type.__qualname__ 414 | ), 415 | UserWarning 416 | ) 417 | return object.__repr__(instance) 418 | 419 | return pformat(instance) 420 | -------------------------------------------------------------------------------- /prettyprinter/color.py: -------------------------------------------------------------------------------- 1 | import os 2 | import colorful 3 | from pygments import token, styles 4 | from pygments.style import Style 5 | from pygments.token import Keyword, Name, Comment, String, Error, Text, \ 6 | Number, Operator, Generic, Whitespace, Punctuation, Other, Literal 7 | 8 | from .sdoctypes import ( 9 | SLine, 10 | SAnnotationPush, 11 | SAnnotationPop, 12 | ) 13 | from .syntax import Token 14 | from .render import as_lines 15 | from .utils import rfind_idx 16 | 17 | _SYNTAX_TOKEN_TO_PYGMENTS_TOKEN = { 18 | Token.KEYWORD_CONSTANT: token.Keyword.Constant, 19 | Token.NAME_BUILTIN: token.Name.Builtin, 20 | Token.NAME_ENTITY: token.Name.Entity, 21 | Token.NAME_FUNCTION: token.Name.Function, 22 | Token.NAME_VARIABLE: token.Name.Variable, 23 | Token.LITERAL_STRING: token.String, 24 | Token.STRING_AFFIX: token.String.Affix, 25 | Token.STRING_ESCAPE: token.String.Escape, 26 | Token.NUMBER_INT: token.Number, 27 | Token.NUMBER_BINARY: token.Number.Bin, 28 | Token.NUMBER_INT: token.Number.Integer, 29 | Token.NUMBER_FLOAT: token.Number.Float, 30 | Token.OPERATOR: token.Operator, 31 | Token.PUNCTUATION: token.Punctuation, 32 | Token.COMMENT_SINGLE: token.Comment.Single, 33 | } 34 | 35 | 36 | # From https://github.com/primer/github-syntax-theme-generator/blob/master/lib/themes/light.json # noqa 37 | # GitHub has MIT licenesed the theme, see 38 | # https://github.com/primer/github-syntax-theme-generator/blob/master/LICENSE 39 | class GitHubLightStyle(Style): 40 | background_color = "#ffffff" # done 41 | highlight_color = "#fafbfc" # done 42 | 43 | styles = { 44 | # No corresponding class for the following: 45 | Text: "#24292e", 46 | Whitespace: "", 47 | Error: "bold #b31d28", 48 | Other: "", 49 | 50 | Comment: "#6a737d", # done 51 | Comment.Multiline: "", 52 | Comment.Preproc: "", 53 | Comment.Single: "", 54 | Comment.Special: "", 55 | 56 | Keyword: "#d73a49", # class: 'k' 57 | Keyword.Constant: "#005cc5", # done 58 | Keyword.Declaration: "#d73a49", 59 | Keyword.Namespace: "#d73a49", 60 | Keyword.Pseudo: "", 61 | Keyword.Reserved: "", 62 | Keyword.Type: "", 63 | 64 | Operator: "#d73a49", # class: 'o' 65 | Operator.Word: "", # class: 'ow' - like keywords 66 | 67 | Punctuation: "", # class: 'p' 68 | 69 | Name: "#6f42c1", # class: 'n' 70 | Name.Attribute: "#24292e", # class: 'na' - to be revised 71 | Name.Builtin: "#005cc5", # class: 'nb' 72 | Name.Builtin.Pseudo: "#005cc5", # class: 'bp' 73 | Name.Class: "#6f42c1", # class: 'nc' - to be revised 74 | Name.Constant: "#005cc5", # class: 'no' - to be revised 75 | Name.Decorator: "#6f42c1", # done 76 | Name.Entity: "#6f42c1", # done 77 | Name.Exception: "#005cc5", # done 78 | Name.Function: "#6f42c1", # done 79 | Name.Function.Magic: "#005cc5", # done 80 | Name.Property: "", # class: 'py' 81 | Name.Label: "", # class: 'nl' 82 | Name.Namespace: "", # class: 'nn' - to be revised 83 | Name.Other: "#005cc5", # class: 'nx' 84 | Name.Tag: "#22863a", # done 85 | Name.Variable: "#e36209", # class: 'nv' - to be revised 86 | Name.Variable.Class: "", # class: 'vc' - to be revised 87 | Name.Variable.Global: "", # class: 'vg' - to be revised 88 | Name.Variable.Instance: "", # class: 'vi' - to be revised 89 | 90 | Number: "#005cc5", # class: 'm' 91 | Number.Float: "", # class: 'mf' 92 | Number.Hex: "", # class: 'mh' 93 | Number.Integer: "", # class: 'mi' 94 | Number.Integer.Long: "", # class: 'il' 95 | Number.Oct: "", # class: 'mo' 96 | 97 | Literal: "#005cc5", # class: 'l' 98 | Literal.Date: "#005cc5", # class: 'ld' 99 | 100 | String: "#032f62", # done 101 | String.Backtick: "", # class: 'sb' 102 | String.Char: "", # class: 'sc' 103 | String.Doc: "", # class: 'sd' - like a comment 104 | String.Double: "", # class: 's2' 105 | String.Escape: "#22863a", # done 106 | String.Heredoc: "", # class: 'sh' 107 | String.Interpol: "#005cc5", # done 108 | String.Other: "", # class: 'sx' 109 | String.Regex: "", # class: 'sr' 110 | String.Single: "", # class: 's1' 111 | String.Symbol: "", # class: 'ss' 112 | 113 | Generic: "", # class: 'g' 114 | Generic.Deleted: "#f92672", # class: 'gd', 115 | Generic.Emph: "italic", # class: 'ge' 116 | Generic.Error: "", # class: 'gr' 117 | Generic.Heading: "", # class: 'gh' 118 | Generic.Inserted: "#22863a bg: #f0fff4", # class: 'gi' 119 | Generic.Output: "", # class: 'go' 120 | Generic.Prompt: "", # class: 'gp' 121 | Generic.Strong: "bold", # class: 'gs' 122 | Generic.Subheading: "bold #005cc5", # class: 'gu' 123 | Generic.Traceback: "", # class: 'gt' 124 | } 125 | 126 | 127 | default_dark_style = styles.get_style_by_name('monokai') 128 | default_light_style = GitHubLightStyle 129 | 130 | is_light_bg = None 131 | 132 | colorfgbg = os.environ.get('COLORFGBG', '') 133 | try: 134 | fg, bg = map(int, colorfgbg.split(';', 1)) 135 | if bg > fg: 136 | is_light_bg = True 137 | if fg > bg: 138 | is_light_bg = False 139 | except ValueError: 140 | pass 141 | 142 | bg_override = os.environ.get('PYPRETTYPRINTER_LIGHT_BACKGROUND') 143 | if bg_override is not None: 144 | is_light_bg = bool(bg_override) 145 | if bg_override == '0' or bg_override.lower() == 'false': 146 | is_light_bg = False 147 | 148 | default_style = default_light_style if is_light_bg else default_dark_style 149 | 150 | 151 | def set_default_style(style): 152 | """Sets default global style to be used by ``prettyprinter.cpprint``. 153 | 154 | :param style: the style to set, either subclass of 155 | ``pygments.styles.Style`` or one of ``'dark'``, ``'light'`` 156 | """ 157 | global default_style 158 | if style == 'dark': 159 | style = default_dark_style 160 | elif style == 'light': 161 | style = default_light_style 162 | 163 | if not issubclass(style, Style): 164 | raise TypeError( 165 | "style must be a subclass of pygments.styles.Style or " 166 | "one of 'dark', 'light'. Got {}".format(repr(style)) 167 | ) 168 | default_style = style 169 | 170 | 171 | def styleattrs_to_colorful(attrs): 172 | c = colorful.reset 173 | if attrs['color'] or attrs['bgcolor']: 174 | # Colorful doesn't have a way to directly set Hex/RGB 175 | # colors- until I find a better way, we do it like this :) 176 | accessor = '' 177 | if attrs['color']: 178 | colorful.update_palette({'prettyprinterCurrFg': attrs['color']}) 179 | accessor = 'prettyprinterCurrFg' 180 | if attrs['bgcolor']: 181 | colorful.update_palette({'prettyprinterCurrBg': attrs['bgcolor']}) 182 | accessor += '_on_prettyprinterCurrBg' 183 | c &= getattr(colorful, accessor) 184 | if attrs['bold']: 185 | c &= colorful.bold 186 | if attrs['italic']: 187 | c &= colorful.italic 188 | if attrs['underline']: 189 | c &= colorful.underline 190 | return c 191 | 192 | 193 | def colored_render_to_stream( 194 | stream, 195 | sdocs, 196 | style, 197 | newline='\n', 198 | separator=' ' 199 | ): 200 | if style is None: 201 | style = default_style 202 | 203 | evald = list(sdocs) 204 | 205 | if not evald: 206 | return 207 | 208 | color_cache = {} 209 | 210 | colorstack = [] 211 | 212 | sdoc_lines = as_lines(evald) 213 | 214 | for sdoc_line in sdoc_lines: 215 | last_text_sdoc_idx = rfind_idx( 216 | lambda sdoc: isinstance(sdoc, str), 217 | sdoc_line 218 | ) 219 | 220 | # Edge case: trailing whitespace on a line. 221 | # Currently happens on multiline str value in a dict: 222 | # there's a trailing whitespace after the colon that's 223 | # hard to eliminate at the doc level. 224 | if last_text_sdoc_idx != -1: 225 | last_text_sdoc = sdoc_line[last_text_sdoc_idx] 226 | sdoc_line[last_text_sdoc_idx] = last_text_sdoc.rstrip() 227 | 228 | for sdoc in sdoc_line: 229 | if isinstance(sdoc, str): 230 | stream.write(sdoc) 231 | elif isinstance(sdoc, SLine): 232 | stream.write(newline + separator * sdoc.indent) 233 | elif isinstance(sdoc, SAnnotationPush): 234 | if isinstance(sdoc.value, Token): 235 | try: 236 | color = color_cache[sdoc.value] 237 | except KeyError: 238 | pygments_token = _SYNTAX_TOKEN_TO_PYGMENTS_TOKEN[ 239 | sdoc.value 240 | ] 241 | tokenattrs = style.style_for_token(pygments_token) 242 | color = styleattrs_to_colorful(tokenattrs) 243 | color_cache[sdoc.value] = color 244 | 245 | colorstack.append(color) 246 | stream.write(str(color)) 247 | 248 | elif isinstance(sdoc, SAnnotationPop): 249 | try: 250 | colorstack.pop() 251 | except IndexError: 252 | continue 253 | 254 | if colorstack: 255 | stream.write(str(colorstack[-1])) 256 | else: 257 | stream.write(str(colorful.reset)) 258 | 259 | if colorstack: 260 | stream.write(str(colorful.reset)) 261 | -------------------------------------------------------------------------------- /prettyprinter/doc.py: -------------------------------------------------------------------------------- 1 | from .doctypes import ( # noqa 2 | AlwaysBreak, 3 | Concat, 4 | Contextual, 5 | Doc, 6 | FlatChoice, 7 | Fill, 8 | Group, 9 | Nest, 10 | Annotated, 11 | NIL, 12 | LINE, 13 | SOFTLINE, 14 | HARDLINE, 15 | ) 16 | from .utils import intersperse # noqa 17 | 18 | 19 | def validate_doc(doc): 20 | if not isinstance(doc, Doc) and not isinstance(doc, str): 21 | raise ValueError('Invalid doc: {}'.format(repr(doc))) 22 | 23 | return doc 24 | 25 | 26 | def group(doc): 27 | """Annotates doc with special meaning to the layout algorithm, so that the 28 | document is attempted to output on a single line if it is possible within 29 | the layout constraints. To lay out the doc on a single line, the `when_flat` 30 | branch of ``FlatChoice`` is used.""" 31 | return Group(validate_doc(doc)) 32 | 33 | 34 | def concat(docs): 35 | """Returns a concatenation of the documents in the iterable argument""" 36 | return Concat(map(validate_doc, docs)) 37 | 38 | 39 | def annotate(annotation, doc): 40 | """Annotates ``doc`` with the arbitrary value ``annotation``""" 41 | return Annotated(doc, annotation) 42 | 43 | 44 | def contextual(fn): 45 | """Returns a Doc that is lazily evaluated when deciding the layout. 46 | 47 | ``fn`` must be a function that accepts four arguments: 48 | 49 | - ``indent`` (``int``): the current indentation level, 0 or more 50 | - ``column`` (``int``) the current output column in the output line 51 | - ``page_width`` (``int``) the requested page width (character count) 52 | - ``ribbon_width`` (``int``) the requested ribbon width (character count) 53 | """ 54 | return Contextual(fn) 55 | 56 | 57 | def align(doc): 58 | """Aligns each new line in ``doc`` with the first new line. 59 | """ 60 | validate_doc(doc) 61 | 62 | def evaluator(indent, column, page_width, ribbon_width): 63 | return Nest(column - indent, doc) 64 | return contextual(evaluator) 65 | 66 | 67 | def hang(i, doc): 68 | return align( 69 | Nest(i, validate_doc(doc)) 70 | ) 71 | 72 | 73 | def nest(i, doc): 74 | return Nest(i, validate_doc(doc)) 75 | 76 | 77 | def fill(docs): 78 | return Fill(map(validate_doc, docs)) 79 | 80 | 81 | def always_break(doc): 82 | """Instructs the layout algorithm that ``doc`` must be 83 | broken to multiple lines. This instruction propagates 84 | to all higher levels in the layout, but nested Docs 85 | may still be laid out flat.""" 86 | return AlwaysBreak(validate_doc(doc)) 87 | 88 | 89 | def flat_choice(when_broken, when_flat): 90 | """Gives the layout algorithm two options. ``when_flat`` Doc will be 91 | used when the document fit onto a single line, and ``when_broken`` is used 92 | when the Doc had to be broken into multiple lines.""" 93 | return FlatChoice( 94 | validate_doc(when_broken), 95 | validate_doc(when_flat) 96 | ) 97 | -------------------------------------------------------------------------------- /prettyprinter/doctypes.py: -------------------------------------------------------------------------------- 1 | def normalize_doc(doc): 2 | if isinstance(doc, str): 3 | if doc == '': 4 | return NIL 5 | return doc 6 | return doc.normalize() 7 | 8 | 9 | class Doc: 10 | """The base class for all Docs, except for plain ``str`` s which 11 | are unboxed. 12 | 13 | A Doc is a tree structure that represents the set of all possible 14 | layouts of the contents. The layout algorithm processes the tree, 15 | narrowing down the set of layouts based on input parameters like 16 | total and ribbon width to produce a stream of SDocs (simple Docs) 17 | that represent a single layout. 18 | """ 19 | __slots__ = () 20 | 21 | def normalize(self): 22 | return self 23 | 24 | 25 | class Annotated(Doc): 26 | __slots__ = ('doc', 'annotation') 27 | 28 | def __init__(self, doc, annotation): 29 | self.doc = doc 30 | self.annotation = annotation 31 | 32 | def __repr__(self): 33 | return 'Annotated({})'.format(repr(self.doc)) 34 | 35 | def normalize(self): 36 | return Annotated(normalize_doc(self.doc), self.annotation) 37 | 38 | 39 | class Nil(Doc): 40 | def __repr__(self): 41 | return 'NIL' 42 | 43 | 44 | NIL = Nil() 45 | 46 | 47 | class Concat(Doc): 48 | __slots__ = ('docs', ) 49 | 50 | def __init__(self, docs): 51 | self.docs = list(docs) 52 | 53 | def normalize(self): 54 | normalized_docs = [] 55 | propagate_broken = False 56 | for doc in self.docs: 57 | doc = normalize_doc(doc) 58 | if isinstance(doc, Concat): 59 | normalized_docs.extend(doc.docs) 60 | elif isinstance(doc, AlwaysBreak): 61 | propagate_broken = True 62 | normalized_docs.append(doc.doc) 63 | elif doc is NIL: 64 | continue 65 | else: 66 | normalized_docs.append(doc) 67 | 68 | if not normalized_docs: 69 | return NIL 70 | 71 | if len(normalized_docs) == 1: 72 | res = normalized_docs[0] 73 | else: 74 | res = Concat(normalized_docs) 75 | 76 | if propagate_broken: 77 | res = AlwaysBreak(res) 78 | return res 79 | 80 | def __repr__(self): 81 | return "Concat([{}])".format( 82 | ', '.join(repr(doc) for doc in self.docs) 83 | ) 84 | 85 | 86 | class Nest(Doc): 87 | __slots__ = ('indent', 'doc') 88 | 89 | def __init__(self, indent, doc): 90 | assert isinstance(indent, int) 91 | assert isinstance(doc, Doc) 92 | 93 | self.indent = indent 94 | self.doc = doc 95 | 96 | def normalize(self): 97 | inner_normalized = normalize_doc(self.doc) 98 | if isinstance(inner_normalized, AlwaysBreak): 99 | return AlwaysBreak( 100 | Nest(self.indent, inner_normalized.doc) 101 | ) 102 | return Nest(self.indent, inner_normalized) 103 | 104 | def __repr__(self): 105 | return 'Nest({}, {})'.format( 106 | repr(self.indent), 107 | repr(self.doc) 108 | ) 109 | 110 | 111 | class FlatChoice(Doc): 112 | __slots__ = ( 113 | '_when_broken', 114 | '_when_flat', 115 | 'normalize_on_access', 116 | '_broken_normalized', 117 | '_flat_normalized', 118 | ) 119 | 120 | def __init__(self, when_broken, when_flat, normalize_on_access=False): 121 | self._when_broken = when_broken 122 | self._when_flat = when_flat 123 | 124 | # If we were to strictly normalize this Doc, we'd have 125 | # to normalize both subtrees, which can be costly if they're 126 | # large. The layout algorithm only accesses one of the 127 | # properties based on the current mode (break/flat). 128 | # Hence we delay the normalization to when that access 129 | # happens. 130 | self.normalize_on_access = normalize_on_access 131 | self._broken_normalized = False 132 | self._flat_normalized = False 133 | 134 | def normalize(self): 135 | if self.normalize_on_access: 136 | return self 137 | 138 | return FlatChoice( 139 | self._when_broken, 140 | self._when_flat, 141 | normalize_on_access=True 142 | ) 143 | 144 | @property 145 | def when_broken(self): 146 | if self.normalize_on_access and not self._broken_normalized: 147 | self._when_broken = normalize_doc(self._when_broken) 148 | self._broken_normalized = True 149 | return self._when_broken 150 | 151 | @property 152 | def when_flat(self): 153 | if self._broken_normalized and not self._flat_normalized: 154 | self._when_flat = normalize_doc(self._when_flat) 155 | self._flat_normalized = True 156 | return self._when_flat 157 | 158 | def __repr__(self): 159 | return 'FlatChoice(when_broken={}, when_flat={})'.format( 160 | repr(self.when_broken), 161 | repr(self.when_flat) 162 | ) 163 | 164 | 165 | class Contextual(Doc): 166 | __slots__ = ('fn', ) 167 | 168 | def __init__(self, fn): 169 | self.fn = fn 170 | 171 | def __repr__(self): 172 | return 'Contextual({})'.format(repr(self.fn)) 173 | 174 | 175 | class HardLine(Doc): 176 | def __repr__(self): 177 | return 'HardLine()' 178 | 179 | 180 | HARDLINE = HardLine() 181 | LINE = FlatChoice(HARDLINE, ' ') 182 | SOFTLINE = FlatChoice(HARDLINE, NIL) 183 | 184 | 185 | class Group(Doc): 186 | __slots__ = ('doc', ) 187 | 188 | def __init__(self, doc): 189 | assert isinstance(doc, Doc) 190 | self.doc = doc 191 | 192 | def normalize(self): 193 | doc_normalized = normalize_doc(self.doc) 194 | if isinstance(doc_normalized, AlwaysBreak): 195 | # Group is the possibility of either flat 196 | # or break; since we're always breaking, 197 | # we don't need Group. 198 | return doc_normalized 199 | elif doc_normalized is NIL: 200 | return NIL 201 | return Group(doc_normalized) 202 | 203 | def __repr__(self): 204 | return 'Group({})'.format(repr(self.doc)) 205 | 206 | 207 | class AlwaysBreak(Doc): 208 | __slots__ = ('doc', ) 209 | 210 | def __init__(self, doc): 211 | assert isinstance(doc, Doc) 212 | self.doc = doc 213 | 214 | def normalize(self): 215 | doc_normalized = normalize_doc(self.doc) 216 | if isinstance(doc_normalized, AlwaysBreak): 217 | return doc_normalized 218 | return AlwaysBreak(doc_normalized) 219 | 220 | def __repr__(self): 221 | return 'AlwaysBreak({})'.format(repr(self.doc)) 222 | 223 | 224 | class Fill(Doc): 225 | __slots__ = ('docs', ) 226 | 227 | def __init__(self, docs): 228 | self.docs = list(docs) 229 | 230 | def normalize(self): 231 | normalized_docs = [] 232 | propagate_broken = False 233 | for doc in self.docs: 234 | if isinstance(doc, AlwaysBreak): 235 | propagate_broken = True 236 | doc = doc.doc 237 | 238 | if doc is NIL: 239 | continue 240 | else: 241 | normalized_docs.append(doc) 242 | 243 | if normalized_docs: 244 | res = Fill(normalized_docs) 245 | if propagate_broken: 246 | res = AlwaysBreak(res) 247 | return res 248 | 249 | return NIL 250 | 251 | def __repr__(self): 252 | return "Fill([{}])".format( 253 | ', '.join(repr(doc) for doc in self.docs) 254 | ) 255 | -------------------------------------------------------------------------------- /prettyprinter/extras/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/tommikaikkonen/prettyprinter/53ba5f934f24228315ef10898fc2b73370349696/prettyprinter/extras/__init__.py -------------------------------------------------------------------------------- /prettyprinter/extras/attrs.py: -------------------------------------------------------------------------------- 1 | from attr import Factory, NOTHING 2 | from prettyprinter.prettyprinter import pretty_call_alt, register_pretty 3 | 4 | 5 | def is_instance_of_attrs_class(value): 6 | cls = type(value) 7 | 8 | try: 9 | cls.__attrs_attrs__ 10 | except AttributeError: 11 | return False 12 | 13 | return True 14 | 15 | 16 | def pretty_attrs(value, ctx): 17 | cls = type(value) 18 | attributes = cls.__attrs_attrs__ 19 | 20 | kwargs = [] 21 | for attribute in attributes: 22 | if not attribute.repr: 23 | continue 24 | 25 | display_attr = False 26 | if attribute.default == NOTHING: 27 | display_attr = True 28 | elif isinstance(attribute.default, Factory): 29 | default_value = ( 30 | attribute.default.factory(value) 31 | if attribute.default.takes_self 32 | else attribute.default.factory() 33 | ) 34 | if default_value != getattr(value, attribute.name): 35 | display_attr = True 36 | else: 37 | if attribute.default != getattr(value, attribute.name): 38 | display_attr = True 39 | 40 | if display_attr: 41 | kwargs.append((attribute.name, getattr(value, attribute.name))) 42 | 43 | return pretty_call_alt(ctx, cls, kwargs=kwargs) 44 | 45 | 46 | def install(): 47 | register_pretty(predicate=is_instance_of_attrs_class)(pretty_attrs) 48 | -------------------------------------------------------------------------------- /prettyprinter/extras/dataclasses.py: -------------------------------------------------------------------------------- 1 | from collections import OrderedDict 2 | from dataclasses import ( 3 | fields, 4 | MISSING, 5 | ) 6 | 7 | from prettyprinter.prettyprinter import pretty_call, register_pretty 8 | 9 | 10 | def is_instance_of_dataclass(value): 11 | try: 12 | fields(value) 13 | except TypeError: 14 | return False 15 | else: 16 | return True 17 | 18 | 19 | def pretty_dataclass_instance(value, ctx): 20 | cls = type(value) 21 | field_defs = fields(value) 22 | 23 | kwargs = [] 24 | for field_def in field_defs: 25 | # repr is True by default, 26 | # therefore if this if False, the user 27 | # has explicitly indicated they don't want 28 | # to display the field value. 29 | if not field_def.repr: 30 | continue 31 | 32 | display_attr = False 33 | 34 | if ( 35 | field_def.default is MISSING and 36 | field_def.default_factory is MISSING 37 | ): 38 | display_attr = True 39 | elif field_def.default is not MISSING: 40 | if field_def.default != getattr(value, field_def.name): 41 | display_attr = True 42 | elif field_def.default_factory is not MISSING: 43 | default_value = field_def.default_factory() 44 | if default_value != getattr(value, field_def.name): 45 | display_attr = True 46 | else: 47 | assert "default and default_factory should not be both defined" 48 | 49 | if display_attr: 50 | kwargs.append((field_def.name, getattr(value, field_def.name))) 51 | 52 | return pretty_call(ctx, cls, **OrderedDict(kwargs)) 53 | 54 | 55 | def install(): 56 | register_pretty(predicate=is_instance_of_dataclass)(pretty_dataclass_instance) 57 | -------------------------------------------------------------------------------- /prettyprinter/extras/django.py: -------------------------------------------------------------------------------- 1 | from enum import Enum, unique 2 | 3 | from django.db.models.fields import NOT_PROVIDED 4 | from django.db.models import Model, ForeignKey 5 | from django.db.models.query import QuerySet 6 | 7 | from ..prettyprinter import ( 8 | MULTILINE_STRATEGY_HANG, 9 | build_fncall, 10 | pretty_call_alt, 11 | pretty_python_value, 12 | register_pretty, 13 | comment_doc, 14 | trailing_comment 15 | ) 16 | 17 | from ..utils import find 18 | 19 | 20 | QUERYSET_OUTPUT_SIZE = 20 21 | 22 | 23 | @unique 24 | class ModelVerbosity(Enum): 25 | UNSET = 1 26 | MINIMAL = 2 27 | SHORT = 3 28 | FULL = 4 29 | 30 | 31 | def inc(value): 32 | return value 33 | 34 | 35 | class dec(object): 36 | __slots__ = ('value', ) 37 | 38 | def __init__(self, value): 39 | self.value = value 40 | 41 | def __lt__(self, other): 42 | assert isinstance(other, dec) 43 | return self.value > other.value 44 | 45 | def __gt__(self, other): 46 | assert isinstance(other, dec) 47 | return self.value < other.value 48 | 49 | def __eq__(self, other): 50 | assert isinstance(other, dec) 51 | return self.value == other.value 52 | 53 | def __le__(self, other): 54 | assert isinstance(other, dec) 55 | return self.value >= other.value 56 | 57 | def __ge__(self, other): 58 | assert isinstance(other, dec) 59 | return self.value <= other.value 60 | 61 | __hash__ = None 62 | 63 | 64 | def field_sort_key(field): 65 | return ( 66 | dec(field.primary_key), 67 | dec(field.unique), 68 | inc(field.null), 69 | inc(field.blank), 70 | dec(field.default is NOT_PROVIDED), 71 | inc(field.name), 72 | ) 73 | 74 | 75 | def pretty_base_model(instance, ctx): 76 | verbosity = ctx.get(ModelVerbosity) 77 | 78 | model = type(instance) 79 | 80 | if verbosity == ModelVerbosity.MINIMAL: 81 | fields = [find(lambda field: field.primary_key, model._meta.fields)] 82 | elif verbosity == ModelVerbosity.SHORT: 83 | fields = sorted( 84 | ( 85 | field 86 | for field in model._meta.fields 87 | if field.primary_key or not field.null and field.unique 88 | ), 89 | key=field_sort_key 90 | ) 91 | else: 92 | fields = sorted(model._meta.fields, key=field_sort_key) 93 | 94 | attrs = [] 95 | value_ctx = ( 96 | ctx 97 | .nested_call() 98 | .use_multiline_strategy(MULTILINE_STRATEGY_HANG) 99 | ) 100 | 101 | null_fieldnames = [] 102 | blank_fieldnames = [] 103 | default_fieldnames = [] 104 | 105 | for field in fields: 106 | if isinstance(field, ForeignKey): 107 | fk_value = getattr(instance, field.attname) 108 | if fk_value is not None: 109 | related_field = field.target_field 110 | related_model = related_field.model 111 | attrs.append(( 112 | field.name, 113 | pretty_call_alt( 114 | ctx, 115 | related_model, 116 | [(related_field.name, fk_value)] 117 | ) 118 | )) 119 | else: 120 | null_fieldnames.append(field.attname) 121 | else: 122 | value = getattr(instance, field.name) 123 | 124 | if field.default is not NOT_PROVIDED: 125 | if callable(field.default): 126 | default_value = field.default() 127 | else: 128 | default_value = field.default 129 | 130 | if value == default_value: 131 | default_fieldnames.append(field.attname) 132 | continue 133 | 134 | if field.null and value is None: 135 | null_fieldnames.append(field.attname) 136 | continue 137 | 138 | if field.blank and value in field.empty_values: 139 | blank_fieldnames.append(field.attname) 140 | continue 141 | 142 | kw = field.name 143 | vdoc = pretty_python_value(value, value_ctx) 144 | 145 | if field.choices: 146 | choices = tuple(field.choices) 147 | ungrouped_choices = ( 148 | (_value, _display) 149 | for value, display in choices 150 | for _value, _display in ( 151 | display if 152 | isinstance(display, tuple) 153 | else [(value, display)]) 154 | ) 155 | 156 | value__display = find( 157 | lambda value__display: value__display[0] == value, 158 | ungrouped_choices, 159 | ) 160 | 161 | try: 162 | _, display = value__display 163 | except ValueError: 164 | display = None 165 | 166 | if display: 167 | vdoc = comment_doc( 168 | vdoc, 169 | display 170 | ) 171 | 172 | attrs.append((kw, vdoc)) 173 | 174 | commentstr = ( 175 | ( 176 | "Null fields: {}\n".format( 177 | ', '.join(null_fieldnames) 178 | ) 179 | if null_fieldnames 180 | else '' 181 | ) + 182 | ( 183 | "Blank fields: {}\n".format( 184 | ', '.join(blank_fieldnames) 185 | ) 186 | if blank_fieldnames 187 | else '' 188 | ) + 189 | ( 190 | "Default value fields: {}\n".format( 191 | ', '.join(default_fieldnames) 192 | ) 193 | if default_fieldnames 194 | else '' 195 | ) 196 | ) 197 | 198 | return build_fncall( 199 | ctx, 200 | model, 201 | kwargdocs=attrs, 202 | trailing_comment=commentstr or None, 203 | ) 204 | 205 | 206 | def pretty_queryset(queryset, ctx): 207 | qs_cls = type(queryset) 208 | 209 | instances = list(queryset[:QUERYSET_OUTPUT_SIZE + 1]) 210 | if len(instances) > QUERYSET_OUTPUT_SIZE: 211 | truncated = True 212 | instances = instances[:-1] 213 | else: 214 | truncated = False 215 | 216 | element_ctx = ctx.assoc(ModelVerbosity, ModelVerbosity.SHORT) 217 | 218 | arg = ( 219 | trailing_comment( 220 | instances, 221 | '...remaining elements truncated' 222 | ) 223 | if truncated 224 | else instances 225 | ) 226 | 227 | return pretty_call_alt( 228 | element_ctx, 229 | qs_cls, 230 | args=(arg, ) 231 | ) 232 | 233 | 234 | def install(): 235 | register_pretty(Model)(pretty_base_model) 236 | register_pretty(QuerySet)(pretty_queryset) 237 | -------------------------------------------------------------------------------- /prettyprinter/extras/ipython.py: -------------------------------------------------------------------------------- 1 | from pygments.styles import get_style_by_name 2 | from pygments.style import Style 3 | 4 | import IPython.lib.pretty 5 | from IPython.lib.pretty import RepresentationPrinter 6 | 7 | from .. import cpprint 8 | from ..utils import get_terminal_width 9 | 10 | OriginalRepresentationPrinter = RepresentationPrinter 11 | 12 | 13 | class _NoStyle(Style): 14 | pass 15 | 16 | 17 | # This function mostly mirrors IPython's 18 | # TerminalInteractiveShell._make_style_from_name_or_cls, 19 | # except for style overrides. 20 | # https://github.com/ipython/ipython/blob/5b2b7dd07a268baceeeedfe919de0a59e5bc922b/IPython/terminal/interactiveshell.py#L284-L346 21 | # TODO: support style overrides. 22 | def pygments_style_from_name_or_cls(name_or_cls, ishell): 23 | if name_or_cls == 'legacy': 24 | legacy = ishell.colors.lower() 25 | if legacy == 'linux': 26 | return get_style_by_name('monokai') 27 | elif legacy == 'lightbg': 28 | return get_style_by_name('pastie') 29 | elif legacy == 'neutral': 30 | return get_style_by_name('default') 31 | elif legacy == 'nocolor': 32 | return _NoStyle 33 | else: 34 | raise ValueError('Got unknown colors: ', legacy) 35 | else: 36 | if isinstance(name_or_cls, str): 37 | return get_style_by_name(name_or_cls) 38 | else: 39 | return name_or_cls 40 | 41 | 42 | def install(): 43 | ipy = get_ipython() # noqa 44 | 45 | columns = get_terminal_width() 46 | 47 | class IPythonCompatPrinter: 48 | def __init__(self, stream, *args, **kwargs): 49 | self.stream = stream 50 | 51 | def pretty(self, obj): 52 | cpprint( 53 | obj, 54 | stream=self.stream, 55 | style=pygments_style_from_name_or_cls( 56 | ipy.highlighting_style, 57 | ishell=ipy 58 | ), 59 | width=columns, 60 | end=None 61 | ) 62 | 63 | def flush(self): 64 | pass 65 | 66 | IPython.lib.pretty.RepresentationPrinter = IPythonCompatPrinter 67 | -------------------------------------------------------------------------------- /prettyprinter/extras/ipython_repr_pretty.py: -------------------------------------------------------------------------------- 1 | from contextlib import contextmanager 2 | 3 | from .ipython import OriginalRepresentationPrinter 4 | from ..utils import ( 5 | compose, 6 | identity, 7 | ) 8 | from ..prettyprinter import ( 9 | register_pretty, 10 | pretty_python_value, 11 | ) 12 | from ..doc import ( 13 | HARDLINE, 14 | concat, 15 | contextual, 16 | flat_choice, 17 | group, 18 | nest 19 | ) 20 | 21 | 22 | def implements_repr_pretty(instance): 23 | try: 24 | method = instance._repr_pretty_ 25 | # Values returned from Mocks don't have a __func__ 26 | # attribute. 27 | method.__func__ 28 | except AttributeError: 29 | return False 30 | return callable(method) 31 | 32 | 33 | class NoopStream: 34 | def write(self, value): 35 | pass 36 | 37 | 38 | class CompatRepresentationPrinter(OriginalRepresentationPrinter): 39 | def __init__(self, *args, **kwargs): 40 | self._prettyprinter_ctx = kwargs.pop('prettyprinter_ctx') 41 | super().__init__(*args, **kwargs) 42 | 43 | # self.output should be assigned by the superclass 44 | assert isinstance(self.output, NoopStream) 45 | 46 | self._pending_wrapper = identity 47 | self._docparts = [] 48 | 49 | def text(self, obj): 50 | super().text(obj) 51 | 52 | self._docparts.append(obj) 53 | 54 | def breakable(self, sep=' '): 55 | super().breakable(sep) 56 | 57 | self._docparts.append( 58 | flat_choice(when_flat=sep, when_broken=HARDLINE) 59 | ) 60 | 61 | def begin_group(self, indent=0, open=''): 62 | super().begin_group(indent, open) 63 | 64 | def wrapper(doc): 65 | if indent: 66 | doc = nest(indent, doc) 67 | return group(doc) 68 | 69 | self._pending_wrapper = compose(wrapper, self._pending_wrapper) 70 | 71 | def end_group(self, dedent=0, close=''): 72 | super().end_group(dedent, close) 73 | 74 | # dedent is ignored; it is not supported to 75 | # have different indentation when starting and 76 | # ending the group. 77 | 78 | doc = self._pending_wrapper(concat(self._docparts)) 79 | 80 | self._docparts = [doc] 81 | self._pending_wrapper = identity 82 | 83 | @contextmanager 84 | def indent(self, indent): 85 | """with statement support for indenting/dedenting.""" 86 | curr_docparts = self._docparts 87 | self._docparts = [] 88 | self.indentation += indent 89 | try: 90 | yield 91 | finally: 92 | self.indentation -= indent 93 | indented_docparts = self._docparts 94 | self._docparts = curr_docparts 95 | self._docparts.append(nest(indent, concat(indented_docparts))) 96 | 97 | def pretty(self, obj): 98 | self._docparts.append( 99 | pretty_python_value(obj, self._prettyprinter_ctx) 100 | ) 101 | 102 | 103 | def wrap_repr_pretty(fn): 104 | def wrapped(value, ctx): 105 | def evaluator(indent, column, page_width, ribbon_width): 106 | printer = CompatRepresentationPrinter( 107 | NoopStream(), 108 | max_width=page_width - column, 109 | max_seq_length=ctx.max_seq_len, 110 | prettyprinter_ctx=ctx 111 | ) 112 | 113 | with printer.group(): 114 | fn(value, printer, cycle=False) 115 | 116 | return concat(printer._docparts) 117 | return contextual(evaluator) 118 | return wrapped 119 | 120 | 121 | def pretty_repr_pretty(value, ctx): 122 | unbound_repr_pretty = value._repr_pretty_.__func__ 123 | return wrap_repr_pretty(unbound_repr_pretty)(value, ctx) 124 | 125 | 126 | def install(): 127 | register_pretty(predicate=implements_repr_pretty)(pretty_repr_pretty) 128 | -------------------------------------------------------------------------------- /prettyprinter/extras/numpy.py: -------------------------------------------------------------------------------- 1 | import ast 2 | from distutils.version import LooseVersion 3 | from math import ceil 4 | 5 | from ..prettyprinter import ( 6 | register_pretty, 7 | pretty_call_alt, 8 | pretty_bool, 9 | pretty_int, 10 | pretty_float 11 | ) 12 | 13 | 14 | def pretty_ndarray(value, ctx): 15 | import numpy as np 16 | # numpy 1.14 added dtype_is_implied. 17 | if LooseVersion(np.__version__) < "1.14": 18 | return repr(value) 19 | if type(value) != np.ndarray: 20 | # Masked arrays, in particular, require their own logic. 21 | return repr(value) 22 | from numpy.core import arrayprint 23 | args = (value.tolist(),) 24 | kwargs = [] 25 | dtype = value.dtype 26 | # This logic is extracted from arrayprint._array_repr_implementation. 27 | skip_dtype = arrayprint.dtype_is_implied(dtype) and value.size > 0 28 | if not skip_dtype: 29 | dtype_repr = repr(dtype) 30 | assert dtype_repr.startswith("dtype(") and dtype_repr.endswith(")") 31 | kwargs.append(("dtype", ast.literal_eval(dtype_repr[6:-1]))) 32 | ctx_new = ctx.nested_call() 33 | # Handle truncation of subsequences for multidimensional arrays 34 | if value.ndim >= 2 and value.size > ctx.max_seq_len: 35 | left, right = 1, ctx.max_seq_len 36 | while left != right: 37 | middle = ceil((left + right) / 2) 38 | if np.prod(np.minimum(middle, value.shape)) > ctx.max_seq_len: 39 | right = middle - 1 40 | else: 41 | left = middle 42 | ctx_new.max_seq_len = left 43 | return pretty_call_alt(ctx_new, type(value), args, kwargs) 44 | 45 | 46 | def install(): 47 | register_pretty("numpy.bool_")(pretty_bool) 48 | 49 | for name in [ 50 | "uint8", "uint16", "uint32", "uint64", 51 | "int8", "int16", "int32", "int64", 52 | ]: 53 | register_pretty("numpy." + name)(pretty_int) 54 | 55 | for name in [ 56 | "float16", "float32", "float64", "float128", 57 | ]: 58 | register_pretty("numpy." + name)(pretty_float) 59 | 60 | register_pretty("numpy.ndarray")(pretty_ndarray) 61 | -------------------------------------------------------------------------------- /prettyprinter/extras/python.py: -------------------------------------------------------------------------------- 1 | import builtins 2 | import sys 3 | from io import StringIO 4 | 5 | from prettyprinter import cpprint 6 | from prettyprinter.utils import get_terminal_width 7 | 8 | 9 | def install(): 10 | try: 11 | get_ipython 12 | except NameError: 13 | pass 14 | else: 15 | raise ValueError( 16 | "Don't install the default Python shell integration " 17 | "if you're using IPython, use the IPython integration with " 18 | "prettyprinter.install_extras(include=['ipython'])." 19 | ) 20 | 21 | def prettyprinter_displayhook(value): 22 | if value is None: 23 | return 24 | 25 | builtins._ = None 26 | stream = StringIO() 27 | output = cpprint( 28 | value, 29 | width=get_terminal_width(default=79), 30 | stream=stream, 31 | end='' 32 | ) 33 | output = stream.getvalue() 34 | 35 | try: 36 | sys.stdout.write(output) 37 | except UnicodeEncodeError: 38 | encoded = output.encode(sys.stdout.encoding, 'backslashreplace') 39 | if hasattr(sys.stdout, 'buffer'): 40 | sys.stdout.buffer.write(encoded) 41 | else: 42 | text = encoded.decode(sys.stdout.encoding, 'strict') 43 | sys.stdout.write(text) 44 | 45 | sys.stdout.write('\n') 46 | builtins._ = value 47 | 48 | sys.displayhook = prettyprinter_displayhook 49 | -------------------------------------------------------------------------------- /prettyprinter/extras/requests.py: -------------------------------------------------------------------------------- 1 | from prettyprinter import pretty_call_alt, comment, register_pretty 2 | 3 | 4 | MAX_CONTENT_CHARS = 500 5 | 6 | 7 | def pretty_headers(headers, ctx): 8 | return pretty_call_alt( 9 | ctx, 10 | type(headers), 11 | args=(dict(headers.items()), ) 12 | ) 13 | 14 | 15 | def pretty_request(request, ctx): 16 | 17 | kwargs = [ 18 | ('method', request.method), 19 | ('url', request.url), 20 | ] 21 | 22 | if request.cookies: 23 | kwargs.append(('cookies', request.cookies)) 24 | 25 | if request.auth: 26 | kwargs.append(('auth', request.auth)) 27 | 28 | if request.json: 29 | kwargs.append(('json', request.json)) 30 | 31 | if request.data: 32 | kwargs.append(('data', request.data)) 33 | 34 | if request.files: 35 | kwargs.append(('files', request.files)) 36 | 37 | if request.headers: 38 | kwargs.append(('headers', request.headers)) 39 | 40 | if request.params: 41 | kwargs.append(('params', request.params)) 42 | 43 | if request.hooks: 44 | from requests.hooks import default_hooks 45 | if request.hooks != default_hooks(): 46 | kwargs.append(('hooks', request.hooks)) 47 | 48 | return pretty_call_alt( 49 | ctx, 50 | 'requests.Request', 51 | kwargs=kwargs 52 | ) 53 | 54 | 55 | def pretty_prepared_request(request, ctx): 56 | from requests.hooks import default_hooks 57 | 58 | kwargs = [ 59 | ('method', request.method), 60 | ('url', request.url), 61 | ] 62 | 63 | if request.headers: 64 | kwargs.append(('headers', request.headers)) 65 | 66 | if request.body is not None: 67 | count_bytes = len(request.body) 68 | 69 | count_display_bytes = 10 70 | count_bytes = len(request.body) 71 | 72 | if count_bytes > count_display_bytes: 73 | truncated_body = comment( 74 | request.body[:count_display_bytes], 75 | '... and {} more bytes'.format(count_bytes - count_display_bytes) 76 | ) 77 | else: 78 | truncated_body = request.body 79 | 80 | kwargs.append(( 81 | 'body', 82 | truncated_body 83 | )) 84 | 85 | if request.hooks != default_hooks(): 86 | kwargs.append(('hooks', request.hooks)) 87 | 88 | return pretty_call_alt( 89 | ctx, 90 | 'requests.PreparedRequest', 91 | kwargs=kwargs 92 | ) 93 | 94 | 95 | def pretty_response(resp, ctx): 96 | content_consumed = bool(resp._content_consumed) 97 | 98 | if not content_consumed: 99 | return comment( 100 | pretty_call_alt( 101 | ctx, 102 | 'requests.Response', 103 | kwargs=[ 104 | ('status_code', comment(resp.status_code, resp.reason)), 105 | ('url', resp.url), 106 | ('elapsed', resp.elapsed), 107 | ('headers', resp.headers) 108 | ] 109 | ), 110 | 'Response content not loaded yet' 111 | ) 112 | 113 | kwargs = [ 114 | ('url', resp.url), 115 | ('status_code', comment(resp.status_code, resp.reason)), 116 | ('elapsed', resp.elapsed), 117 | ('headers', resp.headers), 118 | ] 119 | 120 | has_valid_json_payload = False 121 | if resp.headers.get('Content-Type', 'text/plain').startswith('application/json'): 122 | try: 123 | data = resp.json() 124 | except ValueError: 125 | pass 126 | else: 127 | has_valid_json_payload = True 128 | kwargs.append(('json', comment(data, 'Access with .json()'))) 129 | 130 | if not has_valid_json_payload: 131 | text = resp.text 132 | count_chars_truncated = max(0, len(text) - MAX_CONTENT_CHARS) 133 | 134 | if count_chars_truncated: 135 | truncated = text[:MAX_CONTENT_CHARS] 136 | kwargs.append(( 137 | 'text', 138 | comment(truncated, '{} characters truncated'.format(count_chars_truncated)) 139 | )) 140 | else: 141 | kwargs.append(('text', text)) 142 | 143 | return pretty_call_alt( 144 | ctx, 145 | 'requests.Response', 146 | kwargs=kwargs 147 | ) 148 | 149 | 150 | def pretty_session(session, ctx): 151 | from requests.models import DEFAULT_REDIRECT_LIMIT 152 | 153 | kwargs = [] 154 | 155 | if session.headers: 156 | kwargs.append(('headers', session.headers)) 157 | 158 | if session.auth is not None: 159 | kwargs.append(('auth', session.auth)) 160 | 161 | if session.params: 162 | kwargs.append(('params', session.params)) 163 | 164 | if session.stream: 165 | kwargs.append(('stream', session.stream)) 166 | 167 | if session.cert is not None: 168 | kwargs.append(('cert', session.cert)) 169 | 170 | if session.max_redirects != DEFAULT_REDIRECT_LIMIT: 171 | kwargs.append(('max_redirects', session.max_redirects)) 172 | 173 | if session.cookies: 174 | kwargs.append(('cookies', session.cookies)) 175 | 176 | return pretty_call_alt( 177 | ctx, 178 | 'requests.Session', 179 | kwargs=kwargs 180 | ) 181 | 182 | 183 | def install(): 184 | register_pretty('requests.structures.CaseInsensitiveDict')(pretty_headers) 185 | register_pretty('requests.sessions.Session')(pretty_session) 186 | register_pretty('requests.models.Response')(pretty_response) 187 | register_pretty('requests.models.Request')(pretty_request) 188 | register_pretty('requests.models.PreparedRequest')(pretty_prepared_request) 189 | -------------------------------------------------------------------------------- /prettyprinter/layout.py: -------------------------------------------------------------------------------- 1 | """ 2 | The layout algorithm here was inspired by the following 3 | papers and libraries: 4 | 5 | - Wadler, P. (1998). A prettier printer 6 | https://homepages.inf.ed.ac.uk/wadler/papers/prettier/prettier.pdf 7 | - Lindig, C. (2000) Strictly Pretty 8 | http://citeseerx.ist.psu.edu/viewdoc/summary?doi=10.1.1.34.2200 9 | - Extensions to the Wadler pretty printer by Daniel Leijen in the 10 | Haskell package 'wl-pprint' 11 | https://hackage.haskell.org/package/wl-pprint-1.2/docs/Text-PrettyPrint-Leijen.html 12 | - The Haskell 'prettyprinter' package, which builds on top of the 13 | 'ansi-wl-pprint' package. 14 | https://hackage.haskell.org/package/prettyprinter 15 | - The JavaScript Prettier library 16 | https://github.com/prettier/prettier 17 | """ 18 | 19 | from copy import copy 20 | 21 | from .doctypes import ( 22 | NIL, 23 | HARDLINE, 24 | AlwaysBreak, 25 | Annotated, 26 | Concat, 27 | Contextual, 28 | FlatChoice, 29 | Fill, 30 | Group, 31 | Nest, 32 | normalize_doc, 33 | ) 34 | from .sdoctypes import ( 35 | SLine, 36 | SAnnotationPop, 37 | SAnnotationPush, 38 | ) 39 | 40 | 41 | BREAK_MODE = 0 42 | FLAT_MODE = 1 43 | 44 | 45 | def fast_fitting_predicate( 46 | page_width, # Ignored. 47 | ribbon_frac, # Ignored. 48 | min_nesting_level, # Ignored. 49 | max_width, 50 | triplestack 51 | ): 52 | """ 53 | One element lookahead. Fast, but not the prettiest. 54 | """ 55 | 56 | chars_left = max_width 57 | 58 | while chars_left >= 0: 59 | if not triplestack: 60 | return True 61 | 62 | indent, mode, doc = triplestack.pop() 63 | if doc is NIL: 64 | continue 65 | elif isinstance(doc, str): 66 | chars_left -= len(doc) 67 | elif isinstance(doc, Concat): 68 | # Recursive call in Strictly Pretty: docs within Concat 69 | # are processed in order, with keeping the current 70 | # indentation and mode. 71 | # We want the leftmost element at the top of the stack, 72 | # so we append the concatenated documents in reverse order. 73 | triplestack.extend( 74 | (indent, mode, doc) 75 | for doc in reversed(doc.docs) 76 | ) 77 | elif isinstance(doc, Annotated): 78 | triplestack.append((indent, mode, doc.doc)) 79 | elif isinstance(doc, Fill): 80 | triplestack.extend( 81 | (indent, mode, doc) 82 | for doc in reversed(doc.docs) 83 | ) 84 | elif isinstance(doc, Nest): 85 | # Nest is a combination of an indent and a doc. 86 | # Increase indentation, then add the doc for processing. 87 | triplestack.append((indent + doc.indent, mode, doc.doc)) 88 | elif isinstance(doc, AlwaysBreak): 89 | return False 90 | triplestack.append((indent, BREAK_MODE, doc.doc)) 91 | elif doc is HARDLINE: 92 | return True 93 | elif isinstance(doc, FlatChoice): 94 | if mode is FLAT_MODE: 95 | triplestack.append((indent, mode, doc.when_flat)) 96 | elif mode is BREAK_MODE: 97 | triplestack.append((indent, mode, doc.when_broken)) 98 | else: 99 | raise ValueError 100 | elif isinstance(doc, Group): 101 | # Group just changes the mode. 102 | triplestack.append((indent, FLAT_MODE, doc.doc)) 103 | elif isinstance(doc, Contextual): 104 | ribbon_width = max(0, min(page_width, round(ribbon_frac * page_width))) 105 | 106 | evaluated_doc = doc.fn( 107 | indent=indent, 108 | column=max_width - chars_left, 109 | page_width=page_width, 110 | ribbon_width=ribbon_width, 111 | ) 112 | normalized = normalize_doc(evaluated_doc) 113 | triplestack.append((indent, mode, normalized)) 114 | elif isinstance(doc, SAnnotationPush): 115 | continue 116 | elif isinstance(doc, SAnnotationPop): 117 | continue 118 | else: 119 | raise ValueError((indent, mode, doc)) 120 | 121 | return False 122 | 123 | 124 | def smart_fitting_predicate( 125 | page_width, 126 | ribbon_frac, 127 | min_nesting_level, 128 | max_width, 129 | triplestack 130 | ): 131 | """ 132 | Lookahead until the last doc at the current indentation level. 133 | Pretty, but not as fast. 134 | """ 135 | chars_left = max_width 136 | 137 | while chars_left >= 0: 138 | if not triplestack: 139 | return True 140 | 141 | indent, mode, doc = triplestack.pop() 142 | 143 | if doc is NIL: 144 | continue 145 | elif isinstance(doc, str): 146 | chars_left -= len(doc) 147 | elif isinstance(doc, Concat): 148 | # Recursive call in Strictly Pretty: docs within Concat 149 | # are processed in order, with keeping the current 150 | # indentation and mode. 151 | # We want the leftmost element at the top of the stack, 152 | # so we append the concatenated documents in reverse order. 153 | triplestack.extend( 154 | (indent, mode, doc) 155 | for doc in reversed(doc.docs) 156 | ) 157 | elif isinstance(doc, Annotated): 158 | triplestack.append((indent, mode, doc.doc)) 159 | elif isinstance(doc, Fill): 160 | # Same as the Concat case. 161 | triplestack.extend( 162 | (indent, mode, doc) 163 | for doc in reversed(doc.docs) 164 | ) 165 | elif isinstance(doc, Nest): 166 | # Nest is a combination of an indent and a doc. 167 | # Increase indentation, then add the doc for processing. 168 | triplestack.append((indent + doc.indent, mode, doc.doc)) 169 | elif isinstance(doc, AlwaysBreak): 170 | return False 171 | elif doc is HARDLINE: 172 | # In the fast algorithm, when we see a line, 173 | # we return True. Here, as long as the minimum indentation 174 | # level is satisfied, we continue processing the next line. 175 | # This causes the longer runtime. 176 | if indent > min_nesting_level: 177 | chars_left = page_width - indent 178 | else: 179 | return True 180 | elif isinstance(doc, FlatChoice): 181 | if mode is FLAT_MODE: 182 | triplestack.append((indent, mode, doc.when_flat)) 183 | elif mode is BREAK_MODE: 184 | triplestack.append((indent, mode, doc.when_broken)) 185 | else: 186 | raise ValueError 187 | elif isinstance(doc, Group): 188 | # Group just changes the mode. 189 | triplestack.append((indent, FLAT_MODE, doc.doc)) 190 | elif isinstance(doc, Contextual): 191 | ribbon_width = max(0, min(page_width, round(ribbon_frac * page_width))) 192 | 193 | evaluated_doc = doc.fn( 194 | indent=indent, 195 | column=max_width - chars_left, 196 | page_width=page_width, 197 | ribbon_width=ribbon_width, 198 | ) 199 | normalized = normalize_doc(evaluated_doc) 200 | triplestack.append((indent, mode, normalized)) 201 | elif isinstance(doc, SAnnotationPush): 202 | continue 203 | elif isinstance(doc, SAnnotationPop): 204 | continue 205 | else: 206 | raise ValueError((indent, mode, doc)) 207 | 208 | return False 209 | 210 | 211 | def best_layout( 212 | doc, 213 | width, 214 | ribbon_frac, 215 | fitting_predicate, 216 | outcol=0, 217 | mode=BREAK_MODE 218 | ): 219 | normalized = normalize_doc(doc) 220 | 221 | ribbon_width = max(0, min(width, round(ribbon_frac * width))) 222 | 223 | # The Strictly Pretty paper shows a recursive algorithm. 224 | # This is the stack-and-loop version of it. 225 | triplestack = [(outcol, mode, normalized)] 226 | 227 | while triplestack: 228 | indent, mode, doc = triplestack.pop() 229 | 230 | if doc is NIL: 231 | # Nothing to do here. 232 | continue 233 | 234 | if doc is HARDLINE: 235 | yield SLine(indent) 236 | outcol = indent 237 | elif isinstance(doc, str): 238 | yield doc 239 | outcol += len(doc) 240 | elif isinstance(doc, Concat): 241 | # Add the docs to the stack and process them. 242 | # The first doc in the concatenation must 243 | # end up at the top of the stack, hence the reversing. 244 | triplestack.extend( 245 | (indent, mode, child) 246 | for child in reversed(doc.docs) 247 | ) 248 | elif isinstance(doc, Contextual): 249 | evaluated_doc = doc.fn( 250 | indent=indent, 251 | column=outcol, 252 | page_width=width, 253 | ribbon_width=ribbon_width, 254 | ) 255 | normalized = normalize_doc(evaluated_doc) 256 | triplestack.append((indent, mode, normalized)) 257 | elif isinstance(doc, Annotated): 258 | yield SAnnotationPush(doc.annotation) 259 | # Usually, the triplestack is solely a stack of docs. 260 | # SAnnotationPop is a special case: when we find an annotated doc, 261 | # we output the SAnnotationPush SDoc directly. The equivalent 262 | # SAnnotationPop must be output after all the nested docs have been 263 | # processed. An easy way to do this is to add the SAnnotationPop 264 | # directly to the stack and output it when we see it. 265 | triplestack.append((indent, mode, SAnnotationPop(doc.annotation))) 266 | triplestack.append((indent, mode, doc.doc)) 267 | elif isinstance(doc, FlatChoice): 268 | if mode is BREAK_MODE: 269 | triplestack.append((indent, mode, doc.when_broken)) 270 | elif mode is FLAT_MODE: 271 | triplestack.append((indent, mode, doc.when_flat)) 272 | else: 273 | raise ValueError 274 | elif isinstance(doc, Nest): 275 | # Increase indentation and process the nested doc. 276 | triplestack.append((indent + doc.indent, mode, doc.doc)) 277 | elif isinstance(doc, Group): 278 | new_triplestack = copy(triplestack) 279 | # The line will consist of the Grouped doc, as well as the rest 280 | # of the docs in the stack. 281 | new_triplestack.append((indent, FLAT_MODE, doc.doc)) 282 | 283 | min_nesting_level = min(outcol, indent) 284 | 285 | columns_left_in_line = width - outcol 286 | columns_left_in_ribbon = indent + ribbon_width - outcol 287 | available_width = min(columns_left_in_line, columns_left_in_ribbon) 288 | 289 | if fitting_predicate( 290 | page_width=width, 291 | ribbon_frac=ribbon_frac, 292 | min_nesting_level=min_nesting_level, 293 | max_width=available_width, 294 | triplestack=new_triplestack 295 | ): 296 | # This group will fit on a single line. Continue processing 297 | # the grouped doc in flat mode. 298 | triplestack.append((indent, FLAT_MODE, doc.doc)) 299 | else: 300 | triplestack.append((indent, BREAK_MODE, doc.doc)) 301 | elif isinstance(doc, Fill): 302 | # docs must be alternating whitespace 303 | docs = doc.docs 304 | 305 | if not docs: 306 | continue 307 | 308 | first_doc = docs[0] 309 | flat_content_triple = (indent, FLAT_MODE, first_doc) 310 | broken_content_triple = (indent, BREAK_MODE, first_doc) 311 | 312 | # this is just copy pasted from the group case... 313 | min_nesting_level = min(outcol, indent) 314 | 315 | columns_left_in_line = width - outcol 316 | columns_left_in_ribbon = indent + ribbon_width - outcol 317 | available_width = min(columns_left_in_line, columns_left_in_ribbon) 318 | 319 | does_fit = fast_fitting_predicate( 320 | page_width=width, 321 | ribbon_frac=ribbon_frac, 322 | min_nesting_level=min_nesting_level, 323 | max_width=available_width, 324 | triplestack=[flat_content_triple] 325 | ) 326 | 327 | if len(docs) == 1: 328 | if does_fit: 329 | triplestack.append(flat_content_triple) 330 | else: 331 | triplestack.append(broken_content_triple) 332 | continue 333 | 334 | whitespace = docs[1] 335 | flat_whitespace_triple = (indent, FLAT_MODE, whitespace) 336 | broken_whitespace_triple = (indent, BREAK_MODE, whitespace) 337 | 338 | if len(docs) == 2: 339 | if does_fit: 340 | triplestack.append(flat_whitespace_triple) 341 | triplestack.append(flat_content_triple) 342 | else: 343 | triplestack.append(broken_whitespace_triple) 344 | triplestack.append(broken_content_triple) 345 | 346 | continue 347 | 348 | remaining = docs[2:] 349 | remaining_triple = (indent, mode, Fill(remaining)) 350 | 351 | fst_and_snd_content_flat_triple = (indent, FLAT_MODE, Concat(docs[:2])) 352 | 353 | fst_and_snd_content_does_fit = fast_fitting_predicate( 354 | page_width=width, 355 | ribbon_frac=ribbon_frac, 356 | min_nesting_level=min_nesting_level, 357 | max_width=available_width, 358 | triplestack=[fst_and_snd_content_flat_triple] 359 | ) 360 | 361 | if fst_and_snd_content_does_fit: 362 | triplestack.append(remaining_triple) 363 | triplestack.append(flat_whitespace_triple) 364 | triplestack.append(flat_content_triple) 365 | elif does_fit: 366 | triplestack.append(remaining_triple) 367 | triplestack.append(broken_whitespace_triple) 368 | triplestack.append(flat_content_triple) 369 | else: 370 | triplestack.append(remaining_triple) 371 | triplestack.append(broken_whitespace_triple) 372 | triplestack.append(broken_content_triple) 373 | elif isinstance(doc, AlwaysBreak): 374 | triplestack.append((indent, BREAK_MODE, doc.doc)) 375 | elif isinstance(doc, SAnnotationPop): 376 | yield doc 377 | else: 378 | raise ValueError((indent, mode, doc)) 379 | 380 | 381 | def layout_smart(doc, width=79, ribbon_frac=0.9): 382 | return best_layout( 383 | doc, 384 | width, 385 | ribbon_frac, 386 | fitting_predicate=smart_fitting_predicate, 387 | ) 388 | 389 | 390 | def layout_fast(doc, width=79, ribbon_frac=0.9): 391 | return best_layout( 392 | doc, 393 | width, 394 | ribbon_frac, 395 | fitting_predicate=fast_fitting_predicate, 396 | ) 397 | -------------------------------------------------------------------------------- /prettyprinter/pretty_stdlib.py: -------------------------------------------------------------------------------- 1 | from collections import ( 2 | ChainMap, 3 | Counter, 4 | OrderedDict, 5 | defaultdict, 6 | deque, 7 | ) 8 | from datetime import ( 9 | datetime, 10 | timedelta, 11 | tzinfo, 12 | timezone, 13 | date, 14 | time, 15 | ) 16 | from itertools import chain, dropwhile 17 | import re 18 | 19 | from .doc import ( 20 | concat, 21 | group, 22 | ) 23 | 24 | from .prettyprinter import ( 25 | ADD_OP, 26 | MUL_OP, 27 | NEG_OP, 28 | comment, 29 | build_fncall, 30 | classattr, 31 | identifier, 32 | register_pretty, 33 | pretty_call_alt, 34 | pretty_python_value, 35 | pretty_str, 36 | ) 37 | 38 | try: 39 | import pytz 40 | except ImportError: 41 | _PYTZ_INSTALLED = False 42 | else: 43 | _PYTZ_INSTALLED = True 44 | 45 | 46 | @register_pretty('uuid.UUID') 47 | def pretty_uuid(value, ctx): 48 | return pretty_call_alt(ctx, type(value), args=(str(value), )) 49 | 50 | 51 | @register_pretty(datetime) 52 | def pretty_datetime(dt, ctx): 53 | dt_kwargs = [ 54 | (k, getattr(dt, k)) 55 | for k in ( 56 | 'microsecond', 57 | 'second', 58 | 'minute', 59 | 'hour', 60 | 'day', 61 | 'month', 62 | 'year', 63 | ) 64 | ] 65 | 66 | kwargs = list(reversed(list( 67 | dropwhile( 68 | lambda k__v: k__v[1] == 0, 69 | dt_kwargs 70 | ) 71 | ))) 72 | 73 | if dt.tzinfo is not None: 74 | kwargs.append(('tzinfo', dt.tzinfo)) 75 | 76 | # Doesn't exist before Python 3.6 77 | if getattr(dt, 'fold', None): 78 | kwargs.append(('fold', 1)) 79 | 80 | if len(kwargs) == 3: # year, month, day 81 | return pretty_call_alt( 82 | ctx, 83 | datetime, 84 | args=( 85 | dt.year, 86 | dt.month, 87 | dt.day 88 | ) 89 | ) 90 | 91 | return pretty_call_alt(ctx, datetime, kwargs=kwargs) 92 | 93 | 94 | @register_pretty(tzinfo) 95 | def pretty_tzinfo(value, ctx): 96 | if value == timezone.utc: 97 | return identifier('datetime.timezone.utc') 98 | elif _PYTZ_INSTALLED and value == pytz.utc: 99 | return identifier('pytz.utc') 100 | else: 101 | return repr(value) 102 | 103 | 104 | @register_pretty(timezone) 105 | def pretty_timezone(tz, ctx): 106 | if tz == timezone.utc: 107 | return identifier('datetime.timezone.utc') 108 | 109 | if tz._name is None: 110 | return pretty_call_alt(ctx, timezone, args=(tz._offset, )) 111 | return pretty_call_alt(ctx, timezone, args=(tz._offset, tz._name)) 112 | 113 | 114 | def pretty_pytz_timezone(tz, ctx): 115 | if tz == pytz.utc: 116 | return identifier('pytz.utc') 117 | return pretty_call_alt(ctx, pytz.timezone, args=(tz.zone, )) 118 | 119 | 120 | def pretty_pytz_dst_timezone(tz, ctx): 121 | if tz.zone and pytz.timezone(tz.zone) == tz: 122 | return pretty_pytz_timezone(tz, ctx) 123 | 124 | calldoc = pretty_call_alt( 125 | ctx, 126 | pytz.tzinfo.DstTzInfo, 127 | args=((tz._utcoffset, tz._dst, tz._tzname), ) 128 | ) 129 | 130 | if tz.zone: 131 | return comment( 132 | calldoc, 133 | 'In timezone {}'.format(tz.zone) 134 | ) 135 | return calldoc 136 | 137 | 138 | if _PYTZ_INSTALLED: 139 | register_pretty(pytz.tzinfo.BaseTzInfo)(pretty_pytz_timezone) 140 | register_pretty(pytz.tzinfo.DstTzInfo)(pretty_pytz_dst_timezone) 141 | 142 | 143 | @register_pretty(time) 144 | def pretty_time(value, ctx): 145 | timekws_to_display = reversed( 146 | list( 147 | dropwhile( 148 | lambda kw: getattr(value, kw) == 0, 149 | ('microsecond', 'second', 'minute', 'hour') 150 | ) 151 | ) 152 | ) 153 | 154 | additional_kws = [] 155 | if value.tzinfo is not None: 156 | additional_kws.append(('tzinfo', value.tzinfo)) 157 | 158 | if getattr(value, 'fold', 0) != 0: 159 | additional_kws.append(('fold', value.fold)) 160 | 161 | kwargs = chain( 162 | ( 163 | (kw, getattr(value, kw)) 164 | for kw in timekws_to_display 165 | ), 166 | additional_kws 167 | ) 168 | 169 | return pretty_call_alt( 170 | ctx, 171 | time, 172 | kwargs=kwargs 173 | ) 174 | 175 | 176 | @register_pretty(date) 177 | def pretty_date(value, ctx): 178 | return pretty_call_alt( 179 | ctx, 180 | date, 181 | args=(value.year, value.month, value.day) 182 | ) 183 | 184 | 185 | @register_pretty(timedelta) 186 | def pretty_timedelta(delta, ctx): 187 | if ctx.depth_left == 0: 188 | return pretty_call_alt(ctx, timedelta, args=(..., )) 189 | 190 | pos_delta = abs(delta) 191 | negative = delta != pos_delta 192 | 193 | days = pos_delta.days 194 | seconds = pos_delta.seconds 195 | microseconds = pos_delta.microseconds 196 | 197 | minutes, seconds = divmod(seconds, 60) 198 | hours, minutes = divmod(minutes, 60) 199 | milliseconds, microseconds = divmod(microseconds, 1000) 200 | 201 | attrs = [ 202 | ('days', days), 203 | ('hours', hours), 204 | ('minutes', minutes), 205 | ('seconds', seconds), 206 | ('milliseconds', milliseconds), 207 | ('microseconds', microseconds), 208 | ] 209 | 210 | kwargdocs = [ 211 | (k, pretty_python_value(v, ctx=ctx.nested_call())) 212 | for k, v in attrs 213 | if v != 0 214 | ] 215 | 216 | if kwargdocs and kwargdocs[0][0] == 'days': 217 | years, days = divmod(days, 365) 218 | if years: 219 | _docs = [] 220 | 221 | if years > 1: 222 | _docs.extend([ 223 | pretty_python_value(years, ctx), 224 | ' ', 225 | MUL_OP, 226 | ' ' 227 | ]) 228 | 229 | _docs.append(pretty_python_value(365, ctx)) 230 | 231 | if days: 232 | _docs.extend([ 233 | ' ', 234 | ADD_OP, 235 | ' ', 236 | pretty_python_value(days, ctx) 237 | ]) 238 | 239 | kwargdocs[0] = ('days', concat(_docs)) 240 | 241 | doc = group( 242 | build_fncall( 243 | ctx, 244 | timedelta, 245 | kwargdocs=kwargdocs, 246 | ) 247 | ) 248 | 249 | if negative: 250 | doc = concat([NEG_OP, doc]) 251 | 252 | return doc 253 | 254 | 255 | @register_pretty(ChainMap) 256 | def pretty_chainmap(value, ctx): 257 | constructor = type(value) 258 | if ( 259 | not value.maps or 260 | len(value.maps) == 1 and 261 | not value.maps[0] 262 | ): 263 | return pretty_call_alt(ctx, constructor) 264 | 265 | return pretty_call_alt(ctx, constructor, args=value.maps) 266 | 267 | 268 | @register_pretty(defaultdict) 269 | def pretty_defaultdict(d, ctx): 270 | constructor = type(d) 271 | return pretty_call_alt( 272 | ctx, 273 | constructor, 274 | args=(d.default_factory, dict(d)) 275 | ) 276 | 277 | 278 | @register_pretty(deque) 279 | def pretty_deque(value, ctx): 280 | kwargs = [] 281 | if value.maxlen is not None: 282 | kwargs.append(('maxlen', value.maxlen)) 283 | 284 | return pretty_call_alt( 285 | ctx, 286 | type(value), 287 | args=(list(value), ), 288 | kwargs=kwargs 289 | ) 290 | 291 | 292 | @register_pretty(OrderedDict) 293 | def pretty_ordereddict(d, ctx): 294 | return pretty_call_alt(ctx, type(d), args=(list(d.items()), )) 295 | 296 | 297 | @register_pretty(Counter) 298 | def pretty_counter(counter, ctx): 299 | return pretty_call_alt( 300 | ctx, 301 | type(counter), 302 | args=(dict(counter.most_common()), ), 303 | ) 304 | 305 | 306 | @register_pretty('enum.Enum') 307 | def pretty_enum(value, ctx): 308 | cls = type(value) 309 | return classattr(cls, value.name) 310 | 311 | 312 | @register_pretty('builtins.mappingproxy') 313 | def pretty_mappingproxy(value, ctx): 314 | return pretty_call_alt(ctx, type(value), args=(dict(value), )) 315 | 316 | 317 | @register_pretty('functools.partial') 318 | @register_pretty('functools.partialmethod') 319 | def pretty_partial(value, ctx): 320 | constructor = type(value) 321 | return pretty_call_alt( 322 | ctx, 323 | constructor, 324 | args=(value.func, ) + value.args, 325 | kwargs=value.keywords 326 | ) 327 | 328 | 329 | @register_pretty(BaseException) 330 | def pretty_baseexception(exc, ctx): 331 | return pretty_call_alt( 332 | ctx, 333 | type(exc), 334 | args=exc.args 335 | ) 336 | 337 | 338 | @register_pretty('_ast.AST') 339 | def pretty_nodes(value, ctx): 340 | cls = type(value) 341 | kwargs = [(k, getattr(value, k, None)) for k in value._fields] 342 | if cls.__module__ == '_ast': 343 | cls_name = 'ast.%s' % cls.__qualname__ 344 | else: 345 | cls_name = cls 346 | return pretty_call_alt(ctx, cls_name, kwargs=kwargs) 347 | 348 | 349 | pathstr_split_pattern = re.compile("(/+)") 350 | 351 | 352 | @register_pretty('pathlib.PurePath') 353 | def pretty_path(value, ctx): 354 | strdoc = pretty_str( 355 | value.as_posix(), 356 | ctx, 357 | split_pattern=pathstr_split_pattern 358 | ) 359 | return build_fncall(ctx, type(value), argdocs=(strdoc, )) 360 | -------------------------------------------------------------------------------- /prettyprinter/render.py: -------------------------------------------------------------------------------- 1 | from io import StringIO 2 | 3 | from .sdoctypes import SLine 4 | from .utils import rfind_idx 5 | 6 | 7 | def as_lines(sdocs): 8 | it = iter(sdocs) 9 | currline = [] 10 | for sdoc in it: 11 | if not isinstance(sdoc, SLine): 12 | currline.append(sdoc) 13 | else: 14 | yield currline 15 | currline = [sdoc] 16 | 17 | if currline: 18 | yield currline 19 | 20 | 21 | def default_render_to_stream(stream, sdocs, newline='\n', separator=' '): 22 | evald = list(sdocs) 23 | 24 | if not evald: 25 | return 26 | 27 | for sdoc_line in as_lines(evald): 28 | last_text_sdoc_idx = rfind_idx( 29 | lambda sdoc: isinstance(sdoc, str), 30 | sdoc_line 31 | ) 32 | 33 | # Edge case: trailing whitespace on a line. 34 | # Currently happens on multiline str value in a dict: 35 | # there's a trailing whitespace after the colon that's 36 | # hard to eliminate at the doc level. 37 | if last_text_sdoc_idx != -1: 38 | last_text_sdoc = sdoc_line[last_text_sdoc_idx] 39 | sdoc_line[last_text_sdoc_idx] = last_text_sdoc.rstrip() 40 | 41 | for sdoc in sdoc_line: 42 | if isinstance(sdoc, str): 43 | stream.write(sdoc) 44 | elif isinstance(sdoc, SLine): 45 | stream.write(newline + separator * sdoc.indent) 46 | 47 | 48 | def default_render_to_str(sdocs, newline='\n', separator=' '): 49 | stream = StringIO() 50 | default_render_to_stream(stream, sdocs, newline, separator) 51 | return stream.getvalue() 52 | -------------------------------------------------------------------------------- /prettyprinter/sdoctypes.py: -------------------------------------------------------------------------------- 1 | 2 | class SDoc(object): 3 | pass 4 | 5 | 6 | class SLine(SDoc): 7 | __slots__ = ('indent', ) 8 | 9 | def __init__(self, indent): 10 | assert isinstance(indent, int) 11 | self.indent = indent 12 | 13 | def __repr__(self): 14 | return 'SLine({})'.format(repr(self.indent)) 15 | 16 | 17 | class SAnnotationPush(SDoc): 18 | __slots__ = ('value', ) 19 | 20 | def __init__(self, value): 21 | self.value = value 22 | 23 | def __repr__(self): 24 | return 'SAnnotationPush({})'.format(repr(self.value)) 25 | 26 | 27 | class SAnnotationPop(SDoc): 28 | __slots__ = ('value', ) 29 | 30 | def __init__(self, value): 31 | self.value = value 32 | 33 | def __repr__(self): 34 | return 'SAnnotationPush({})'.format(repr(self.value)) 35 | -------------------------------------------------------------------------------- /prettyprinter/syntax.py: -------------------------------------------------------------------------------- 1 | from enum import IntEnum, unique 2 | 3 | 4 | @unique 5 | class Token(IntEnum): 6 | KEYWORD_CONSTANT = 1 7 | NAME_BUILTIN = 2 8 | NAME_ENTITY = 3 9 | NAME_FUNCTION = 4 10 | NAME_VARIABLE = 5 11 | LITERAL_STRING = 6 12 | STRING_AFFIX = 7 13 | STRING_ESCAPE = 8 14 | NUMBER_BINARY = 9 15 | NUMBER_FLOAT = 10 16 | NUMBER_INT = 11 17 | OPERATOR = 12 18 | PUNCTUATION = 13 19 | COMMENT_SINGLE = 14 20 | -------------------------------------------------------------------------------- /prettyprinter/utils.py: -------------------------------------------------------------------------------- 1 | from itertools import islice 2 | import shutil 3 | 4 | 5 | def intersperse(x, ys): 6 | """ 7 | Returns an iterable where ``x`` is inserted between 8 | each element of ``ys`` 9 | 10 | :type ys: Iterable 11 | """ 12 | it = iter(ys) 13 | 14 | try: 15 | y = next(it) 16 | except StopIteration: 17 | return 18 | 19 | yield y 20 | 21 | for y in it: 22 | yield x 23 | yield y 24 | 25 | 26 | def find(predicate, iterable, default=None): 27 | filtered = iter((x for x in iterable if predicate(x))) 28 | return next(filtered, default) 29 | 30 | 31 | def rfind_idx(predicate, seq): 32 | length = len(seq) 33 | for i, el in enumerate(reversed(seq)): 34 | if predicate(el): 35 | return length - i - 1 36 | return -1 37 | 38 | 39 | def identity(x): 40 | return x 41 | 42 | 43 | def get_terminal_width(default=79): 44 | return shutil.get_terminal_size((default, None)).columns 45 | 46 | 47 | def take(n, iterable): 48 | return islice(iterable, n) 49 | 50 | 51 | def compose(f, g): 52 | if f is identity: 53 | return g 54 | if g is identity: 55 | return f 56 | 57 | def composed(x): 58 | return f(g(x)) 59 | 60 | composed.__name__ = 'composed_{}_then_{}'.format( 61 | g.__name__, 62 | f.__name__ 63 | ) 64 | 65 | return composed 66 | -------------------------------------------------------------------------------- /prettyprinterlightscreenshot.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/tommikaikkonen/prettyprinter/53ba5f934f24228315ef10898fc2b73370349696/prettyprinterlightscreenshot.png -------------------------------------------------------------------------------- /prettyprinterscreenshot.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/tommikaikkonen/prettyprinter/53ba5f934f24228315ef10898fc2b73370349696/prettyprinterscreenshot.png -------------------------------------------------------------------------------- /requirements_dev.txt: -------------------------------------------------------------------------------- 1 | pip==9.0.1 2 | hypothesis==3.33.0 3 | bumpversion==0.5.3 4 | wheel==0.29.0 5 | watchdog==0.8.3 6 | flake8==3.5.0 7 | tox==2.9.1 8 | coverage==4.4.2 9 | Sphinx==1.6.5 10 | cryptography==1.7 11 | PyYAML==3.11 12 | pytest==4.3.0 13 | pytest-runner==3.0 14 | pycodestyle==2.3.1 15 | colorful==0.4.0 16 | Pygments==2.2.0 17 | dataclasses==0.3 18 | ipython==6.2.1 19 | requests==2.21.0 20 | pytz==2017.3 21 | attrs==17.4.0 22 | Django==1.10.8 23 | pytest-django==3.4.7 24 | pytest-pythonpath==0.7.3 25 | numpy==1.16.1 26 | -------------------------------------------------------------------------------- /setup.cfg: -------------------------------------------------------------------------------- 1 | [bumpversion] 2 | current_version = 0.18.0 3 | commit = True 4 | tag = True 5 | 6 | [bumpversion:file:setup.py] 7 | search = version='{current_version}' 8 | replace = version='{new_version}' 9 | 10 | [bumpversion:file:prettyprinter/__init__.py] 11 | search = __version__ = '{current_version}' 12 | replace = __version__ = '{new_version}' 13 | 14 | [bdist_wheel] 15 | universal = 1 16 | 17 | [flake8] 18 | exclude = docs 19 | max-line-length = 99 20 | 21 | [tool:pytest] 22 | python_paths = tests/test_django 23 | DJANGO_SETTINGS_MODULE = prettyprinter_testproject.settings 24 | django_find_project = true 25 | 26 | [aliases] 27 | test = pytest 28 | 29 | -------------------------------------------------------------------------------- /setup.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # -*- coding: utf-8 -*- 3 | 4 | """The setup script.""" 5 | 6 | from setuptools import setup, find_packages 7 | 8 | with open('README.rst') as readme_file: 9 | readme = readme_file.read() 10 | 11 | with open('HISTORY.rst') as history_file: 12 | history = history_file.read() 13 | 14 | requirements = [ 15 | 'colorful>=0.4.0', 16 | 'Pygments>=2.2.0', 17 | ] 18 | 19 | setup_requirements = [ 20 | 'pytest-runner==3.0', 21 | # TODO(tommikaikkonen): put setup requirements (distutils extensions, etc.) here 22 | ] 23 | 24 | test_requirements = [ 25 | 'pytest==4.3.0', 26 | 'hypothesis==3.33.0', 27 | 'dataclasses==0.6', 28 | 'django>=1.10.8', 29 | 'requests==2.21.0', 30 | 'attrs==17.4.0', 31 | 'IPython==6.2.1', 32 | 'pytz==2017.3', 33 | 'tox-pyenv==1.1.0', 34 | 'pytest-django==3.4.7', 35 | 'pytest-pythonpath==0.7.3', 36 | 'numpy', 37 | ] 38 | 39 | setup( 40 | name='prettyprinter', 41 | version='0.18.0', 42 | description="Syntax-highlighting, declarative and composable pretty printer for Python 3.5+", 43 | long_description=readme + '\n\n' + history, 44 | author="Tommi Kaikkonen", 45 | author_email='kaikkonentommi@gmail.com', 46 | url='https://github.com/tommikaikkonen/prettyprinter', 47 | packages=find_packages(include=['prettyprinter', 'prettyprinter.extras']), 48 | include_package_data=True, 49 | install_requires=requirements, 50 | license="MIT license", 51 | zip_safe=False, 52 | keywords='prettyprinter', 53 | classifiers=[ 54 | 'Development Status :: 2 - Pre-Alpha', 55 | 'Intended Audience :: Developers', 56 | 'License :: OSI Approved :: MIT License', 57 | 'Natural Language :: English', 58 | 'Programming Language :: Python :: 3.6', 59 | 'Programming Language :: Python :: 3.5', 60 | ], 61 | test_suite='tests', 62 | tests_require=test_requirements, 63 | setup_requires=setup_requirements, 64 | ) 65 | -------------------------------------------------------------------------------- /tests/__init__.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | 3 | """Unit test package for prettyprinter.""" 4 | -------------------------------------------------------------------------------- /tests/conftest.py: -------------------------------------------------------------------------------- 1 | import sys 2 | 3 | from prettyprinter import set_default_config 4 | 5 | # Need this to deterministically test on Python 3.5 6 | set_default_config(sort_dict_keys=True) 7 | 8 | 9 | def pytest_ignore_collect(path, config): 10 | if 'test_dataclasses' in str(path) and sys.version_info < (3, 7): 11 | return True 12 | -------------------------------------------------------------------------------- /tests/perf.py: -------------------------------------------------------------------------------- 1 | from prettyprinter import pformat 2 | import json 3 | 4 | 5 | def main(): 6 | with open('tests/sample_json.json') as f: 7 | data = json.load(f) 8 | 9 | pformat(data) 10 | 11 | 12 | if __name__ == '__main__': 13 | main() 14 | -------------------------------------------------------------------------------- /tests/sample_json.json: -------------------------------------------------------------------------------- 1 | [ 2 | { 3 | "msys": { 4 | "relay_message": { 5 | "content": { 6 | "email_rfc822": "Return-Path: \r\nMIME-Version: 1.0\r\nFrom: me@here.com\r\nReceived: by 10.114.82.10 with HTTP; Mon, 4 Jul 2016 07:53:14 -0700 (PDT)\r\nDate: Mon, 4 Jul 2016 15:53:14 +0100\r\nMessage-ID: <484810298443-112311-xqxbby@mail.there.com>\r\nSubject: Relay webhooks rawk!\r\nTo: you@there.com\r\nContent-Type: multipart/alternative; boundary=deaddeaffeedf00fall45dbhail980dhypnot0ad\r\n\r\n--deaddeaffeedf00fall45dbhail980dhypnot0ad\r\nContent-Type: text/plain; charset=UTF-8\r\nHi there SparkPostians.\r\n\r\n--deaddeaffeedf00fall45dbhail980dhypnot0ad\r\nContent-Type: text/html; charset=UTF-8\r\n\r\n

Hi there SparkPostians

\r\n\r\n--deaddeaffeedf00fall45dbhail980dhypnot0ad--\r\n", 7 | "email_rfc822_is_base64": false, 8 | "headers": [ 9 | { 10 | "Return-Path": "" 11 | }, 12 | { 13 | "MIME-Version": "1.0" 14 | }, 15 | { 16 | "From": "me@here.com" 17 | }, 18 | { 19 | "Received": "by 10.114.82.10 with HTTP; Mon, 4 Jul 2016 07:53:14 -0700 (PDT)" 20 | }, 21 | { 22 | "Date": "Mon, 4 Jul 2016 15:53:14 +0100" 23 | }, 24 | { 25 | "Message-ID": "<484810298443-112311-xqxbby@mail.there.com>" 26 | }, 27 | { 28 | "Subject": "Relay webhooks rawk!" 29 | }, 30 | { 31 | "To": "you@there.com" 32 | } 33 | ], 34 | "html": "

Hi there SparkPostians.

", 35 | "subject": "We come in peace", 36 | "text": "Hi there SparkPostians.", 37 | "to": [ 38 | "your@yourdomain.com" 39 | ] 40 | }, 41 | "customer_id": "1337", 42 | "ok": true, 43 | "not_ok": false, 44 | "unknown": null, 45 | "friendly_from": "me@here.com", 46 | "msg_from": "me@here.com", 47 | "rcpt_to": "you@there.com", 48 | "webhook_id": "4839201967643219", 49 | "lots_of_text": "Philip Lee Wadler (born April 8, 1956) is an American computer scientist known for his contributions to programming language design and type theory. In particular, he has contributed to the theory behind functional programming[8] and the use of monads in functional programming, the design of the purely functional language Haskell,[9] and the XQuery declarative query language. In 1984, he created the Orwell programming language. Wadler was involved in adding generic types to Java 5.0.[10] He is also author of the paper Theorems for free![11] that gave rise to much research on functional language optimization (see also Parametricity). p" 50 | } 51 | } 52 | } 53 | ] -------------------------------------------------------------------------------- /tests/test_ast.py: -------------------------------------------------------------------------------- 1 | import ast 2 | import pytest 3 | 4 | from prettyprinter import pformat 5 | 6 | 7 | def test_parsed(): 8 | node = ast.parse('value = 42') 9 | assert pformat(node, width=999) == """\ 10 | ast.Module( 11 | body=[ 12 | ast.Assign( 13 | targets=[ast.Name(id='value', ctx=ast.Store())], 14 | value=ast.Num(n=42) 15 | ) 16 | ] 17 | )""" 18 | 19 | 20 | @pytest.mark.parametrize('cls, identifier', [ 21 | (ast.Name, 'ast.Name'), 22 | (type('Name', (ast.Name,), {'__module__': 'custom'}), 'custom.Name'), 23 | ]) 24 | def test_pure_node(cls, identifier): 25 | name = cls(id='value', ctx=None) 26 | assert pformat(name) == "%s(id='value', ctx=None)" % identifier 27 | -------------------------------------------------------------------------------- /tests/test_attrs.py: -------------------------------------------------------------------------------- 1 | from attr import attrs, attrib, Factory 2 | 3 | from prettyprinter import install_extras, pformat 4 | 5 | install_extras(['attrs']) 6 | 7 | 8 | @attrs 9 | class MyClass: 10 | one = attrib() 11 | optional = attrib(default=1) 12 | optional2 = attrib(default=Factory(list)) 13 | 14 | 15 | def test_simple_case(): 16 | value = MyClass(1) 17 | expected = "tests.test_attrs.MyClass(one=1)" 18 | assert pformat(value, width=999) == expected 19 | 20 | 21 | def test_different_from_default(): 22 | value = MyClass(1, optional=2, optional2=[1]) 23 | expected = "tests.test_attrs.MyClass(one=1, optional=2, optional2=[1])" 24 | assert pformat(value, width=999) == expected 25 | 26 | 27 | @attrs 28 | class MyOtherClass: 29 | one = attrib(repr=False) 30 | 31 | 32 | def test_no_repr_field(): 33 | value = MyOtherClass(1) 34 | expected = "tests.test_attrs.MyOtherClass()" 35 | assert pformat(value, width=999) == expected 36 | -------------------------------------------------------------------------------- /tests/test_dataclasses.py: -------------------------------------------------------------------------------- 1 | from dataclasses import ( 2 | dataclass, 3 | field, 4 | ) 5 | from typing import Any 6 | 7 | from prettyprinter import install_extras, pformat 8 | 9 | install_extras(['dataclasses']) 10 | 11 | 12 | @dataclass 13 | class MyClass: 14 | one: Any 15 | optional: Any = field(default=1) 16 | optional2: Any = field(default_factory=list) 17 | 18 | 19 | def test_simple_case(): 20 | value = MyClass(1) 21 | expected = "tests.test_dataclasses.MyClass(one=1)" 22 | assert pformat(value, width=999) == expected 23 | 24 | 25 | def test_different_from_default(): 26 | value = MyClass(1, optional=2, optional2=[1]) 27 | expected = "tests.test_dataclasses.MyClass(one=1, optional=2, optional2=[1])" 28 | assert pformat(value, width=999) == expected 29 | 30 | 31 | @dataclass 32 | class MyOtherClass: 33 | one: Any = field(repr=False) 34 | 35 | 36 | def test_no_repr_field(): 37 | value = MyOtherClass(1) 38 | expected = "tests.test_dataclasses.MyOtherClass()" 39 | assert pformat(value, width=999) == expected 40 | -------------------------------------------------------------------------------- /tests/test_django/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/tommikaikkonen/prettyprinter/53ba5f934f24228315ef10898fc2b73370349696/tests/test_django/__init__.py -------------------------------------------------------------------------------- /tests/test_django/coreapp/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/tommikaikkonen/prettyprinter/53ba5f934f24228315ef10898fc2b73370349696/tests/test_django/coreapp/__init__.py -------------------------------------------------------------------------------- /tests/test_django/coreapp/models.py: -------------------------------------------------------------------------------- 1 | from django.db import models 2 | 3 | 4 | class MyModel(models.Model): 5 | name = models.CharField(max_length=128, blank=True) 6 | slug = models.CharField( 7 | max_length=128, 8 | null=True, 9 | blank=True, 10 | unique=True 11 | ) 12 | version = models.IntegerField(default=1) 13 | kind = models.CharField( 14 | max_length=1, 15 | choices=( 16 | ('A', 'Display for A'), 17 | ('B', 'Display for B'), 18 | ('C', 'Display for C'), 19 | ), 20 | default='A' 21 | ) 22 | -------------------------------------------------------------------------------- /tests/test_django/coreapp/test_prettyprinter_definitions.py: -------------------------------------------------------------------------------- 1 | import pytest 2 | from prettyprinter import install_extras, pformat 3 | 4 | from coreapp.models import MyModel 5 | 6 | install_extras(['django']) 7 | 8 | 9 | @pytest.mark.django_db 10 | def test_simple_case(): 11 | instance = MyModel.objects.create(name='John', slug='john', version=2) 12 | expected = """\ 13 | coreapp.models.MyModel( 14 | id={}, 15 | slug='john', 16 | version=2, 17 | name='John', 18 | # Default value fields: kind 19 | )""".format( 20 | instance.id 21 | ) 22 | assert pformat(instance, width=999) == expected 23 | 24 | 25 | @pytest.mark.django_db 26 | def test_blank_field(): 27 | instance = MyModel.objects.create(name='', slug=None, version=2) 28 | expected = """\ 29 | coreapp.models.MyModel( 30 | id={}, 31 | version=2, 32 | # Null fields: slug 33 | # Blank fields: name 34 | # Default value fields: kind 35 | )""".format(instance.id) 36 | assert pformat(instance, width=999) == expected 37 | 38 | 39 | @pytest.mark.django_db 40 | def test_default_field(): 41 | instance = MyModel.objects.create(name='', slug='a', version=1) 42 | expected = """\ 43 | coreapp.models.MyModel( 44 | id={}, 45 | slug='a', 46 | # Blank fields: name 47 | # Default value fields: kind, version 48 | )""".format(instance.id) 49 | assert pformat(instance, width=999) == expected 50 | 51 | 52 | @pytest.mark.django_db 53 | def test_choices_display(): 54 | instance = MyModel.objects.create( 55 | name='John', 56 | slug='john', 57 | version=1, 58 | kind='B' 59 | ) 60 | expected = """\ 61 | coreapp.models.MyModel( 62 | id={}, 63 | slug='john', 64 | kind='B', # Display for B 65 | name='John', 66 | # Default value fields: version 67 | )""".format(instance.id) 68 | assert pformat(instance, width=999) == expected 69 | 70 | 71 | @pytest.mark.django_db 72 | def test_queryset(): 73 | for i in range(11): 74 | MyModel.objects.create( 75 | name='Name{}'.format(i), 76 | version=1, 77 | slug='slug-{}'.format(i) 78 | ) 79 | 80 | qs = MyModel.objects.all() 81 | assert pformat(qs, width=999) == """\ 82 | django.db.models.query.QuerySet([ 83 | coreapp.models.MyModel(id=1), 84 | coreapp.models.MyModel(id=2), 85 | coreapp.models.MyModel(id=3), 86 | coreapp.models.MyModel(id=4), 87 | coreapp.models.MyModel(id=5), 88 | coreapp.models.MyModel(id=6), 89 | coreapp.models.MyModel(id=7), 90 | coreapp.models.MyModel(id=8), 91 | coreapp.models.MyModel(id=9), 92 | coreapp.models.MyModel(id=10), 93 | coreapp.models.MyModel(id=11) 94 | ])""" 95 | -------------------------------------------------------------------------------- /tests/test_django/manage.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | import os 3 | import sys 4 | 5 | if __name__ == "__main__": 6 | os.environ.setdefault("DJANGO_SETTINGS_MODULE", "prettyprinter_testproject.settings") 7 | try: 8 | from django.core.management import execute_from_command_line 9 | except ImportError: 10 | # The above import may fail for some other reason. Ensure that the 11 | # issue is really that Django is missing to avoid masking other 12 | # exceptions on Python 2. 13 | try: 14 | import django # noqa 15 | except ImportError: 16 | raise ImportError( 17 | "Couldn't import Django. Are you sure it's installed and " 18 | "available on your PYTHONPATH environment variable? Did you " 19 | "forget to activate a virtual environment?" 20 | ) 21 | raise 22 | execute_from_command_line(sys.argv) 23 | -------------------------------------------------------------------------------- /tests/test_django/prettyprinter_testproject/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/tommikaikkonen/prettyprinter/53ba5f934f24228315ef10898fc2b73370349696/tests/test_django/prettyprinter_testproject/__init__.py -------------------------------------------------------------------------------- /tests/test_django/prettyprinter_testproject/settings.py: -------------------------------------------------------------------------------- 1 | """ 2 | Django settings for prettyprinter_testproject project. 3 | 4 | Generated by 'django-admin startproject' using Django 1.10.8. 5 | 6 | For more information on this file, see 7 | https://docs.djangoproject.com/en/1.10/topics/settings/ 8 | 9 | For the full list of settings and their values, see 10 | https://docs.djangoproject.com/en/1.10/ref/settings/ 11 | """ 12 | 13 | import os 14 | 15 | # Build paths inside the project like this: os.path.join(BASE_DIR, ...) 16 | BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) 17 | 18 | 19 | # Quick-start development settings - unsuitable for production 20 | # See https://docs.djangoproject.com/en/1.10/howto/deployment/checklist/ 21 | 22 | # SECURITY WARNING: keep the secret key used in production secret! 23 | SECRET_KEY = 'irrelevant' 24 | 25 | # SECURITY WARNING: don't run with debug turned on in production! 26 | DEBUG = True 27 | 28 | ALLOWED_HOSTS = [] 29 | 30 | 31 | # Application definition 32 | 33 | INSTALLED_APPS = [ 34 | 'django.contrib.admin', 35 | 'django.contrib.auth', 36 | 'django.contrib.contenttypes', 37 | 'django.contrib.sessions', 38 | 'django.contrib.messages', 39 | 'django.contrib.staticfiles', 40 | 'coreapp' 41 | ] 42 | 43 | MIDDLEWARE = [ 44 | 'django.middleware.security.SecurityMiddleware', 45 | 'django.contrib.sessions.middleware.SessionMiddleware', 46 | 'django.middleware.common.CommonMiddleware', 47 | 'django.middleware.csrf.CsrfViewMiddleware', 48 | 'django.contrib.auth.middleware.AuthenticationMiddleware', 49 | 'django.contrib.messages.middleware.MessageMiddleware', 50 | 'django.middleware.clickjacking.XFrameOptionsMiddleware', 51 | ] 52 | 53 | ROOT_URLCONF = 'prettyprinter_testproject.urls' 54 | 55 | TEMPLATES = [ 56 | { 57 | 'BACKEND': 'django.template.backends.django.DjangoTemplates', 58 | 'DIRS': [], 59 | 'APP_DIRS': True, 60 | 'OPTIONS': { 61 | 'context_processors': [ 62 | 'django.template.context_processors.debug', 63 | 'django.template.context_processors.request', 64 | 'django.contrib.auth.context_processors.auth', 65 | 'django.contrib.messages.context_processors.messages', 66 | ], 67 | }, 68 | }, 69 | ] 70 | 71 | WSGI_APPLICATION = 'prettyprinter_testproject.wsgi.application' 72 | 73 | 74 | # Database 75 | # https://docs.djangoproject.com/en/1.10/ref/settings/#databases 76 | 77 | DATABASES = { 78 | 'default': { 79 | 'ENGINE': 'django.db.backends.sqlite3', 80 | 'NAME': ':memory:', 81 | } 82 | } 83 | 84 | 85 | # Password validation 86 | # https://docs.djangoproject.com/en/1.10/ref/settings/#auth-password-validators 87 | 88 | AUTH_PASSWORD_VALIDATORS = [ 89 | { 90 | 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', 91 | }, 92 | { 93 | 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', 94 | }, 95 | { 96 | 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator', 97 | }, 98 | { 99 | 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator', 100 | }, 101 | ] 102 | 103 | 104 | # Internationalization 105 | # https://docs.djangoproject.com/en/1.10/topics/i18n/ 106 | 107 | LANGUAGE_CODE = 'en-us' 108 | 109 | TIME_ZONE = 'UTC' 110 | 111 | USE_I18N = True 112 | 113 | USE_L10N = True 114 | 115 | USE_TZ = True 116 | 117 | 118 | # Static files (CSS, JavaScript, Images) 119 | # https://docs.djangoproject.com/en/1.10/howto/static-files/ 120 | 121 | STATIC_URL = '/static/' 122 | 123 | 124 | class DisableMigrations(object): 125 | def __contains__(self, item): 126 | return True 127 | 128 | def __getitem__(self, item): 129 | return 'notmigrations' 130 | 131 | 132 | MIGRATION_MODULES = DisableMigrations() 133 | -------------------------------------------------------------------------------- /tests/test_django/prettyprinter_testproject/urls.py: -------------------------------------------------------------------------------- 1 | """prettyprinter_testproject URL Configuration 2 | 3 | The `urlpatterns` list routes URLs to views. For more information please see: 4 | https://docs.djangoproject.com/en/1.10/topics/http/urls/ 5 | Examples: 6 | Function views 7 | 1. Add an import: from my_app import views 8 | 2. Add a URL to urlpatterns: url(r'^$', views.home, name='home') 9 | Class-based views 10 | 1. Add an import: from other_app.views import Home 11 | 2. Add a URL to urlpatterns: url(r'^$', Home.as_view(), name='home') 12 | Including another URLconf 13 | 1. Import the include() function: from django.conf.urls import url, include 14 | 2. Add a URL to urlpatterns: url(r'^blog/', include('blog.urls')) 15 | """ 16 | from django.conf.urls import url 17 | from django.contrib import admin 18 | 19 | urlpatterns = [ 20 | url(r'^admin/', admin.site.urls), 21 | ] 22 | -------------------------------------------------------------------------------- /tests/test_django/prettyprinter_testproject/wsgi.py: -------------------------------------------------------------------------------- 1 | """ 2 | WSGI config for prettyprinter_testproject project. 3 | 4 | It exposes the WSGI callable as a module-level variable named ``application``. 5 | 6 | For more information on this file, see 7 | https://docs.djangoproject.com/en/1.10/howto/deployment/wsgi/ 8 | """ 9 | 10 | import os 11 | 12 | from django.core.wsgi import get_wsgi_application 13 | 14 | os.environ.setdefault("DJANGO_SETTINGS_MODULE", "prettyprinter_testproject.settings") 15 | 16 | application = get_wsgi_application() 17 | -------------------------------------------------------------------------------- /tests/test_ipython_repr_pretty.py: -------------------------------------------------------------------------------- 1 | import pytest # noqa 2 | 3 | from prettyprinter import ( 4 | pformat, 5 | ) 6 | import prettyprinter.extras.ipython_repr_pretty 7 | 8 | prettyprinter.extras.ipython_repr_pretty.install() 9 | 10 | 11 | def test_compat(): 12 | class MyClass: 13 | def _repr_pretty_(self, p, cycle): 14 | with p.group(0, '{', '}'): 15 | with p.indent(4): 16 | p.breakable(sep='') 17 | p.text("'a': ") 18 | p.pretty(1) 19 | p.text(',') 20 | p.breakable(sep=' ') 21 | p.text("'b': ") 22 | p.pretty(2) 23 | p.breakable(sep='') 24 | 25 | result = pformat(MyClass()) 26 | expected = """{'a': 1, 'b': 2}""" 27 | assert result == expected 28 | 29 | result = pformat(MyClass(), width=12) 30 | expected = """\ 31 | { 32 | 'a': 1, 33 | 'b': 2 34 | }""" 35 | 36 | assert result == expected 37 | -------------------------------------------------------------------------------- /tests/test_numpy.py: -------------------------------------------------------------------------------- 1 | import numpy as np 2 | import pytest 3 | 4 | from prettyprinter import install_extras, pformat 5 | 6 | install_extras(["numpy"]) 7 | 8 | 9 | @pytest.mark.parametrize('nptype', ( 10 | np.sctypes["uint"] + 11 | np.sctypes["int"] + 12 | np.sctypes["float"] 13 | )) 14 | def test_numpy_numeric_types(nptype): 15 | val = nptype(1) 16 | py_val = val.item() 17 | 18 | if type(py_val) in (int, float): 19 | inner_printed = pformat(py_val) 20 | else: 21 | # numpy renders types such as float128, 22 | # that are not representable in native Python 23 | # types, with Python syntax 24 | inner_printed = repr(py_val) 25 | 26 | expected = "numpy.{}({})".format(nptype.__name__, inner_printed) 27 | assert pformat(val) == expected 28 | 29 | 30 | def test_numpy_bool_type(): 31 | assert pformat(np.bool_(False)) == "numpy.bool_(False)" 32 | assert pformat(np.bool_(True)) == "numpy.bool_(True)" 33 | 34 | 35 | def test_array(): 36 | assert pformat(np.array([0, 1])) == "numpy.ndarray([0, 1])" 37 | assert pformat(np.array([0., 1.])) == "numpy.ndarray([0.0, 1.0])" 38 | assert pformat(np.array([0, 1], dtype=np.uint8)) == "numpy.ndarray([0, 1], dtype='uint8')" 39 | assert pformat(np.array(["a", "b"])) == "numpy.ndarray(['a', 'b'], dtype='>> print(repr(b"\"''")) 263 | # >>> b'"\'\'' 264 | # 265 | # Where as prettyprinter chooses 266 | # >>> print(pformat(b"\"''"")) 267 | # >>> b"\"''" 268 | # For fewer escapes. 269 | used_same_quote_type = reprd[-1] == pformatted[-1] 270 | 271 | if used_same_quote_type: 272 | assert pformat(bytestr) == repr(bytestr) 273 | 274 | 275 | @settings(max_examples=500) 276 | @given(containers(primitives())) 277 | def test_readable(value): 278 | formatted = pformat(value) 279 | 280 | _locals = {'datetime': datetime, 'pytz': pytz} 281 | evald = eval(formatted, None, _locals) 282 | assert evald == value 283 | 284 | 285 | def nested_dictionaries(): 286 | simple_strings_alphabet = 'abcdefghijklmnopqrstuvwxyz\'"\r\n ' 287 | simple_text = st.text(alphabet=simple_strings_alphabet, min_size=5) 288 | 289 | def extend(base): 290 | return st.one_of( 291 | st.lists(base, min_size=5), 292 | st.dictionaries(keys=simple_text, values=base, min_size=1) 293 | ) 294 | 295 | return st.recursive(simple_text, extend, max_leaves=50) 296 | 297 | 298 | def test_top_level_str(): 299 | """Tests that top level strings are not indented or surrounded with parentheses""" 300 | 301 | pprint('ab' * 50) 302 | expected = ( 303 | "'ababababababababababababababababababababababababababababababababababa'" 304 | "\n'bababababababababababababababab'" 305 | ) 306 | assert pformat('ab' * 50) == expected 307 | 308 | 309 | def test_second_level_str(): 310 | """Test that second level strs are indented""" 311 | expected = """\ 312 | [ 313 | 'ababababababababababababababababababababababababababababababababababa' 314 | 'bababababababababababababababab', 315 | 'ababababababababababababababababababababababababababababababababababa' 316 | 'bababababababababababababababab' 317 | ]""" 318 | res = pformat(['ab' * 50] * 2) 319 | assert res == expected 320 | 321 | 322 | def test_single_element_sequence_multiline_strategy(): 323 | """Test that sequences with a single str-like element are not hang-indented 324 | in multiline mode.""" 325 | expected = """\ 326 | [ 327 | 'ababababababababababababababababababababababababababababababababababa' 328 | 'bababababababababababababababab' 329 | ]""" 330 | res = pformat(['ab' * 50]) 331 | assert res == expected 332 | 333 | 334 | def test_str_bug(): 335 | data = 'lorem ipsum dolor sit amet ' * 10 336 | expected = """\ 337 | 'lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum ' 338 | 'dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet ' 339 | 'lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum ' 340 | 'dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet '""" 341 | res = pformat(data) 342 | assert res == expected 343 | 344 | 345 | def test_many_cases(): 346 | # top-level multiline str. 347 | pprint('abcd' * 40) 348 | 349 | # sequence with multiline strs. 350 | pprint(['abcd' * 40] * 5) 351 | 352 | # nested dict 353 | pprint({ 354 | 'ab' * 40: 'cd' * 50 355 | }) 356 | 357 | # long urls. 358 | pprint([ 359 | 'https://www.example.com/User/john/files/Projects/prettyprinter/images/original/image0001.jpg' # noqa 360 | '?q=verylongquerystring&maxsize=1500&signature=af429fkven2aA' 361 | '#content1-header-something-something' 362 | ] * 5) 363 | nativepprint([ 364 | 'https://www.example.com/User/john/files/Projects/prettyprinter/images/original/image0001.jpg' # noqa 365 | '?q=verylongquerystring&maxsize=1500&signature=af429fkven2aA' 366 | '#content1-header-something-something' 367 | ] * 5) 368 | 369 | 370 | def test_datetime(): 371 | pprint(datetime.datetime.utcnow().replace(tzinfo=pytz.utc), width=40) 372 | pprint(datetime.timedelta(weeks=2, days=1, hours=3, milliseconds=5)) 373 | neg_td = -datetime.timedelta(weeks=2, days=1, hours=3, milliseconds=5) 374 | pprint(neg_td) 375 | 376 | 377 | @given(nested_dictionaries()) 378 | def test_nested_structures(value): 379 | pprint(value) 380 | 381 | 382 | def test_gh_issue_25(): 383 | pprint( 384 | {'a': {'a': {'a': {'a': {'a': {'a': {'a': {'a': {'a': {'a': {'a': {'a': {'a': 1}}}}}}}}}}}}}, 385 | width=30 386 | ) 387 | 388 | 389 | def test_gh_issue_59(): 390 | out = pformat({'a': comment('abcde' * 20, 'Comment'), 'b': 1}) 391 | assert out == """\ 392 | { 393 | 'a': 394 | # Comment 395 | 'abcdeabcdeabcdeabcdeabcdeabcdeabcdeabcdeabcdeabcdeabcdeabcdeabcdeabcd' 396 | 'eabcdeabcdeabcdeabcdeabcdeabcde', 397 | 'b': 1 398 | }""" 399 | 400 | 401 | def test_time_struct_time(): 402 | data = time.strptime("2000", "%Y") 403 | assert pformat(data) == """\ 404 | time.struct_time(( 405 | 2000, # tm_year 406 | 1, # tm_mon 407 | 1, # tm_mday 408 | 0, # tm_hour 409 | 0, # tm_min 410 | 0, # tm_sec 411 | 5, # tm_wday 412 | 1, # tm_yday 413 | -1 # tm_isdst 414 | ))""" 415 | # The cnamedtuple implementation has a caching 416 | # mechanism for the resolved order of fieldnames. 417 | # Those fieldnames should have been cached on the first 418 | # call, so check that this alternative code path does 419 | # not throw. 420 | pformat(data) 421 | 422 | 423 | def _safe_get_terminal_size(): 424 | try: 425 | return os.get_terminal_size() 426 | except Exception: 427 | return None 428 | 429 | 430 | def safe_get_asyncgen_hooks(): 431 | try: 432 | return sys.get_asyncgen_hooks() 433 | except Exception: 434 | return None 435 | 436 | 437 | @pytest.mark.parametrize('value, reconstructable', [ 438 | (time.strptime("2000", "%Y"), True), 439 | (os.stat(os.__file__), True), 440 | (os.times(), False), 441 | (_safe_get_terminal_size(), True), 442 | (resource.getrusage(resource.RUSAGE_SELF), True), 443 | (sys.flags, False), 444 | (sys.float_info, False), 445 | (safe_get_asyncgen_hooks(), False), 446 | (sys.hash_info, False), 447 | (sys.thread_info, False), 448 | (sys.version_info, False), 449 | (time.localtime(), True), 450 | ]) 451 | def test_cnamedtuples(value, reconstructable): 452 | # ignore calls that failed 453 | if value is None: 454 | return 455 | 456 | # should not throw 457 | fieldnames = resolve_cnamedtuple_fieldnames(value) 458 | printed = pformat(value) 459 | 460 | for fieldname in fieldnames: 461 | assert fieldname in printed 462 | 463 | if reconstructable: 464 | reconstructed = eval(printed) 465 | assert reconstructed == value 466 | 467 | 468 | def test_simplenamespace(): 469 | ns = SimpleNamespace(a=1, b=2) 470 | expected = """types.SimpleNamespace(a=1, b=2)""" 471 | assert pformat(ns) == expected 472 | 473 | 474 | def test_gh_issue_28(): 475 | start = datetime.datetime.now() 476 | pprint([]) 477 | end = datetime.datetime.now() 478 | took = end - start 479 | 480 | start2 = datetime.datetime.now() 481 | pprint([[[[[[[[[[[[[[[[[[[[]]]]]]]]]]]]]]]]]]]]) 482 | end2 = datetime.datetime.now() 483 | took2 = end2 - start2 484 | 485 | # Checks (with the simplest heuristic I could think of) 486 | # that nesting does not introduce exponential runtime. 487 | assert took2 < took * 100 488 | 489 | 490 | def test_large_data_performance(): 491 | data = [ 492 | { 493 | 'text': 'lorem ipsum dolor sit amet ' * 500 494 | } 495 | ] * 200 496 | stream = StringIO() 497 | 498 | start = datetime.datetime.now() 499 | cpprint(data, stream=stream) 500 | stream.getvalue() 501 | 502 | end = datetime.datetime.now() 503 | took = end - start 504 | print('took', took) 505 | # The bottleneck is in string to doc conversion, 506 | # specifically escaping strings many times. 507 | # There's probably more we can do here 508 | assert took < datetime.timedelta(seconds=13) 509 | 510 | 511 | @settings(max_examples=5000) 512 | @given( 513 | st.text(), 514 | st.integers(min_value=5), 515 | st.sampled_from(('"', "'")) 516 | ) 517 | def test_str_to_lines(s, max_len, use_quote): 518 | lines = list(str_to_lines(max_len, use_quote, s)) 519 | 520 | for line in lines: 521 | assert line 522 | assert len(line) <= max_len * len('\\Uxxxxxxxx') 523 | 524 | assert ''.join(lines) == s 525 | 526 | 527 | def test_is_registered(): 528 | class MyClass: 529 | pass 530 | 531 | assert not is_registered(MyClass) 532 | 533 | # object is not counted as a subclass 534 | assert not is_registered(MyClass, check_superclasses=True) 535 | 536 | @register_pretty(MyClass) 537 | def pretty_myclass(instance, ctx): 538 | return '...' 539 | 540 | assert is_registered(MyClass) 541 | assert is_registered(MyClass, check_superclasses=True) 542 | 543 | 544 | def test_is_registered_subclass(): 545 | class MyList(list): 546 | pass 547 | 548 | assert not is_registered(MyList) 549 | assert is_registered(MyList, check_superclasses=True) 550 | 551 | 552 | def test_pretty_repr(): 553 | class MyClass: 554 | __repr__ = pretty_repr 555 | 556 | @register_pretty(MyClass) 557 | def pretty_myclass(value, ctx): 558 | return pretty_call_alt(ctx, MyClass) 559 | 560 | assert repr(MyClass()) == pformat(MyClass()) 561 | 562 | 563 | def test_pretty_repr_unregistered_uses_default_repr_and_warns(): 564 | class MyClass: 565 | __repr__ = pretty_repr 566 | 567 | inst = MyClass() 568 | 569 | with pytest.warns(UserWarning) as record: 570 | result = repr(inst) 571 | 572 | assert result == object.__repr__(inst) 573 | assert len(record) == 1 574 | 575 | 576 | def test_dict_sorted_by_insertion(): 577 | """dict keys should be printed 578 | in insertion order.""" 579 | if sys.version_info >= (3, 6): 580 | value = { 581 | 'x': 1, 582 | 'a': 2 583 | } 584 | expected = """{'x': 1, 'a': 2}""" 585 | assert pformat(value, sort_dict_keys=False) == expected 586 | 587 | 588 | def test_sort_dict_keys(): 589 | value = { 590 | 'x': 1, 591 | 'a': 2 592 | } 593 | expected = """{'a': 2, 'x': 1}""" 594 | assert pformat(value, sort_dict_keys=True) == expected 595 | 596 | 597 | def test_dict_subclass(): 598 | class MyDict(dict): 599 | pass 600 | 601 | empty = MyDict() 602 | constructor_str = 'tests.test_prettyprinter.test_dict_subclass..MyDict' 603 | assert pformat(empty) == constructor_str + '()' 604 | 605 | value = MyDict({'a': 1}) 606 | assert pformat(value) == constructor_str + "({'a': 1})" 607 | 608 | truncated = MyDict({'a': 1, 'b': 2}) 609 | assert pformat(truncated, max_seq_len=1) == constructor_str + """\ 610 | ({ 611 | 'a': 1 612 | # ...and 1 more elements 613 | })""" 614 | 615 | 616 | def test_list_subclass(): 617 | class MyList(list): 618 | pass 619 | 620 | empty = MyList() 621 | constructor_str = 'tests.test_prettyprinter.test_list_subclass..MyList' 622 | assert pformat(empty) == constructor_str + '()' 623 | 624 | value = MyList([1, 2]) 625 | assert pformat(value) == constructor_str + "([1, 2])" 626 | 627 | truncated = MyList([1, 2]) 628 | assert pformat(truncated, max_seq_len=1) == constructor_str + """\ 629 | ([ 630 | 1, 631 | # ...and 1 more elements 632 | ])""" 633 | 634 | 635 | def test_builtin_method(): 636 | assert pformat(int(1).to_bytes == "int.to_bytes # built-in bound method") 637 | 638 | 639 | class TestDeferredType(dict): 640 | pass 641 | 642 | 643 | def test_deferred_registration(): 644 | expected = 'Deferred type works.' 645 | 646 | assert not is_registered(TestDeferredType, register_deferred=False) 647 | 648 | @register_pretty('tests.test_prettyprinter.TestDeferredType') 649 | def pretty_testdeferredtype(value, ctx): 650 | return expected 651 | 652 | assert not is_registered( 653 | TestDeferredType, 654 | check_deferred=False, 655 | register_deferred=False 656 | ) 657 | assert is_registered( 658 | TestDeferredType, 659 | register_deferred=False 660 | ) 661 | 662 | assert pformat(TestDeferredType()) == expected 663 | 664 | # Printer should have been moved to non-deferred registry 665 | assert is_registered( 666 | TestDeferredType, 667 | check_deferred=False, 668 | register_deferred=False 669 | ) 670 | 671 | 672 | class BaseTestDeferredType(dict): 673 | pass 674 | 675 | 676 | class ConcreteTestDeferredType(BaseTestDeferredType): 677 | pass 678 | 679 | 680 | def test_deferred_registration_subclass(): 681 | """Registering a printer for BaseTestDeferredType should be resolved 682 | when using the subclass ConcreteTestDeferredType""" 683 | 684 | expected = 'Deferred type works.' 685 | 686 | @register_pretty('tests.test_prettyprinter.BaseTestDeferredType') 687 | def pretty_testdeferredtype(value, ctx): 688 | return expected 689 | 690 | assert not is_registered( 691 | ConcreteTestDeferredType, 692 | check_superclasses=False, 693 | register_deferred=False 694 | ) 695 | 696 | assert is_registered( 697 | ConcreteTestDeferredType, 698 | check_superclasses=True, 699 | register_deferred=False 700 | ) 701 | 702 | assert pformat(ConcreteTestDeferredType()) == expected 703 | assert is_registered( 704 | ConcreteTestDeferredType, 705 | check_superclasses=True, 706 | check_deferred=False, 707 | register_deferred=False 708 | ) 709 | assert pformat(ConcreteTestDeferredType()) == expected 710 | 711 | 712 | def test_bad_printer_caught(): 713 | class MyClass: 714 | pass 715 | 716 | @register_pretty(MyClass) 717 | def pretty_myclass(value, ctx): 718 | raise ValueError(value) 719 | 720 | value = MyClass() 721 | 722 | with pytest.warns(UserWarning, match='Falling back to default repr') as record: 723 | result = pformat(value) 724 | 725 | assert result == repr(value) 726 | assert len(record) == 1 727 | -------------------------------------------------------------------------------- /tests/test_requests.py: -------------------------------------------------------------------------------- 1 | from datetime import timedelta 2 | from io import BytesIO 3 | from requests import ( 4 | Request, 5 | Response, 6 | Session, 7 | ) 8 | from requests.structures import CaseInsensitiveDict 9 | 10 | from prettyprinter import ( 11 | install_extras, 12 | pformat, 13 | ) 14 | 15 | install_extras(['requests']) 16 | 17 | 18 | def test_session(): 19 | sess = Session() 20 | sess.auth = ('user', 'pass') 21 | assert pformat(sess, width=999) == """\ 22 | requests.Session( 23 | headers=requests.structures.CaseInsensitiveDict({ 24 | 'Accept': '*/*', 25 | 'Accept-Encoding': 'gzip, deflate', 26 | 'Connection': 'keep-alive', 27 | 'User-Agent': 'python-requests/2.21.0' 28 | }), 29 | auth=('user', 'pass') 30 | )""" 31 | 32 | 33 | def test_request(): 34 | request = Request( 35 | 'GET', 36 | 'https://example.com/pages/1', 37 | data={'ok': True}, 38 | headers={ 39 | 'Content-Type': 'application/json', 40 | } 41 | ) 42 | assert pformat(request, width=999) == """\ 43 | requests.Request( 44 | method='GET', 45 | url='https://example.com/pages/1', 46 | data={'ok': True}, 47 | headers={'Content-Type': 'application/json'} 48 | )""" 49 | 50 | 51 | def test_prepared_request(): 52 | request = Request( 53 | 'POST', 54 | 'https://example.com/pages/1', 55 | json={'a': ['b', 'c', 'd']}, 56 | headers={ 57 | 'Content-Type': 'application/json', 58 | } 59 | ) 60 | prepped = request.prepare() 61 | assert pformat(prepped, width=999) == """\ 62 | requests.PreparedRequest( 63 | method='POST', 64 | url='https://example.com/pages/1', 65 | headers=requests.structures.CaseInsensitiveDict({ 66 | 'Content-Length': '22', 67 | 'Content-Type': 'application/json' 68 | }), 69 | body=b'{"a": ["b"' # ... and 12 more bytes 70 | )""" 71 | 72 | 73 | def test_response(): 74 | request = Request( 75 | 'POST', 76 | 'https://example.com/pages/1', 77 | json={'a': ['b', 'c', 'd']}, 78 | headers={ 79 | 'Content-Type': 'application/json', 80 | } 81 | ) 82 | prepped = request.prepare() 83 | 84 | payload = 'This is the response body.'.encode('utf-8') 85 | resp = Response() 86 | resp.raw = BytesIO(payload) 87 | resp.request = prepped 88 | resp.status_code = 200 89 | resp.url = 'https://example.com/pages/1' 90 | resp.encoding = 'utf-8' 91 | resp.reason = 'OK' 92 | resp.elapsed = timedelta(seconds=2) 93 | resp.headers = CaseInsensitiveDict({ 94 | 'Content-Type': 'text/plain', 95 | 'Content-Length': len(payload) 96 | }) 97 | assert pformat(resp, width=999) == """\ 98 | # Response content not loaded yet 99 | requests.Response( 100 | status_code=200, # OK 101 | url='https://example.com/pages/1', 102 | elapsed=datetime.timedelta(seconds=2), 103 | headers=requests.structures.CaseInsensitiveDict({ 104 | 'Content-Length': 26, 105 | 'Content-Type': 'text/plain' 106 | }) 107 | )""" 108 | 109 | # Loads content 110 | resp.text 111 | 112 | assert pformat(resp, width=999) == """\ 113 | requests.Response( 114 | url='https://example.com/pages/1', 115 | status_code=200, # OK 116 | elapsed=datetime.timedelta(seconds=2), 117 | headers=requests.structures.CaseInsensitiveDict({ 118 | 'Content-Length': 26, 119 | 'Content-Type': 'text/plain' 120 | }), 121 | text='This is the response body.' 122 | )""" 123 | -------------------------------------------------------------------------------- /tests/test_stdlib_definitions.py: -------------------------------------------------------------------------------- 1 | import os 2 | from collections import ( 3 | ChainMap, 4 | Counter, 5 | OrderedDict, 6 | defaultdict, 7 | deque, 8 | namedtuple, 9 | ) 10 | from enum import Enum 11 | from functools import partial, partialmethod 12 | from pathlib import PosixPath, PurePosixPath, PureWindowsPath, WindowsPath 13 | import sys 14 | from types import MappingProxyType 15 | from uuid import UUID 16 | 17 | import pytest 18 | 19 | from prettyprinter import pformat, is_registered 20 | 21 | 22 | def test_counter(): 23 | value = Counter({'a': 1, 'b': 200}) 24 | expected = "collections.Counter({'a': 1, 'b': 200})" 25 | assert pformat(value, width=999, sort_dict_keys=True) == expected 26 | if sys.version_info >= (3, 6): 27 | expected = "collections.Counter({'b': 200, 'a': 1})" 28 | assert pformat(value, width=999, sort_dict_keys=False) == expected 29 | 30 | 31 | def test_ordereddict(): 32 | value = OrderedDict([('a', 1), ('b', 2)]) 33 | expected = "collections.OrderedDict([('a', 1), ('b', 2)])" 34 | assert pformat(value, width=999, sort_dict_keys=True) == expected 35 | 36 | 37 | def test_defaultdict(): 38 | value = defaultdict(list) 39 | assert pformat(value, width=999) == 'collections.defaultdict(list, {})' 40 | 41 | 42 | def test_deque(): 43 | value = deque([1, 2], maxlen=10) 44 | assert pformat(value, width=999) == 'collections.deque([1, 2], maxlen=10)' 45 | 46 | value2 = deque([1, 2]) 47 | assert pformat(value2, width=999) == 'collections.deque([1, 2])' 48 | 49 | 50 | def test_chainmap(): 51 | empty = ChainMap() 52 | assert pformat(empty, width=999) == 'collections.ChainMap()' 53 | 54 | value = ChainMap({'a': 1}, {'b': 2}, {'a': 1}) 55 | assert pformat(value, width=999) == "collections.ChainMap({'a': 1}, {'b': 2}, {'a': 1})" 56 | 57 | 58 | def test_enum(): 59 | class TestEnum(Enum): 60 | ONE = 1 61 | TWO = 2 62 | 63 | value = TestEnum.ONE 64 | expected = 'tests.test_stdlib_definitions.test_enum..TestEnum.ONE' 65 | assert pformat(value) == expected 66 | 67 | 68 | def test_mappingproxytype(): 69 | assert is_registered( 70 | MappingProxyType, 71 | check_deferred=True, 72 | register_deferred=False 73 | ) 74 | value = MappingProxyType({'a': 1, 'b': 2}) 75 | expected = "mappingproxy({'a': 1, 'b': 2})" 76 | assert pformat(value, sort_dict_keys=True) == expected 77 | 78 | 79 | def test_uuid(): 80 | value = UUID('3ec21c4e-8125-478c-aa2c-c66de452c2eb') 81 | expected = "uuid.UUID('3ec21c4e-8125-478c-aa2c-c66de452c2eb')" 82 | assert pformat(value) == expected 83 | 84 | 85 | def test_namedtuple(): 86 | MyClass = namedtuple('MyClass', ['one', 'two']) 87 | value = MyClass(one=1, two=2) 88 | constructor_str = 'tests.test_stdlib_definitions.MyClass' 89 | assert pformat(value, width=999) == constructor_str + '(one=1, two=2)' 90 | 91 | 92 | @pytest.mark.parametrize('typ', [partial, partialmethod]) 93 | def test_partial(typ): 94 | value = typ(sorted, [2, 3, 1], reverse=True) 95 | assert pformat(value) == """\ 96 | functools.{}( 97 | sorted, # built-in function 98 | [2, 3, 1], 99 | reverse=True 100 | )""".format(typ.__name__) 101 | 102 | 103 | def test_exception(): 104 | exc = ValueError(1) 105 | assert is_registered(ValueError, check_superclasses=True) 106 | assert pformat(exc) == 'ValueError(1)' 107 | 108 | 109 | @pytest.mark.parametrize('typ, name, args, pathstr', [ 110 | pytest.param( 111 | PosixPath, 'PosixPath', ('a', '..', 'b/c'), "'a/../b/c'", 112 | marks=pytest.mark.skipif(os.name == 'nt', reason='POSIX only'), 113 | ), 114 | (PurePosixPath, 'PurePosixPath', ('a', '..', 'b/c'), "'a/../b/c'"), 115 | pytest.param( 116 | WindowsPath, 'WindowsPath', ('C:\\', '..', 'b\\c'), "'C:/../b/c'", 117 | marks=pytest.mark.skipif(os.name != 'nt', reason='Windows only'), 118 | ), 119 | (PureWindowsPath, 'PureWindowsPath', ('C:\\', '..', 'b\\c'), "'C:/../b/c'"), 120 | ]) 121 | def test_purepath(typ, name, args, pathstr): 122 | path = typ(*args) 123 | assert is_registered(typ, check_superclasses=True) 124 | assert pformat(path) == 'pathlib.{}({})'.format(name, pathstr) 125 | assert pformat(path, width=20) == """\ 126 | pathlib.{}( 127 | {} 128 | )""".format(name, pathstr) 129 | 130 | 131 | @pytest.mark.parametrize('typ, name', [ 132 | pytest.param( 133 | PosixPath, 'PosixPath', 134 | marks=pytest.mark.skipif(os.name == 'nt', reason='POSIX only'), 135 | ), 136 | (PurePosixPath, 'PurePosixPath'), 137 | pytest.param( 138 | WindowsPath, 'WindowsPath', 139 | marks=pytest.mark.skipif(os.name != 'nt', reason='Windows only'), 140 | ), 141 | (PureWindowsPath, 'PureWindowsPath'), 142 | ]) 143 | def test_purelongpath(typ, name): 144 | as_str = "/a-b" * 10 145 | path = typ(as_str) 146 | assert pformat(path) == 'pathlib.{}({!r})'.format(name, as_str) 147 | assert pformat(path, width=20) == """\ 148 | pathlib.{}( 149 | '/a-b/a-b/a-b/' 150 | 'a-b/a-b/a-b/' 151 | 'a-b/a-b/a-b/' 152 | 'a-b' 153 | )""".format(name) 154 | -------------------------------------------------------------------------------- /tox.ini: -------------------------------------------------------------------------------- 1 | [tox] 2 | envlist = py35, py36, flake8 3 | 4 | [testenv:flake8] 5 | basepython=python 6 | deps=flake8 7 | commands=flake8 prettyprinter 8 | 9 | [testenv] 10 | setenv = 11 | PYTHONPATH = {toxinidir} 12 | deps = 13 | -r{toxinidir}/requirements_dev.txt 14 | commands = 15 | pip install -U pip 16 | py.test --basetemp={envtmpdir} 17 | --------------------------------------------------------------------------------