pax_global_header00006660000000000000000000000064135777307070014532gustar00rootroot0000000000000052 comment=2acce01fcdda2ea32eea835c30ccca21aaff7297 astunparse-1.6.3/000077500000000000000000000000001357773070700137265ustar00rootroot00000000000000astunparse-1.6.3/.gitignore000066400000000000000000000005621357773070700157210ustar00rootroot00000000000000*.py[cod] # C extensions *.so # Packages *.egg *.egg-info dist build eggs parts bin var sdist develop-eggs .installed.cfg # Installer logs pip-log.txt # Unit test / coverage reports .coverage .tox nosetests.xml htmlcov # Translations *.mo # Mr Developer .mr.developer.cfg .project .pydevproject # Complexity output/*.html output/*/index.html # Sphinx docs/_buildastunparse-1.6.3/.travis.yml000066400000000000000000000005621357773070700160420ustar00rootroot00000000000000# Config file for automatic testing at travis-ci.org sudo: false language: python python: - "2.7" - "3.4" - "3.5" - "3.6" - "3.7" - "3.8" # command to install dependencies, e.g. pip install -r requirements.txt --use-mirrors install: pip install -r requirements.txt # command to run tests, e.g. python setup.py test script: python setup.py test cache: pip astunparse-1.6.3/AUTHORS.rst000066400000000000000000000004011357773070700156000ustar00rootroot00000000000000======= Credits ======= Maintainer ---------- * Simon Percivall Authors ------- * The Python Software Foundation * Bogdan Opanchuk * Vladimir Iakovlev * Thomas Grainger * Amund Hov * Jakub Wilk * Mateusz Bysiek * Serge Sans Paille astunparse-1.6.3/CONTRIBUTING.rst000066400000000000000000000043061357773070700163720ustar00rootroot00000000000000============ Contributing ============ Contributions are welcome, and they are greatly appreciated! Every little bit helps, and credit will always be given. You can contribute in many ways: Types of Contributions ---------------------- Report Bugs ~~~~~~~~~~~ Report bugs at https://github.com/simonpercivall/astunparse. If you are reporting a bug, please include: * Any details about your local setup that might be helpful in troubleshooting. * Detailed steps to reproduce the bug. Fix Bugs ~~~~~~~~ Look through the GitHub issues for bugs. Anything tagged with "bug" is open to whoever wants to implement it. Implement Features ~~~~~~~~~~~~~~~~~~ Look through the GitHub issues for features. Anything tagged with "feature" is open to whoever wants to implement it. Write Documentation ~~~~~~~~~~~~~~~~~~~ AST Unparser could always use more documentation, whether as part of the official AST Unparser docs, in docstrings, or even on the web in blog posts, articles, and such. Submit Feedback ~~~~~~~~~~~~~~~ The best way to send feedback is to file an issue at https://github.com/simonpercivall/astunparse/issues. If you are proposing a feature: * Explain in detail how it would work. * Keep the scope as narrow as possible, to make it easier to implement. * Remember that this is a volunteer-driven project, and that contributions are welcome :) Get Started! ------------ Ready to contribute? Here's how to set up `astunparse` for local development. 1. Check out the repository. 5. When you're done making changes, check that your changes pass flake8 and the tests, including testing other Python versions with tox:: $ flake8 astunparse tests $ python setup.py test $ tox To get flake8 and tox, just pip install them into your virtualenv. 6. Commit and send the patch or create a pull request. Pull Request Guidelines ----------------------- Before you submit a pull request, check that it meets these guidelines: 1. The pull request should include tests. 2. If the pull request adds functionality, the docs should be updated. Put your new functionality into a function with a docstring, and add the feature to the list in README.rst. 3. The pull request should work for Python 2.7, and 3.3.astunparse-1.6.3/HISTORY.rst000066400000000000000000000024161357773070700156240ustar00rootroot00000000000000Changelog ========= Here's the recent changes to AST Unparser. 1.6.3 - 2019-12-22 ~~~~~~~~~~~~~~~~~~ * Add full support for Python 3.8 1.6.2 - 2019-01-19 ~~~~~~~~~~~~~~~~~~ * Add support for the Constant node in Python 3.8 * Add tests to the sdist 1.6.1 - 2018-10-03 ~~~~~~~~~~~~~~~~~~ * Fix the roundtripping of very complex f-strings. 1.6.0 - 2018-09-30 ~~~~~~~~~~~~~~~~~~ * Python 3.7 compatibility 1.5.0 - 2017-02-05 ~~~~~~~~~~~~~~~~~~ * Python 3.6 compatibility * bugfix: correct argparser option type 1.4.0 - 2016-06-24 ~~~~~~~~~~~~~~~~~~ * Support for the ``async`` keyword * Support for unparsing "Interactive" and "Expression" nodes 1.3.0 - 2016-01-17 ~~~~~~~~~~~~~~~~~~ * Python 3.5 compatibility 1.2.0 - 2014-04-03 ~~~~~~~~~~~~~~~~~~ * Python 2.6 through 3.4 compatibility * A new function ``dump`` is added to return a pretty-printed version of the AST. It's also available when running ``python -m astunparse`` as the ``--dump`` argument. 1.1.0 - 2014-04-01 ~~~~~~~~~~~~~~~~~~ * ``unparse`` will return the source code for an AST. It is pretty feature-complete, and round-trips the stdlib, and is compatible with Python 2.7 and Python 3.4. Running ``python -m astunparse`` will print the round-tripped source for any python files given as argument. astunparse-1.6.3/LICENSE000066400000000000000000000075401357773070700147410ustar00rootroot00000000000000LICENSE ======= Copyright (c) 2014, Simon Percivall All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of AST Unparser nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. PYTHON SOFTWARE FOUNDATION LICENSE VERSION 2 -------------------------------------------- 1. This LICENSE AGREEMENT is between the Python Software Foundation ("PSF"), and the Individual or Organization ("Licensee") accessing and otherwise using this software ("Python") in source or binary form and its associated documentation. 2. Subject to the terms and conditions of this License Agreement, PSF hereby grants Licensee a nonexclusive, royalty-free, world-wide license to reproduce, analyze, test, perform and/or display publicly, prepare derivative works, distribute, and otherwise use Python alone or in any derivative version, provided, however, that PSF's License Agreement and PSF's notice of copyright, i.e., "Copyright (c) 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010, 2011, 2012, 2013, 2014 Python Software Foundation; All Rights Reserved" are retained in Python alone or in any derivative version prepared by Licensee. 3. In the event Licensee prepares a derivative work that is based on or incorporates Python or any part thereof, and wants to make the derivative work available to others as provided herein, then Licensee hereby agrees to include in any such work a brief summary of the changes made to Python. 4. PSF is making Python available to Licensee on an "AS IS" basis. PSF MAKES NO REPRESENTATIONS OR WARRANTIES, EXPRESS OR IMPLIED. BY WAY OF EXAMPLE, BUT NOT LIMITATION, PSF MAKES NO AND DISCLAIMS ANY REPRESENTATION OR WARRANTY OF MERCHANTABILITY OR FITNESS FOR ANY PARTICULAR PURPOSE OR THAT THE USE OF PYTHON WILL NOT INFRINGE ANY THIRD PARTY RIGHTS. 5. PSF SHALL NOT BE LIABLE TO LICENSEE OR ANY OTHER USERS OF PYTHON FOR ANY INCIDENTAL, SPECIAL, OR CONSEQUENTIAL DAMAGES OR LOSS AS A RESULT OF MODIFYING, DISTRIBUTING, OR OTHERWISE USING PYTHON, OR ANY DERIVATIVE THEREOF, EVEN IF ADVISED OF THE POSSIBILITY THEREOF. 6. This License Agreement will automatically terminate upon a material breach of its terms and conditions. 7. Nothing in this License Agreement shall be deemed to create any relationship of agency, partnership, or joint venture between PSF and Licensee. This License Agreement does not grant permission to use PSF trademarks or trade name in a trademark sense to endorse or promote products or services of Licensee, or any third party. 8. By copying, installing or otherwise using Python, Licensee agrees to be bound by the terms and conditions of this License Agreement. astunparse-1.6.3/MANIFEST.in000066400000000000000000000002701357773070700154630ustar00rootroot00000000000000include AUTHORS.rst include CONTRIBUTING.rst include HISTORY.rst include LICENSE include README.rst include requirements.txt include test_requirements.txt recursive-include tests *.py astunparse-1.6.3/Makefile000066400000000000000000000015521357773070700153710ustar00rootroot00000000000000.PHONY: clean-pyc clean-build docs clean help: @echo "clean-build - remove build artifacts" @echo "clean-pyc - remove Python file artifacts" @echo "lint - check style with flake8" @echo "test - run tests" @echo "coverage - check code coverage quickly with the default Python" @echo "docs - generate Sphinx HTML documentation, including API docs" @echo "release - package and upload a release" @echo "sdist - package" clean: clean-build clean-pyc rm -fr htmlcov/ clean-build: rm -fr build/ rm -fr dist/ rm -fr *.egg-info rm -fr tmp* clean-pyc: find . -name '*.pyc' -exec rm -f {} + find . -name '*.pyo' -exec rm -f {} + find . -name '*~' -exec rm -f {} + lint: flake8 lib/astunparse tests test: tox coverage: tox -e coverage docs: tox -e docs dist: clean python setup.py sdist python setup.py bdist_wheel python setup.py bdist_egg ls -l dist astunparse-1.6.3/README.rst000066400000000000000000000041571357773070700154240ustar00rootroot00000000000000============ AST Unparser ============ .. image:: https://badge.fury.io/py/astunparse.png :target: http://badge.fury.io/py/astunparse .. image:: https://travis-ci.org/simonpercivall/astunparse.png?branch=master :target: https://travis-ci.org/simonpercivall/astunparse .. image:: https://readthedocs.org/projects/astunparse/badge/ :target: https://astunparse.readthedocs.org/ An AST unparser for Python. This is a factored out version of ``unparse`` found in the Python source distribution; under Demo/parser in Python 2 and under Tools/parser in Python 3. Basic example:: import inspect import ast import astunparse # get back the source code astunparse.unparse(ast.parse(inspect.getsource(ast))) # get a pretty-printed dump of the AST astunparse.dump(ast.parse(inspect.getsource(ast))) This library is single-source compatible with Python 2.6 through Python 3.5. It is authored by the Python core developers; I have simply merged the Python 2.7 and the Python 3.5 source and test suites, and added a wrapper. This factoring out is to provide a library implementation that supports both versions. Added to this is a pretty-printing ``dump`` utility function. The test suite both runs specific tests and also roundtrips much of the standard library. Extensions and Alternatives --------------------------- Similar projects include: * codegen_ * astor_ * astmonkey_ * astprint_ None of these roundtrip much of the standard library and fail several of the basic tests in the ``test_unparse`` test suite. This library uses mature and core maintained code instead of trying to patch existing libraries. The ``unparse`` and the ``test_unparse`` modules are under the PSF license. Extensions include: * typed-astunparse: extends astunparse to support type annotations. * Documentation: http://astunparse.rtfd.org. Features -------- * unparses Python AST. * pretty-prints AST. .. _codegen: https://github.com/andreif/codegen .. _astor: https://github.com/berkerpeksag/astor .. _astmonkey: https://github.com/konradhalas/astmonkey .. _astprint: https://github.com/Manticore/astprint astunparse-1.6.3/docs/000077500000000000000000000000001357773070700146565ustar00rootroot00000000000000astunparse-1.6.3/docs/Makefile000066400000000000000000000151711357773070700163230ustar00rootroot00000000000000# Makefile for Sphinx documentation # # You can set these variables from the command line. SPHINXOPTS = SPHINXBUILD = sphinx-build PAPER = BUILDDIR = _build # User-friendly check for sphinx-build ifeq ($(shell which $(SPHINXBUILD) >/dev/null 2>&1; echo $$?), 1) $(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/) endif # Internal variables. PAPEROPT_a4 = -D latex_paper_size=a4 PAPEROPT_letter = -D latex_paper_size=letter ALLSPHINXOPTS = -d $(BUILDDIR)/doctrees $(PAPEROPT_$(PAPER)) $(SPHINXOPTS) . # the i18n builder cannot share the environment and doctrees with the others I18NSPHINXOPTS = $(PAPEROPT_$(PAPER)) $(SPHINXOPTS) . .PHONY: help clean html dirhtml singlehtml pickle json htmlhelp qthelp devhelp epub latex latexpdf text man changes linkcheck doctest gettext help: @echo "Please use \`make ' where is one of" @echo " html to make standalone HTML files" @echo " dirhtml to make HTML files named index.html in directories" @echo " singlehtml to make a single large HTML file" @echo " pickle to make pickle files" @echo " json to make JSON files" @echo " htmlhelp to make HTML files and a HTML help project" @echo " qthelp to make HTML files and a qthelp project" @echo " devhelp to make HTML files and a Devhelp project" @echo " epub to make an epub" @echo " latex to make LaTeX files, you can set PAPER=a4 or PAPER=letter" @echo " latexpdf to make LaTeX files and run them through pdflatex" @echo " latexpdfja to make LaTeX files and run them through platex/dvipdfmx" @echo " text to make text files" @echo " man to make manual pages" @echo " texinfo to make Texinfo files" @echo " info to make Texinfo files and run them through makeinfo" @echo " gettext to make PO message catalogs" @echo " changes to make an overview of all changed/added/deprecated items" @echo " xml to make Docutils-native XML files" @echo " pseudoxml to make pseudoxml-XML files for display purposes" @echo " linkcheck to check all external links for integrity" @echo " doctest to run all doctests embedded in the documentation (if enabled)" clean: rm -rf $(BUILDDIR)/* html: $(SPHINXBUILD) -b html $(ALLSPHINXOPTS) $(BUILDDIR)/html @echo @echo "Build finished. The HTML pages are in $(BUILDDIR)/html." dirhtml: $(SPHINXBUILD) -b dirhtml $(ALLSPHINXOPTS) $(BUILDDIR)/dirhtml @echo @echo "Build finished. The HTML pages are in $(BUILDDIR)/dirhtml." singlehtml: $(SPHINXBUILD) -b singlehtml $(ALLSPHINXOPTS) $(BUILDDIR)/singlehtml @echo @echo "Build finished. The HTML page is in $(BUILDDIR)/singlehtml." pickle: $(SPHINXBUILD) -b pickle $(ALLSPHINXOPTS) $(BUILDDIR)/pickle @echo @echo "Build finished; now you can process the pickle files." json: $(SPHINXBUILD) -b json $(ALLSPHINXOPTS) $(BUILDDIR)/json @echo @echo "Build finished; now you can process the JSON files." htmlhelp: $(SPHINXBUILD) -b htmlhelp $(ALLSPHINXOPTS) $(BUILDDIR)/htmlhelp @echo @echo "Build finished; now you can run HTML Help Workshop with the" \ ".hhp project file in $(BUILDDIR)/htmlhelp." qthelp: $(SPHINXBUILD) -b qthelp $(ALLSPHINXOPTS) $(BUILDDIR)/qthelp @echo @echo "Build finished; now you can run "qcollectiongenerator" with the" \ ".qhcp project file in $(BUILDDIR)/qthelp, like this:" @echo "# qcollectiongenerator $(BUILDDIR)/qthelp/complexity.qhcp" @echo "To view the help file:" @echo "# assistant -collectionFile $(BUILDDIR)/qthelp/complexity.qhc" devhelp: $(SPHINXBUILD) -b devhelp $(ALLSPHINXOPTS) $(BUILDDIR)/devhelp @echo @echo "Build finished." @echo "To view the help file:" @echo "# mkdir -p $$HOME/.local/share/devhelp/complexity" @echo "# ln -s $(BUILDDIR)/devhelp $$HOME/.local/share/devhelp/complexity" @echo "# devhelp" epub: $(SPHINXBUILD) -b epub $(ALLSPHINXOPTS) $(BUILDDIR)/epub @echo @echo "Build finished. The epub file is in $(BUILDDIR)/epub." latex: $(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex @echo @echo "Build finished; the LaTeX files are in $(BUILDDIR)/latex." @echo "Run \`make' in that directory to run these through (pdf)latex" \ "(use \`make latexpdf' here to do that automatically)." latexpdf: $(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex @echo "Running LaTeX files through pdflatex..." $(MAKE) -C $(BUILDDIR)/latex all-pdf @echo "pdflatex finished; the PDF files are in $(BUILDDIR)/latex." latexpdfja: $(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex @echo "Running LaTeX files through platex and dvipdfmx..." $(MAKE) -C $(BUILDDIR)/latex all-pdf-ja @echo "pdflatex finished; the PDF files are in $(BUILDDIR)/latex." text: $(SPHINXBUILD) -b text $(ALLSPHINXOPTS) $(BUILDDIR)/text @echo @echo "Build finished. The text files are in $(BUILDDIR)/text." man: $(SPHINXBUILD) -b man $(ALLSPHINXOPTS) $(BUILDDIR)/man @echo @echo "Build finished. The manual pages are in $(BUILDDIR)/man." texinfo: $(SPHINXBUILD) -b texinfo $(ALLSPHINXOPTS) $(BUILDDIR)/texinfo @echo @echo "Build finished. The Texinfo files are in $(BUILDDIR)/texinfo." @echo "Run \`make' in that directory to run these through makeinfo" \ "(use \`make info' here to do that automatically)." info: $(SPHINXBUILD) -b texinfo $(ALLSPHINXOPTS) $(BUILDDIR)/texinfo @echo "Running Texinfo files through makeinfo..." make -C $(BUILDDIR)/texinfo info @echo "makeinfo finished; the Info files are in $(BUILDDIR)/texinfo." gettext: $(SPHINXBUILD) -b gettext $(I18NSPHINXOPTS) $(BUILDDIR)/locale @echo @echo "Build finished. The message catalogs are in $(BUILDDIR)/locale." changes: $(SPHINXBUILD) -b changes $(ALLSPHINXOPTS) $(BUILDDIR)/changes @echo @echo "The overview file is in $(BUILDDIR)/changes." linkcheck: $(SPHINXBUILD) -b linkcheck $(ALLSPHINXOPTS) $(BUILDDIR)/linkcheck @echo @echo "Link check complete; look for any errors in the above output " \ "or in $(BUILDDIR)/linkcheck/output.txt." doctest: $(SPHINXBUILD) -b doctest $(ALLSPHINXOPTS) $(BUILDDIR)/doctest @echo "Testing of doctests in the sources finished, look at the " \ "results in $(BUILDDIR)/doctest/output.txt." xml: $(SPHINXBUILD) -b xml $(ALLSPHINXOPTS) $(BUILDDIR)/xml @echo @echo "Build finished. The XML files are in $(BUILDDIR)/xml." pseudoxml: $(SPHINXBUILD) -b pseudoxml $(ALLSPHINXOPTS) $(BUILDDIR)/pseudoxml @echo @echo "Build finished. The pseudo-XML files are in $(BUILDDIR)/pseudoxml."astunparse-1.6.3/docs/authors.rst000066400000000000000000000000331357773070700170710ustar00rootroot00000000000000.. include:: ../AUTHORS.rstastunparse-1.6.3/docs/conf.py000077500000000000000000000205771357773070700161730ustar00rootroot00000000000000#!/usr/bin/env python # -*- coding: utf-8 -*- # # complexity documentation build configuration file, created by # sphinx-quickstart on Tue Jul 9 22:26:36 2013. # # This file is execfile()d with the current directory set to its containing dir. # # Note that not all possible configuration values are present in this # autogenerated file. # # All configuration values have a default; values that are commented out # serve to show the default. import sys, os # If extensions (or modules to document with autodoc) are in another directory, # add these directories to sys.path here. If the directory is relative to the # documentation root, use os.path.abspath to make it absolute, like shown here. #sys.path.insert(0, os.path.abspath('.')) # Get the project root dir, which is the parent dir of this cwd = os.getcwd() project_root = os.path.dirname(cwd) # Insert the project root dir as the first element in the PYTHONPATH. # This lets us ensure that the source package is imported, and that its # version is used. sys.path.insert(0, project_root) import astunparse # -- General configuration ----------------------------------------------------- # If your documentation needs a minimal Sphinx version, state it here. #needs_sphinx = '1.0' # Add any Sphinx extension module names here, as strings. They can be extensions # coming with Sphinx (named 'sphinx.ext.*') or your custom ones. extensions = [ 'sphinx.ext.autodoc', 'sphinx.ext.viewcode', 'sphinx.ext.todo', ] # Add any paths that contain templates here, relative to this directory. templates_path = ['_templates'] # The suffix of source filenames. source_suffix = '.rst' # The encoding of source files. #source_encoding = 'utf-8-sig' # The master toctree document. master_doc = 'index' # General information about the project. project = u'AST Unparser' copyright = u'2014, Simon Percivall' # The version info for the project you're documenting, acts as replacement for # |version| and |release|, also used in various other places throughout the # built documents. # # The short X.Y version. version = astunparse.__version__ # The full version, including alpha/beta/rc tags. release = astunparse.__version__ # The language for content autogenerated by Sphinx. Refer to documentation # for a list of supported languages. #language = None # There are two options for replacing |today|: either, you set today to some # non-false value, then it is used: #today = '' # Else, today_fmt is used as the format for a strftime call. #today_fmt = '%B %d, %Y' # List of patterns, relative to source directory, that match files and # directories to ignore when looking for source files. exclude_patterns = ['_build'] # The reST default role (used for this markup: `text`) to use for all documents. #default_role = None # If true, '()' will be appended to :func: etc. cross-reference text. #add_function_parentheses = True # If true, the current module name will be prepended to all description # unit titles (such as .. function::). #add_module_names = True # If true, sectionauthor and moduleauthor directives will be shown in the # output. They are ignored by default. #show_authors = False # The name of the Pygments (syntax highlighting) style to use. pygments_style = 'sphinx' # A list of ignored prefixes for module index sorting. #modindex_common_prefix = [] # If true, keep warnings as "system message" paragraphs in the built documents. #keep_warnings = False # -- Options for HTML output --------------------------------------------------- # The theme to use for HTML and HTML Help pages. See the documentation for # a list of builtin themes. # Theme options are theme-specific and customize the look and feel of a theme # further. For a list of options available for each theme, see the # documentation. #html_theme_options = {} # Add any paths that contain custom themes here, relative to this directory. if not os.environ.get('READTHEDOCS', None) == 'True': import sphinx_rtd_theme html_theme = 'sphinx_rtd_theme' html_theme_path = [sphinx_rtd_theme.get_html_theme_path()] # The name for this set of Sphinx documents. If None, it defaults to # " v documentation". #html_title = None # A shorter title for the navigation bar. Default is the same as html_title. #html_short_title = None # The name of an image file (relative to this directory) to place at the top # of the sidebar. #html_logo = None # The name of an image file (within the static path) to use as favicon of the # docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32 # pixels large. #html_favicon = None # Add any paths that contain custom static files (such as style sheets) here, # relative to this directory. They are copied after the builtin static files, # so a file named "default.css" will overwrite the builtin "default.css". # html_static_path = ['_static'] # If not '', a 'Last updated on:' timestamp is inserted at every page bottom, # using the given strftime format. #html_last_updated_fmt = '%b %d, %Y' # If true, SmartyPants will be used to convert quotes and dashes to # typographically correct entities. #html_use_smartypants = True # Custom sidebar templates, maps document names to template names. #html_sidebars = {} # Additional templates that should be rendered to pages, maps page names to # template names. #html_additional_pages = {} # If false, no module index is generated. #html_domain_indices = True # If false, no index is generated. #html_use_index = True # If true, the index is split into individual pages for each letter. #html_split_index = False # If true, links to the reST sources are added to the pages. #html_show_sourcelink = True # If true, "Created using Sphinx" is shown in the HTML footer. Default is True. #html_show_sphinx = True # If true, "(C) Copyright ..." is shown in the HTML footer. Default is True. #html_show_copyright = True # If true, an OpenSearch description file will be output, and all pages will # contain a tag referring to it. The value of this option must be the # base URL from which the finished HTML is served. #html_use_opensearch = '' # This is the file name suffix for HTML files (e.g. ".xhtml"). #html_file_suffix = None # Output file base name for HTML help builder. htmlhelp_basename = 'astunparsedoc' # -- Options for LaTeX output -------------------------------------------------- latex_elements = { # The paper size ('letterpaper' or 'a4paper'). #'papersize': 'letterpaper', # The font size ('10pt', '11pt' or '12pt'). #'pointsize': '10pt', # Additional stuff for the LaTeX preamble. #'preamble': '', } # Grouping the document tree into LaTeX files. List of tuples # (source start file, target name, title, author, documentclass [howto/manual]). latex_documents = [ ('index', 'astunparse.tex', u'AST Unparser Documentation', u'Simon Percivall', 'manual'), ] # The name of an image file (relative to this directory) to place at the top of # the title page. #latex_logo = None # For "manual" documents, if this is true, then toplevel headings are parts, # not chapters. #latex_use_parts = False # If true, show page references after internal links. #latex_show_pagerefs = False # If true, show URL addresses after external links. #latex_show_urls = False # Documents to append as an appendix to all manuals. #latex_appendices = [] # If false, no module index is generated. #latex_domain_indices = True # -- Options for manual page output -------------------------------------------- # One entry per manual page. List of tuples # (source start file, name, description, authors, manual section). man_pages = [ ('index', 'astunparse', u'AST Unparser Documentation', [u'Simon Percivall'], 1) ] # If true, show URL addresses after external links. #man_show_urls = False # -- Options for Texinfo output ------------------------------------------------ # Grouping the document tree into Texinfo files. List of tuples # (source start file, target name, title, author, # dir menu entry, description, category) texinfo_documents = [ ('index', 'astunparse', u'AST Unparser Documentation', u'Simon Percivall', 'astunparse', 'One line description of project.', 'Miscellaneous'), ] # Documents to append as an appendix to all manuals. #texinfo_appendices = [] # If false, no module index is generated. #texinfo_domain_indices = True # How to display URL addresses: 'footnote', 'no', or 'inline'. #texinfo_show_urls = 'footnote' # If true, do not generate a @detailmenu in the "Top" node's menu. #texinfo_no_detailmenu = False astunparse-1.6.3/docs/contributing.rst000066400000000000000000000000401357773070700201110ustar00rootroot00000000000000.. include:: ../CONTRIBUTING.rstastunparse-1.6.3/docs/history.rst000066400000000000000000000001261357773070700171100ustar00rootroot00000000000000.. _history: ======= History ======= .. include:: ../HISTORY.rst :start-line: 3 astunparse-1.6.3/docs/index.rst000066400000000000000000000005431357773070700165210ustar00rootroot00000000000000Welcome to the AST Unparser documentation! ========================================== .. include:: ../README.rst :start-line: 13 Contents: ========= .. toctree:: :maxdepth: 2 installation usage astunparse contributing authors history Indices and tables ================== * :ref:`genindex` * :ref:`modindex` * :ref:`search` astunparse-1.6.3/docs/installation.rst000066400000000000000000000003111357773070700201040ustar00rootroot00000000000000============ Installation ============ At the command line:: $ easy_install astunparse Or, if you have virtualenvwrapper installed:: $ mkvirtualenv astunparse $ pip install astunparse astunparse-1.6.3/docs/make.bat000066400000000000000000000145021357773070700162650ustar00rootroot00000000000000@ECHO OFF REM Command file for Sphinx documentation if "%SPHINXBUILD%" == "" ( set SPHINXBUILD=sphinx-build ) set BUILDDIR=_build set ALLSPHINXOPTS=-d %BUILDDIR%/doctrees %SPHINXOPTS% . set I18NSPHINXOPTS=%SPHINXOPTS% . if NOT "%PAPER%" == "" ( set ALLSPHINXOPTS=-D latex_paper_size=%PAPER% %ALLSPHINXOPTS% set I18NSPHINXOPTS=-D latex_paper_size=%PAPER% %I18NSPHINXOPTS% ) if "%1" == "" goto help if "%1" == "help" ( :help echo.Please use `make ^` where ^ is one of echo. html to make standalone HTML files echo. dirhtml to make HTML files named index.html in directories echo. singlehtml to make a single large HTML file echo. pickle to make pickle files echo. json to make JSON files echo. htmlhelp to make HTML files and a HTML help project echo. qthelp to make HTML files and a qthelp project echo. devhelp to make HTML files and a Devhelp project echo. epub to make an epub echo. latex to make LaTeX files, you can set PAPER=a4 or PAPER=letter echo. text to make text files echo. man to make manual pages echo. texinfo to make Texinfo files echo. gettext to make PO message catalogs echo. changes to make an overview over all changed/added/deprecated items echo. xml to make Docutils-native XML files echo. pseudoxml to make pseudoxml-XML files for display purposes echo. linkcheck to check all external links for integrity echo. doctest to run all doctests embedded in the documentation if enabled goto end ) if "%1" == "clean" ( for /d %%i in (%BUILDDIR%\*) do rmdir /q /s %%i del /q /s %BUILDDIR%\* goto end ) %SPHINXBUILD% 2> nul if errorlevel 9009 ( echo. echo.The 'sphinx-build' command was not found. Make sure you have Sphinx echo.installed, then set the SPHINXBUILD environment variable to point echo.to the full path of the 'sphinx-build' executable. Alternatively you echo.may add the Sphinx directory to PATH. echo. echo.If you don't have Sphinx installed, grab it from echo.http://sphinx-doc.org/ exit /b 1 ) if "%1" == "html" ( %SPHINXBUILD% -b html %ALLSPHINXOPTS% %BUILDDIR%/html if errorlevel 1 exit /b 1 echo. echo.Build finished. The HTML pages are in %BUILDDIR%/html. goto end ) if "%1" == "dirhtml" ( %SPHINXBUILD% -b dirhtml %ALLSPHINXOPTS% %BUILDDIR%/dirhtml if errorlevel 1 exit /b 1 echo. echo.Build finished. The HTML pages are in %BUILDDIR%/dirhtml. goto end ) if "%1" == "singlehtml" ( %SPHINXBUILD% -b singlehtml %ALLSPHINXOPTS% %BUILDDIR%/singlehtml if errorlevel 1 exit /b 1 echo. echo.Build finished. The HTML pages are in %BUILDDIR%/singlehtml. goto end ) if "%1" == "pickle" ( %SPHINXBUILD% -b pickle %ALLSPHINXOPTS% %BUILDDIR%/pickle if errorlevel 1 exit /b 1 echo. echo.Build finished; now you can process the pickle files. goto end ) if "%1" == "json" ( %SPHINXBUILD% -b json %ALLSPHINXOPTS% %BUILDDIR%/json if errorlevel 1 exit /b 1 echo. echo.Build finished; now you can process the JSON files. goto end ) if "%1" == "htmlhelp" ( %SPHINXBUILD% -b htmlhelp %ALLSPHINXOPTS% %BUILDDIR%/htmlhelp if errorlevel 1 exit /b 1 echo. echo.Build finished; now you can run HTML Help Workshop with the ^ .hhp project file in %BUILDDIR%/htmlhelp. goto end ) if "%1" == "qthelp" ( %SPHINXBUILD% -b qthelp %ALLSPHINXOPTS% %BUILDDIR%/qthelp if errorlevel 1 exit /b 1 echo. echo.Build finished; now you can run "qcollectiongenerator" with the ^ .qhcp project file in %BUILDDIR%/qthelp, like this: echo.^> qcollectiongenerator %BUILDDIR%\qthelp\complexity.qhcp echo.To view the help file: echo.^> assistant -collectionFile %BUILDDIR%\qthelp\complexity.ghc goto end ) if "%1" == "devhelp" ( %SPHINXBUILD% -b devhelp %ALLSPHINXOPTS% %BUILDDIR%/devhelp if errorlevel 1 exit /b 1 echo. echo.Build finished. goto end ) if "%1" == "epub" ( %SPHINXBUILD% -b epub %ALLSPHINXOPTS% %BUILDDIR%/epub if errorlevel 1 exit /b 1 echo. echo.Build finished. The epub file is in %BUILDDIR%/epub. goto end ) if "%1" == "latex" ( %SPHINXBUILD% -b latex %ALLSPHINXOPTS% %BUILDDIR%/latex if errorlevel 1 exit /b 1 echo. echo.Build finished; the LaTeX files are in %BUILDDIR%/latex. goto end ) if "%1" == "latexpdf" ( %SPHINXBUILD% -b latex %ALLSPHINXOPTS% %BUILDDIR%/latex cd %BUILDDIR%/latex make all-pdf cd %BUILDDIR%/.. echo. echo.Build finished; the PDF files are in %BUILDDIR%/latex. goto end ) if "%1" == "latexpdfja" ( %SPHINXBUILD% -b latex %ALLSPHINXOPTS% %BUILDDIR%/latex cd %BUILDDIR%/latex make all-pdf-ja cd %BUILDDIR%/.. echo. echo.Build finished; the PDF files are in %BUILDDIR%/latex. goto end ) if "%1" == "text" ( %SPHINXBUILD% -b text %ALLSPHINXOPTS% %BUILDDIR%/text if errorlevel 1 exit /b 1 echo. echo.Build finished. The text files are in %BUILDDIR%/text. goto end ) if "%1" == "man" ( %SPHINXBUILD% -b man %ALLSPHINXOPTS% %BUILDDIR%/man if errorlevel 1 exit /b 1 echo. echo.Build finished. The manual pages are in %BUILDDIR%/man. goto end ) if "%1" == "texinfo" ( %SPHINXBUILD% -b texinfo %ALLSPHINXOPTS% %BUILDDIR%/texinfo if errorlevel 1 exit /b 1 echo. echo.Build finished. The Texinfo files are in %BUILDDIR%/texinfo. goto end ) if "%1" == "gettext" ( %SPHINXBUILD% -b gettext %I18NSPHINXOPTS% %BUILDDIR%/locale if errorlevel 1 exit /b 1 echo. echo.Build finished. The message catalogs are in %BUILDDIR%/locale. goto end ) if "%1" == "changes" ( %SPHINXBUILD% -b changes %ALLSPHINXOPTS% %BUILDDIR%/changes if errorlevel 1 exit /b 1 echo. echo.The overview file is in %BUILDDIR%/changes. goto end ) if "%1" == "linkcheck" ( %SPHINXBUILD% -b linkcheck %ALLSPHINXOPTS% %BUILDDIR%/linkcheck if errorlevel 1 exit /b 1 echo. echo.Link check complete; look for any errors in the above output ^ or in %BUILDDIR%/linkcheck/output.txt. goto end ) if "%1" == "doctest" ( %SPHINXBUILD% -b doctest %ALLSPHINXOPTS% %BUILDDIR%/doctest if errorlevel 1 exit /b 1 echo. echo.Testing of doctests in the sources finished, look at the ^ results in %BUILDDIR%/doctest/output.txt. goto end ) if "%1" == "xml" ( %SPHINXBUILD% -b xml %ALLSPHINXOPTS% %BUILDDIR%/xml if errorlevel 1 exit /b 1 echo. echo.Build finished. The XML files are in %BUILDDIR%/xml. goto end ) if "%1" == "pseudoxml" ( %SPHINXBUILD% -b pseudoxml %ALLSPHINXOPTS% %BUILDDIR%/pseudoxml if errorlevel 1 exit /b 1 echo. echo.Build finished. The pseudo-XML files are in %BUILDDIR%/pseudoxml. goto end ) :endastunparse-1.6.3/docs/requirements.txt000066400000000000000000000000671357773070700201450ustar00rootroot00000000000000pygments sphinx sphinx_rtd_theme -r../requirements.txt astunparse-1.6.3/docs/usage.rst000066400000000000000000000002151357773070700165120ustar00rootroot00000000000000===== Usage ===== To use AST Unparser in a project:: import astunparse Then use the :func:`unparse` function to unparse an AST tree. astunparse-1.6.3/lib/000077500000000000000000000000001357773070700144745ustar00rootroot00000000000000astunparse-1.6.3/lib/astunparse/000077500000000000000000000000001357773070700166615ustar00rootroot00000000000000astunparse-1.6.3/lib/astunparse/__init__.py000066400000000000000000000005451357773070700207760ustar00rootroot00000000000000# coding: utf-8 from __future__ import absolute_import from six.moves import cStringIO from .unparser import Unparser from .printer import Printer __version__ = '1.6.3' def unparse(tree): v = cStringIO() Unparser(tree, file=v) return v.getvalue() def dump(tree): v = cStringIO() Printer(file=v).visit(tree) return v.getvalue() astunparse-1.6.3/lib/astunparse/__main__.py000066400000000000000000000023061357773070700207540ustar00rootroot00000000000000from __future__ import print_function import sys import os import argparse from .unparser import roundtrip from . import dump def roundtrip_recursive(target, dump_tree=False): if os.path.isfile(target): print(target) print("=" * len(target)) if dump_tree: dump(target) else: roundtrip(target) print() elif os.path.isdir(target): for item in os.listdir(target): if item.endswith(".py"): roundtrip_recursive(os.path.join(target, item), dump_tree) else: print( "WARNING: skipping '%s', not a file or directory" % target, file=sys.stderr ) def main(args): parser = argparse.ArgumentParser(prog="astunparse") parser.add_argument( 'target', nargs='+', help="Files or directories to show roundtripped source for" ) parser.add_argument( '--dump', type=bool, help="Show a pretty-printed AST instead of the source" ) arguments = parser.parse_args(args) for target in arguments.target: roundtrip_recursive(target, dump_tree=arguments.dump) if __name__ == "__main__": main(sys.argv[1:]) astunparse-1.6.3/lib/astunparse/printer.py000066400000000000000000000026001357773070700207140ustar00rootroot00000000000000from __future__ import unicode_literals import sys import ast import six class Printer(ast.NodeVisitor): def __init__(self, file=sys.stdout, indent=" "): self.indentation = 0 self.indent_with = indent self.f = file # overridden to make the API obvious def visit(self, node): super(Printer, self).visit(node) def write(self, text): self.f.write(six.text_type(text)) def generic_visit(self, node): if isinstance(node, list): nodestart = "[" nodeend = "]" children = [("", child) for child in node] else: nodestart = type(node).__name__ + "(" nodeend = ")" children = [(name + "=", value) for name, value in ast.iter_fields(node)] if len(children) > 1: self.indentation += 1 self.write(nodestart) for i, pair in enumerate(children): attr, child = pair if len(children) > 1: self.write("\n" + self.indent_with * self.indentation) if isinstance(child, (ast.AST, list)): self.write(attr) self.visit(child) else: self.write(attr + repr(child)) if i != len(children) - 1: self.write(",") self.write(nodeend) if len(children) > 1: self.indentation -= 1 astunparse-1.6.3/lib/astunparse/unparser.py000066400000000000000000000654421357773070700211050ustar00rootroot00000000000000"Usage: unparse.py " from __future__ import print_function, unicode_literals import six import sys import ast import os import tokenize from six import StringIO # Large float and imaginary literals get turned into infinities in the AST. # We unparse those infinities to INFSTR. INFSTR = "1e" + repr(sys.float_info.max_10_exp + 1) def interleave(inter, f, seq): """Call f on each item in seq, calling inter() in between. """ seq = iter(seq) try: f(next(seq)) except StopIteration: pass else: for x in seq: inter() f(x) class Unparser: """Methods in this class recursively traverse an AST and output source code for the abstract syntax; original formatting is disregarded. """ def __init__(self, tree, file = sys.stdout): """Unparser(tree, file=sys.stdout) -> None. Print the source for tree to file.""" self.f = file self.future_imports = [] self._indent = 0 self.dispatch(tree) print("", file=self.f) self.f.flush() def fill(self, text = ""): "Indent a piece of text, according to the current indentation level" self.f.write("\n"+" "*self._indent + text) def write(self, text): "Append a piece of text to the current line." self.f.write(six.text_type(text)) def enter(self): "Print ':', and increase the indentation." self.write(":") self._indent += 1 def leave(self): "Decrease the indentation level." self._indent -= 1 def dispatch(self, tree): "Dispatcher function, dispatching tree type T to method _T." if isinstance(tree, list): for t in tree: self.dispatch(t) return meth = getattr(self, "_"+tree.__class__.__name__) meth(tree) ############### Unparsing methods ###################### # There should be one method per concrete grammar type # # Constructors should be grouped by sum type. Ideally, # # this would follow the order in the grammar, but # # currently doesn't. # ######################################################## def _Module(self, tree): for stmt in tree.body: self.dispatch(stmt) def _Interactive(self, tree): for stmt in tree.body: self.dispatch(stmt) def _Expression(self, tree): self.dispatch(tree.body) # stmt def _Expr(self, tree): self.fill() self.dispatch(tree.value) def _NamedExpr(self, tree): self.write("(") self.dispatch(tree.target) self.write(" := ") self.dispatch(tree.value) self.write(")") def _Import(self, t): self.fill("import ") interleave(lambda: self.write(", "), self.dispatch, t.names) def _ImportFrom(self, t): # A from __future__ import may affect unparsing, so record it. if t.module and t.module == '__future__': self.future_imports.extend(n.name for n in t.names) self.fill("from ") self.write("." * t.level) if t.module: self.write(t.module) self.write(" import ") interleave(lambda: self.write(", "), self.dispatch, t.names) def _Assign(self, t): self.fill() for target in t.targets: self.dispatch(target) self.write(" = ") self.dispatch(t.value) def _AugAssign(self, t): self.fill() self.dispatch(t.target) self.write(" "+self.binop[t.op.__class__.__name__]+"= ") self.dispatch(t.value) def _AnnAssign(self, t): self.fill() if not t.simple and isinstance(t.target, ast.Name): self.write('(') self.dispatch(t.target) if not t.simple and isinstance(t.target, ast.Name): self.write(')') self.write(": ") self.dispatch(t.annotation) if t.value: self.write(" = ") self.dispatch(t.value) def _Return(self, t): self.fill("return") if t.value: self.write(" ") self.dispatch(t.value) def _Pass(self, t): self.fill("pass") def _Break(self, t): self.fill("break") def _Continue(self, t): self.fill("continue") def _Delete(self, t): self.fill("del ") interleave(lambda: self.write(", "), self.dispatch, t.targets) def _Assert(self, t): self.fill("assert ") self.dispatch(t.test) if t.msg: self.write(", ") self.dispatch(t.msg) def _Exec(self, t): self.fill("exec ") self.dispatch(t.body) if t.globals: self.write(" in ") self.dispatch(t.globals) if t.locals: self.write(", ") self.dispatch(t.locals) def _Print(self, t): self.fill("print ") do_comma = False if t.dest: self.write(">>") self.dispatch(t.dest) do_comma = True for e in t.values: if do_comma:self.write(", ") else:do_comma=True self.dispatch(e) if not t.nl: self.write(",") def _Global(self, t): self.fill("global ") interleave(lambda: self.write(", "), self.write, t.names) def _Nonlocal(self, t): self.fill("nonlocal ") interleave(lambda: self.write(", "), self.write, t.names) def _Await(self, t): self.write("(") self.write("await") if t.value: self.write(" ") self.dispatch(t.value) self.write(")") def _Yield(self, t): self.write("(") self.write("yield") if t.value: self.write(" ") self.dispatch(t.value) self.write(")") def _YieldFrom(self, t): self.write("(") self.write("yield from") if t.value: self.write(" ") self.dispatch(t.value) self.write(")") def _Raise(self, t): self.fill("raise") if six.PY3: if not t.exc: assert not t.cause return self.write(" ") self.dispatch(t.exc) if t.cause: self.write(" from ") self.dispatch(t.cause) else: self.write(" ") if t.type: self.dispatch(t.type) if t.inst: self.write(", ") self.dispatch(t.inst) if t.tback: self.write(", ") self.dispatch(t.tback) def _Try(self, t): self.fill("try") self.enter() self.dispatch(t.body) self.leave() for ex in t.handlers: self.dispatch(ex) if t.orelse: self.fill("else") self.enter() self.dispatch(t.orelse) self.leave() if t.finalbody: self.fill("finally") self.enter() self.dispatch(t.finalbody) self.leave() def _TryExcept(self, t): self.fill("try") self.enter() self.dispatch(t.body) self.leave() for ex in t.handlers: self.dispatch(ex) if t.orelse: self.fill("else") self.enter() self.dispatch(t.orelse) self.leave() def _TryFinally(self, t): if len(t.body) == 1 and isinstance(t.body[0], ast.TryExcept): # try-except-finally self.dispatch(t.body) else: self.fill("try") self.enter() self.dispatch(t.body) self.leave() self.fill("finally") self.enter() self.dispatch(t.finalbody) self.leave() def _ExceptHandler(self, t): self.fill("except") if t.type: self.write(" ") self.dispatch(t.type) if t.name: self.write(" as ") if six.PY3: self.write(t.name) else: self.dispatch(t.name) self.enter() self.dispatch(t.body) self.leave() def _ClassDef(self, t): self.write("\n") for deco in t.decorator_list: self.fill("@") self.dispatch(deco) self.fill("class "+t.name) if six.PY3: self.write("(") comma = False for e in t.bases: if comma: self.write(", ") else: comma = True self.dispatch(e) for e in t.keywords: if comma: self.write(", ") else: comma = True self.dispatch(e) if sys.version_info[:2] < (3, 5): if t.starargs: if comma: self.write(", ") else: comma = True self.write("*") self.dispatch(t.starargs) if t.kwargs: if comma: self.write(", ") else: comma = True self.write("**") self.dispatch(t.kwargs) self.write(")") elif t.bases: self.write("(") for a in t.bases: self.dispatch(a) self.write(", ") self.write(")") self.enter() self.dispatch(t.body) self.leave() def _FunctionDef(self, t): self.__FunctionDef_helper(t, "def") def _AsyncFunctionDef(self, t): self.__FunctionDef_helper(t, "async def") def __FunctionDef_helper(self, t, fill_suffix): self.write("\n") for deco in t.decorator_list: self.fill("@") self.dispatch(deco) def_str = fill_suffix+" "+t.name + "(" self.fill(def_str) self.dispatch(t.args) self.write(")") if getattr(t, "returns", False): self.write(" -> ") self.dispatch(t.returns) self.enter() self.dispatch(t.body) self.leave() def _For(self, t): self.__For_helper("for ", t) def _AsyncFor(self, t): self.__For_helper("async for ", t) def __For_helper(self, fill, t): self.fill(fill) self.dispatch(t.target) self.write(" in ") self.dispatch(t.iter) self.enter() self.dispatch(t.body) self.leave() if t.orelse: self.fill("else") self.enter() self.dispatch(t.orelse) self.leave() def _If(self, t): self.fill("if ") self.dispatch(t.test) self.enter() self.dispatch(t.body) self.leave() # collapse nested ifs into equivalent elifs. while (t.orelse and len(t.orelse) == 1 and isinstance(t.orelse[0], ast.If)): t = t.orelse[0] self.fill("elif ") self.dispatch(t.test) self.enter() self.dispatch(t.body) self.leave() # final else if t.orelse: self.fill("else") self.enter() self.dispatch(t.orelse) self.leave() def _While(self, t): self.fill("while ") self.dispatch(t.test) self.enter() self.dispatch(t.body) self.leave() if t.orelse: self.fill("else") self.enter() self.dispatch(t.orelse) self.leave() def _generic_With(self, t, async_=False): self.fill("async with " if async_ else "with ") if hasattr(t, 'items'): interleave(lambda: self.write(", "), self.dispatch, t.items) else: self.dispatch(t.context_expr) if t.optional_vars: self.write(" as ") self.dispatch(t.optional_vars) self.enter() self.dispatch(t.body) self.leave() def _With(self, t): self._generic_With(t) def _AsyncWith(self, t): self._generic_With(t, async_=True) # expr def _Bytes(self, t): self.write(repr(t.s)) def _Str(self, tree): if six.PY3: self.write(repr(tree.s)) else: # if from __future__ import unicode_literals is in effect, # then we want to output string literals using a 'b' prefix # and unicode literals with no prefix. if "unicode_literals" not in self.future_imports: self.write(repr(tree.s)) elif isinstance(tree.s, str): self.write("b" + repr(tree.s)) elif isinstance(tree.s, unicode): self.write(repr(tree.s).lstrip("u")) else: assert False, "shouldn't get here" def _JoinedStr(self, t): # JoinedStr(expr* values) self.write("f") string = StringIO() self._fstring_JoinedStr(t, string.write) # Deviation from `unparse.py`: Try to find an unused quote. # This change is made to handle _very_ complex f-strings. v = string.getvalue() if '\n' in v or '\r' in v: quote_types = ["'''", '"""'] else: quote_types = ["'", '"', '"""', "'''"] for quote_type in quote_types: if quote_type not in v: v = "{quote_type}{v}{quote_type}".format(quote_type=quote_type, v=v) break else: v = repr(v) self.write(v) def _FormattedValue(self, t): # FormattedValue(expr value, int? conversion, expr? format_spec) self.write("f") string = StringIO() self._fstring_JoinedStr(t, string.write) self.write(repr(string.getvalue())) def _fstring_JoinedStr(self, t, write): for value in t.values: meth = getattr(self, "_fstring_" + type(value).__name__) meth(value, write) def _fstring_Str(self, t, write): value = t.s.replace("{", "{{").replace("}", "}}") write(value) def _fstring_Constant(self, t, write): assert isinstance(t.value, str) value = t.value.replace("{", "{{").replace("}", "}}") write(value) def _fstring_FormattedValue(self, t, write): write("{") expr = StringIO() Unparser(t.value, expr) expr = expr.getvalue().rstrip("\n") if expr.startswith("{"): write(" ") # Separate pair of opening brackets as "{ {" write(expr) if t.conversion != -1: conversion = chr(t.conversion) assert conversion in "sra" write("!{conversion}".format(conversion=conversion)) if t.format_spec: write(":") meth = getattr(self, "_fstring_" + type(t.format_spec).__name__) meth(t.format_spec, write) write("}") def _Name(self, t): self.write(t.id) def _NameConstant(self, t): self.write(repr(t.value)) def _Repr(self, t): self.write("`") self.dispatch(t.value) self.write("`") def _write_constant(self, value): if isinstance(value, (float, complex)): # Substitute overflowing decimal literal for AST infinities. self.write(repr(value).replace("inf", INFSTR)) else: self.write(repr(value)) def _Constant(self, t): value = t.value if isinstance(value, tuple): self.write("(") if len(value) == 1: self._write_constant(value[0]) self.write(",") else: interleave(lambda: self.write(", "), self._write_constant, value) self.write(")") elif value is Ellipsis: # instead of `...` for Py2 compatibility self.write("...") else: if t.kind == "u": self.write("u") self._write_constant(t.value) def _Num(self, t): repr_n = repr(t.n) if six.PY3: self.write(repr_n.replace("inf", INFSTR)) else: # Parenthesize negative numbers, to avoid turning (-1)**2 into -1**2. if repr_n.startswith("-"): self.write("(") if "inf" in repr_n and repr_n.endswith("*j"): repr_n = repr_n.replace("*j", "j") # Substitute overflowing decimal literal for AST infinities. self.write(repr_n.replace("inf", INFSTR)) if repr_n.startswith("-"): self.write(")") def _List(self, t): self.write("[") interleave(lambda: self.write(", "), self.dispatch, t.elts) self.write("]") def _ListComp(self, t): self.write("[") self.dispatch(t.elt) for gen in t.generators: self.dispatch(gen) self.write("]") def _GeneratorExp(self, t): self.write("(") self.dispatch(t.elt) for gen in t.generators: self.dispatch(gen) self.write(")") def _SetComp(self, t): self.write("{") self.dispatch(t.elt) for gen in t.generators: self.dispatch(gen) self.write("}") def _DictComp(self, t): self.write("{") self.dispatch(t.key) self.write(": ") self.dispatch(t.value) for gen in t.generators: self.dispatch(gen) self.write("}") def _comprehension(self, t): if getattr(t, 'is_async', False): self.write(" async for ") else: self.write(" for ") self.dispatch(t.target) self.write(" in ") self.dispatch(t.iter) for if_clause in t.ifs: self.write(" if ") self.dispatch(if_clause) def _IfExp(self, t): self.write("(") self.dispatch(t.body) self.write(" if ") self.dispatch(t.test) self.write(" else ") self.dispatch(t.orelse) self.write(")") def _Set(self, t): assert(t.elts) # should be at least one element self.write("{") interleave(lambda: self.write(", "), self.dispatch, t.elts) self.write("}") def _Dict(self, t): self.write("{") def write_key_value_pair(k, v): self.dispatch(k) self.write(": ") self.dispatch(v) def write_item(item): k, v = item if k is None: # for dictionary unpacking operator in dicts {**{'y': 2}} # see PEP 448 for details self.write("**") self.dispatch(v) else: write_key_value_pair(k, v) interleave(lambda: self.write(", "), write_item, zip(t.keys, t.values)) self.write("}") def _Tuple(self, t): self.write("(") if len(t.elts) == 1: elt = t.elts[0] self.dispatch(elt) self.write(",") else: interleave(lambda: self.write(", "), self.dispatch, t.elts) self.write(")") unop = {"Invert":"~", "Not": "not", "UAdd":"+", "USub":"-"} def _UnaryOp(self, t): self.write("(") self.write(self.unop[t.op.__class__.__name__]) self.write(" ") if six.PY2 and isinstance(t.op, ast.USub) and isinstance(t.operand, ast.Num): # If we're applying unary minus to a number, parenthesize the number. # This is necessary: -2147483648 is different from -(2147483648) on # a 32-bit machine (the first is an int, the second a long), and # -7j is different from -(7j). (The first has real part 0.0, the second # has real part -0.0.) self.write("(") self.dispatch(t.operand) self.write(")") else: self.dispatch(t.operand) self.write(")") binop = { "Add":"+", "Sub":"-", "Mult":"*", "MatMult":"@", "Div":"/", "Mod":"%", "LShift":"<<", "RShift":">>", "BitOr":"|", "BitXor":"^", "BitAnd":"&", "FloorDiv":"//", "Pow": "**"} def _BinOp(self, t): self.write("(") self.dispatch(t.left) self.write(" " + self.binop[t.op.__class__.__name__] + " ") self.dispatch(t.right) self.write(")") cmpops = {"Eq":"==", "NotEq":"!=", "Lt":"<", "LtE":"<=", "Gt":">", "GtE":">=", "Is":"is", "IsNot":"is not", "In":"in", "NotIn":"not in"} def _Compare(self, t): self.write("(") self.dispatch(t.left) for o, e in zip(t.ops, t.comparators): self.write(" " + self.cmpops[o.__class__.__name__] + " ") self.dispatch(e) self.write(")") boolops = {ast.And: 'and', ast.Or: 'or'} def _BoolOp(self, t): self.write("(") s = " %s " % self.boolops[t.op.__class__] interleave(lambda: self.write(s), self.dispatch, t.values) self.write(")") def _Attribute(self,t): self.dispatch(t.value) # Special case: 3.__abs__() is a syntax error, so if t.value # is an integer literal then we need to either parenthesize # it or add an extra space to get 3 .__abs__(). if isinstance(t.value, getattr(ast, 'Constant', getattr(ast, 'Num', None))) and isinstance(t.value.n, int): self.write(" ") self.write(".") self.write(t.attr) def _Call(self, t): self.dispatch(t.func) self.write("(") comma = False for e in t.args: if comma: self.write(", ") else: comma = True self.dispatch(e) for e in t.keywords: if comma: self.write(", ") else: comma = True self.dispatch(e) if sys.version_info[:2] < (3, 5): if t.starargs: if comma: self.write(", ") else: comma = True self.write("*") self.dispatch(t.starargs) if t.kwargs: if comma: self.write(", ") else: comma = True self.write("**") self.dispatch(t.kwargs) self.write(")") def _Subscript(self, t): self.dispatch(t.value) self.write("[") self.dispatch(t.slice) self.write("]") def _Starred(self, t): self.write("*") self.dispatch(t.value) # slice def _Ellipsis(self, t): self.write("...") def _Index(self, t): self.dispatch(t.value) def _Slice(self, t): if t.lower: self.dispatch(t.lower) self.write(":") if t.upper: self.dispatch(t.upper) if t.step: self.write(":") self.dispatch(t.step) def _ExtSlice(self, t): interleave(lambda: self.write(', '), self.dispatch, t.dims) # argument def _arg(self, t): self.write(t.arg) if t.annotation: self.write(": ") self.dispatch(t.annotation) # others def _arguments(self, t): first = True # normal arguments all_args = getattr(t, 'posonlyargs', []) + t.args defaults = [None] * (len(all_args) - len(t.defaults)) + t.defaults for index, elements in enumerate(zip(all_args, defaults), 1): a, d = elements if first:first = False else: self.write(", ") self.dispatch(a) if d: self.write("=") self.dispatch(d) if index == len(getattr(t, 'posonlyargs', ())): self.write(", /") # varargs, or bare '*' if no varargs but keyword-only arguments present if t.vararg or getattr(t, "kwonlyargs", False): if first:first = False else: self.write(", ") self.write("*") if t.vararg: if hasattr(t.vararg, 'arg'): self.write(t.vararg.arg) if t.vararg.annotation: self.write(": ") self.dispatch(t.vararg.annotation) else: self.write(t.vararg) if getattr(t, 'varargannotation', None): self.write(": ") self.dispatch(t.varargannotation) # keyword-only arguments if getattr(t, "kwonlyargs", False): for a, d in zip(t.kwonlyargs, t.kw_defaults): if first:first = False else: self.write(", ") self.dispatch(a), if d: self.write("=") self.dispatch(d) # kwargs if t.kwarg: if first:first = False else: self.write(", ") if hasattr(t.kwarg, 'arg'): self.write("**"+t.kwarg.arg) if t.kwarg.annotation: self.write(": ") self.dispatch(t.kwarg.annotation) else: self.write("**"+t.kwarg) if getattr(t, 'kwargannotation', None): self.write(": ") self.dispatch(t.kwargannotation) def _keyword(self, t): if t.arg is None: # starting from Python 3.5 this denotes a kwargs part of the invocation self.write("**") else: self.write(t.arg) self.write("=") self.dispatch(t.value) def _Lambda(self, t): self.write("(") self.write("lambda ") self.dispatch(t.args) self.write(": ") self.dispatch(t.body) self.write(")") def _alias(self, t): self.write(t.name) if t.asname: self.write(" as "+t.asname) def _withitem(self, t): self.dispatch(t.context_expr) if t.optional_vars: self.write(" as ") self.dispatch(t.optional_vars) def roundtrip(filename, output=sys.stdout): if six.PY3: with open(filename, "rb") as pyfile: encoding = tokenize.detect_encoding(pyfile.readline)[0] with open(filename, "r", encoding=encoding) as pyfile: source = pyfile.read() else: with open(filename, "r") as pyfile: source = pyfile.read() tree = compile(source, filename, "exec", ast.PyCF_ONLY_AST, dont_inherit=True) Unparser(tree, output) def testdir(a): try: names = [n for n in os.listdir(a) if n.endswith('.py')] except OSError: print("Directory not readable: %s" % a, file=sys.stderr) else: for n in names: fullname = os.path.join(a, n) if os.path.isfile(fullname): output = StringIO() print('Testing %s' % fullname) try: roundtrip(fullname, output) except Exception as e: print(' Failed to compile, exception is %s' % repr(e)) elif os.path.isdir(fullname): testdir(fullname) def main(args): if args[0] == '--testdir': for a in args[1:]: testdir(a) else: for a in args: roundtrip(a) if __name__=='__main__': main(sys.argv[1:]) astunparse-1.6.3/requirements.txt000066400000000000000000000000531357773070700172100ustar00rootroot00000000000000wheel >= 0.23.0, < 1.0 six >= 1.6.1, < 2.0 astunparse-1.6.3/setup.cfg000066400000000000000000000000251357773070700155440ustar00rootroot00000000000000[wheel] universal = 1astunparse-1.6.3/setup.py000077500000000000000000000036761357773070700154570ustar00rootroot00000000000000#!/usr/bin/env python # -*- coding: utf-8 -*- import sys import os import re from setuptools import setup, find_packages readme = open('README.rst').read() history = open('HISTORY.rst').read().replace('.. :changelog:', '') def read_reqs(name): with open(os.path.join(os.path.dirname(__file__), name)) as f: return [line for line in f.read().split('\n') if line and not line.strip().startswith('#')] tests_require = [] # mostly handled by tox if sys.version_info < (2, 7): tests_require.append("unittest2 == 0.5.1") # except this def read_version(): with open(os.path.join('lib', 'astunparse', '__init__.py')) as f: m = re.search(r'''__version__\s*=\s*['"]([^'"]*)['"]''', f.read()) if m: return m.group(1) raise ValueError("couldn't find version") setup( name='astunparse', version=read_version(), description='An AST unparser for Python', long_description=readme + '\n\n' + history, maintainer='Simon Percivall', maintainer_email='percivall@gmail.com', url='https://github.com/simonpercivall/astunparse', packages=find_packages('lib'), package_dir={'': 'lib'}, include_package_data=True, install_requires=read_reqs('requirements.txt'), license="BSD", zip_safe=False, keywords='astunparse', classifiers=[ 'Development Status :: 5 - Production/Stable', 'Intended Audience :: Developers', 'License :: OSI Approved :: BSD License', 'Natural Language :: English', "Programming Language :: Python :: 2", 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 3.5', 'Programming Language :: Python :: 3.6', 'Programming Language :: Python :: 3.7', 'Programming Language :: Python :: 3.8', 'Topic :: Software Development :: Code Generators', ], test_suite='tests', tests_require=tests_require, ) astunparse-1.6.3/test_requirements.txt000066400000000000000000000000451357773070700202500ustar00rootroot00000000000000coverage == 3.7.1 -rrequirements.txt astunparse-1.6.3/tests/000077500000000000000000000000001357773070700150705ustar00rootroot00000000000000astunparse-1.6.3/tests/__init__.py000077500000000000000000000000561357773070700172050ustar00rootroot00000000000000#!/usr/bin/env python # -*- coding: utf-8 -*- astunparse-1.6.3/tests/common.py000066400000000000000000000303141357773070700167330ustar00rootroot00000000000000import codecs import os import sys if sys.version_info < (2, 7): import unittest2 as unittest else: import unittest import six if six.PY3: import tokenize else: from lib2to3.pgen2 import tokenize def read_pyfile(filename): """Read and return the contents of a Python source file (as a string), taking into account the file encoding.""" if six.PY3: with open(filename, "rb") as pyfile: encoding = tokenize.detect_encoding(pyfile.readline)[0] with codecs.open(filename, "r", encoding=encoding) as pyfile: source = pyfile.read() else: with open(filename, "r") as pyfile: source = pyfile.read() return source code_parseable_in_all_parser_modes = """\ (a + b + c) * (d + e + f) """ for_else = """\ def f(): for x in range(10): break else: y = 2 z = 3 """ while_else = """\ def g(): while True: break else: y = 2 z = 3 """ relative_import = """\ from . import fred from .. import barney from .australia import shrimp as prawns """ import_many = """\ import fred, barney """ nonlocal_ex = """\ def f(): x = 1 def g(): nonlocal x x = 2 y = 7 def h(): nonlocal x, y """ # also acts as test for 'except ... as ...' raise_from = """\ try: 1 / 0 except ZeroDivisionError as e: raise ArithmeticError from e """ async_comprehensions_and_generators = """\ async def async_function(): my_set = {i async for i in aiter() if i % 2} my_list = [i async for i in aiter() if i % 2] my_dict = {i: -i async for i in aiter() if i % 2} my_gen = (i ** 2 async for i in agen()) my_other_gen = (i - 1 async for i in agen() if i % 2) """ class_decorator = """\ @f1(arg) @f2 class Foo: pass """ elif1 = """\ if cond1: suite1 elif cond2: suite2 else: suite3 """ elif2 = """\ if cond1: suite1 elif cond2: suite2 """ try_except_finally = """\ try: suite1 except ex1: suite2 except ex2: suite3 else: suite4 finally: suite5 """ with_simple = """\ with f(): suite1 """ with_as = """\ with f() as x: suite1 """ with_two_items = """\ with f() as x, g() as y: suite1 """ a_repr = """\ `{}` """ complex_f_string = '''\ f\'\'\'-{f"""*{f"+{f'.{x}.'}+"}*"""}-\'\'\' ''' async_function_def = """\ async def f(): suite1 """ async_for = """\ async def f(): async for _ in reader: suite1 """ async_with = """\ async def f(): async with g(): suite1 """ async_with_as = """\ async def f(): async with g() as x: suite1 """ class AstunparseCommonTestCase: # Tests for specific bugs found in earlier versions of unparse def assertASTEqual(self, dump1, dump2): raise NotImplementedError() def check_roundtrip(self, code1, filename="internal", mode="exec"): raise NotImplementedError() test_directories = [ os.path.join(getattr(sys, 'real_prefix', sys.prefix), 'lib', 'python%s.%s' % sys.version_info[:2])] def test_files(self): names = [] for test_dir in self.test_directories: for n in os.listdir(test_dir): if n.endswith('.py') and not n.startswith('bad'): names.append(os.path.join(test_dir, n)) for filename in names: print('Testing %s' % filename) source = read_pyfile(filename) self.check_roundtrip(source) def test_parser_modes(self): for mode in ['exec', 'single', 'eval']: self.check_roundtrip(code_parseable_in_all_parser_modes, mode=mode) def test_del_statement(self): self.check_roundtrip("del x, y, z") def test_shifts(self): self.check_roundtrip("45 << 2") self.check_roundtrip("13 >> 7") def test_for_else(self): self.check_roundtrip(for_else) def test_while_else(self): self.check_roundtrip(while_else) def test_unary_parens(self): self.check_roundtrip("(-1)**7") self.check_roundtrip("(-1.)**8") self.check_roundtrip("(-1j)**6") self.check_roundtrip("not True or False") self.check_roundtrip("True or not False") @unittest.skipUnless(sys.version_info < (3, 6), "Only works for Python < 3.6") def test_integer_parens(self): self.check_roundtrip("3 .__abs__()") def test_huge_float(self): self.check_roundtrip("1e1000") self.check_roundtrip("-1e1000") self.check_roundtrip("1e1000j") self.check_roundtrip("-1e1000j") @unittest.skipUnless(six.PY2, "Only works for Python 2") def test_min_int27(self): self.check_roundtrip(str(-sys.maxint-1)) self.check_roundtrip("-(%s)" % (sys.maxint + 1)) @unittest.skipUnless(six.PY3, "Only works for Python 3") def test_min_int30(self): self.check_roundtrip(str(-2**31)) self.check_roundtrip(str(-2**63)) def test_imaginary_literals(self): self.check_roundtrip("7j") self.check_roundtrip("-7j") self.check_roundtrip("0j") self.check_roundtrip("-0j") if six.PY2: self.check_roundtrip("-(7j)") self.check_roundtrip("-(0j)") def test_negative_zero(self): self.check_roundtrip("-0") self.check_roundtrip("-(0)") self.check_roundtrip("-0b0") self.check_roundtrip("-(0b0)") self.check_roundtrip("-0o0") self.check_roundtrip("-(0o0)") self.check_roundtrip("-0x0") self.check_roundtrip("-(0x0)") def test_lambda_parentheses(self): self.check_roundtrip("(lambda: int)()") def test_chained_comparisons(self): self.check_roundtrip("1 < 4 <= 5") self.check_roundtrip("a is b is c is not d") def test_function_arguments(self): self.check_roundtrip("def f(): pass") self.check_roundtrip("def f(a): pass") self.check_roundtrip("def f(b = 2): pass") self.check_roundtrip("def f(a, b): pass") self.check_roundtrip("def f(a, b = 2): pass") self.check_roundtrip("def f(a = 5, b = 2): pass") self.check_roundtrip("def f(*args, **kwargs): pass") if six.PY3: self.check_roundtrip("def f(*, a = 1, b = 2): pass") self.check_roundtrip("def f(*, a = 1, b): pass") self.check_roundtrip("def f(*, a, b = 2): pass") self.check_roundtrip("def f(a, b = None, *, c, **kwds): pass") self.check_roundtrip("def f(a=2, *args, c=5, d, **kwds): pass") def test_relative_import(self): self.check_roundtrip(relative_import) def test_import_many(self): self.check_roundtrip(import_many) @unittest.skipUnless(six.PY3, "Only for Python 3") def test_nonlocal(self): self.check_roundtrip(nonlocal_ex) @unittest.skipUnless(six.PY3, "Only for Python 3") def test_raise_from(self): self.check_roundtrip(raise_from) def test_bytes(self): self.check_roundtrip("b'123'") @unittest.skipIf(sys.version_info < (3, 6), "Not supported < 3.6") def test_formatted_value(self): self.check_roundtrip('f"{value}"') self.check_roundtrip('f"{value!s}"') self.check_roundtrip('f"{value:4}"') self.check_roundtrip('f"{value!s:4}"') @unittest.skipIf(sys.version_info < (3, 6), "Not supported < 3.6") def test_joined_str(self): self.check_roundtrip('f"{key}={value!s}"') self.check_roundtrip('f"{key}={value!r}"') self.check_roundtrip('f"{key}={value!a}"') @unittest.skipIf(sys.version_info != (3, 6, 0), "Only supported on 3.6.0") def test_joined_str_361(self): self.check_roundtrip('f"{key:4}={value!s}"') self.check_roundtrip('f"{key:02}={value!r}"') self.check_roundtrip('f"{key:6}={value!a}"') self.check_roundtrip('f"{key:4}={value:#06x}"') self.check_roundtrip('f"{key:02}={value:#06x}"') self.check_roundtrip('f"{key:6}={value:#06x}"') self.check_roundtrip('f"{key:4}={value!s:#06x}"') self.check_roundtrip('f"{key:4}={value!r:#06x}"') self.check_roundtrip('f"{key:4}={value!a:#06x}"') @unittest.skipUnless(six.PY2, "Only for Python 2") def test_repr(self): self.check_roundtrip(a_repr) @unittest.skipUnless(sys.version_info[:2] >= (3, 6), "Only for Python 3.6 or greater") def test_complex_f_string(self): self.check_roundtrip(complex_f_string) @unittest.skipUnless(six.PY3, "Only for Python 3") def test_annotations(self): self.check_roundtrip("def f(a : int): pass") self.check_roundtrip("def f(a: int = 5): pass") self.check_roundtrip("def f(*args: [int]): pass") self.check_roundtrip("def f(**kwargs: dict): pass") self.check_roundtrip("def f() -> None: pass") @unittest.skipIf(sys.version_info < (2, 7), "Not supported < 2.7") def test_set_literal(self): self.check_roundtrip("{'a', 'b', 'c'}") @unittest.skipIf(sys.version_info < (2, 7), "Not supported < 2.7") def test_set_comprehension(self): self.check_roundtrip("{x for x in range(5)}") @unittest.skipIf(sys.version_info < (2, 7), "Not supported < 2.7") def test_dict_comprehension(self): self.check_roundtrip("{x: x*x for x in range(10)}") @unittest.skipIf(sys.version_info < (3, 6), "Not supported < 3.6") def test_dict_with_unpacking(self): self.check_roundtrip("{**x}") self.check_roundtrip("{a: b, **x}") @unittest.skipIf(sys.version_info < (3, 6), "Not supported < 3.6") def test_async_comp_and_gen_in_async_function(self): self.check_roundtrip(async_comprehensions_and_generators) @unittest.skipIf(sys.version_info < (3, 7), "Not supported < 3.7") def test_async_comprehension(self): self.check_roundtrip("{i async for i in aiter() if i % 2}") self.check_roundtrip("[i async for i in aiter() if i % 2]") self.check_roundtrip("{i: -i async for i in aiter() if i % 2}") @unittest.skipIf(sys.version_info < (3, 7), "Not supported < 3.7") def test_async_generator_expression(self): self.check_roundtrip("(i ** 2 async for i in agen())") self.check_roundtrip("(i - 1 async for i in agen() if i % 2)") def test_class_decorators(self): self.check_roundtrip(class_decorator) @unittest.skipUnless(six.PY3, "Only for Python 3") def test_class_definition(self): self.check_roundtrip("class A(metaclass=type, *[], **{}): pass") def test_elifs(self): self.check_roundtrip(elif1) self.check_roundtrip(elif2) def test_try_except_finally(self): self.check_roundtrip(try_except_finally) @unittest.skipUnless(six.PY3, "Only for Python 3") def test_starred_assignment(self): self.check_roundtrip("a, *b, c = seq") self.check_roundtrip("a, (*b, c) = seq") self.check_roundtrip("a, *b[0], c = seq") self.check_roundtrip("a, *(b, c) = seq") @unittest.skipIf(sys.version_info < (3, 6), "Not supported < 3.6") def test_variable_annotation(self): self.check_roundtrip("a: int") self.check_roundtrip("a: int = 0") self.check_roundtrip("a: int = None") self.check_roundtrip("some_list: List[int]") self.check_roundtrip("some_list: List[int] = []") self.check_roundtrip("t: Tuple[int, ...] = (1, 2, 3)") self.check_roundtrip("(a): int") self.check_roundtrip("(a): int = 0") self.check_roundtrip("(a): int = None") def test_with_simple(self): self.check_roundtrip(with_simple) def test_with_as(self): self.check_roundtrip(with_as) @unittest.skipIf(sys.version_info < (2, 7), "Not supported < 2.7") def test_with_two_items(self): self.check_roundtrip(with_two_items) @unittest.skipIf(sys.version_info < (3, 5), "Not supported < 3.5") def test_async_function_def(self): self.check_roundtrip(async_function_def) @unittest.skipIf(sys.version_info < (3, 5), "Not supported < 3.5") def test_async_for(self): self.check_roundtrip(async_for) @unittest.skipIf(sys.version_info < (3, 5), "Not supported < 3.5") def test_async_with(self): self.check_roundtrip(async_with) @unittest.skipIf(sys.version_info < (3, 5), "Not supported < 3.5") def test_async_with_as(self): self.check_roundtrip(async_with_as) astunparse-1.6.3/tests/test_dump.py000066400000000000000000000013311357773070700174440ustar00rootroot00000000000000import ast import re import sys if sys.version_info < (2, 7): import unittest2 as unittest else: import unittest import astunparse from tests.common import AstunparseCommonTestCase class DumpTestCase(AstunparseCommonTestCase, unittest.TestCase): def assertASTEqual(self, dump1, dump2): # undo the pretty-printing dump1 = re.sub(r"(?<=[\(\[])\n\s+", "", dump1) dump1 = re.sub(r"\n\s+", " ", dump1) self.assertEqual(dump1, dump2) def check_roundtrip(self, code1, filename="internal", mode="exec"): ast_ = compile(str(code1), filename, mode, ast.PyCF_ONLY_AST) dump1 = astunparse.dump(ast_) dump2 = ast.dump(ast_) self.assertASTEqual(dump1, dump2) astunparse-1.6.3/tests/test_unparse.py000066400000000000000000000011761357773070700201630ustar00rootroot00000000000000import ast import sys if sys.version_info < (2, 7): import unittest2 as unittest else: import unittest import astunparse from tests.common import AstunparseCommonTestCase class UnparseTestCase(AstunparseCommonTestCase, unittest.TestCase): def assertASTEqual(self, ast1, ast2): self.assertEqual(ast.dump(ast1), ast.dump(ast2)) def check_roundtrip(self, code1, filename="internal", mode="exec"): ast1 = compile(str(code1), filename, mode, ast.PyCF_ONLY_AST) code2 = astunparse.unparse(ast1) ast2 = compile(code2, filename, mode, ast.PyCF_ONLY_AST) self.assertASTEqual(ast1, ast2) astunparse-1.6.3/tox.ini000066400000000000000000000015711357773070700152450ustar00rootroot00000000000000[tox] envlist = py27, py35, py36, py37, py38 [testenv] usedevelop = True commands = {envpython} setup.py test deps = -rtest_requirements.txt [testenv:py26] deps = -rtest_requirements.txt unittest2 == 0.5.1 [testenv:docs] basepython = python2.7 usedevelop = True commands = sphinx-apidoc -T -o docs/ lib make -C docs clean make -C docs html whitelist_externals = make rm deps = -rdocs/requirements.txt [testenv:coverage] usedevelop = True basepython = python2.7 commands = coverage run --source astunparse setup.py test coverage report -m coverage html deps = -rtest_requirements.txt [testenv:ipython] basepython = python2.7 usedevelop = True commands = ipython deps = ipython -rtest_requirements.txt [testenv:ipython3] basepython = python3.5 usedevelop = True commands = ipython3 deps = ipython -rtest_requirements.txt