Modified fork of CPython's ast module that parses `# type:` comments

Overview

Typed AST

Build Status Chat at https://gitter.im/python/typed_ast

typed_ast is a Python 3 package that provides a Python 2.7 and Python 3 parser similar to the standard ast library. Unlike ast up to Python 3.7, the parsers in typed_ast include PEP 484 type comments and are independent of the version of Python under which they are run. The typed_ast parsers produce the standard Python AST (plus type comments), and are both fast and correct, as they are based on the CPython 2.7 and 3.7 parsers. typed_ast runs on CPython 3.6-3.10 on Linux, OS X and Windows.

Note: Starting with Python 3.8, we recommend to use the native ast parser (see below).

Development Philosophy

This project is a (mostly) drop-in replacement for the builtin ast module. It is intended to be bug-for-bug compatible and behave identically, except for the presence of a few additional fields on the returned classes and a few additional optional arguments to the parse call. Therefore, typed_ast will not accept any bugfixes for bugs in ast -- they should be fixed upstream instead. To avoid feature bloat, any new features for typed_ast should have the potential to be broadly useful and not be built just for one niche usecase or in a manner such that only one project can use them.

Incompatibilities

For the purposes of consuming syntax trees, this should be a drop-in replacement. It is not a drop-in replacement for users that wish to create or transform ASTs, as a number of syntax tree classes have additional fields that must be populated when constructing them.

Due to reliance on certain C APIs, this library does not build on and there are no plans to support PyPy.

Python 3.8

typed_ast will not be updated to support parsing Python 3.8 and newer. Instead, it is recommended to use the stdlib ast module there, which has been augmented to support extracting type comments and has limited support for parsing older versions of Python 3.

Submodules

ast3

The ast3 parser produces the AST from a Python 3 code, up to Python 3.7. (For rationale and technical details, see here.) The AST it currently produces is described in ast3/Parser/Python.asdl. If you wish to limit parsing to older versions of Python 3, ast3 can be configured to to give a SyntaxError for new syntax features introduced beyond a given Python version. For more information, see the module docstring in typed_ast/ast3.py.

ast27

The ast27 parser tracks the standard Python 2.7 AST, which is expected to never receive further updates. The AST it produces is described in ast27/Parser/Python.asdl. For more information, see the module docstring in typed_ast/ast27.py.

conversions

typed_ast also provides a conversions module which converts ast27 ASTs into ast3 ASTs. This functionality is somewhat experimental, however. For more information, see the py2to3 docstring in typed_ast/conversions.

Note: as these parsers consider type comments part of the grammar, incorrectly placed type comments are considered syntax errors.

Updates and Releases

To update typed_ast for new major Python releases, see update_process.md.

To make a new typed_ast release, see release_process.md.

Comments
  • [DO NOT MERGE] Fix def line numbers for decorated nodes

    [DO NOT MERGE] Fix def line numbers for decorated nodes

    Previously, due to requirements of inspect.getsource and getting the bytecode first line number correct, CPython had to patch the line number of decorated AST nodes. This changes that so for:

    @decorate(
            "multi",
            "line"
            )
    def foo(
            a: int,
            b: str,
            ):
    
            pass
    

    The line number for the foo FunctionDef is 5, not 1. Based on my work in https://github.com/python/cpython/pull/6460

    Fixes https://github.com/python/typed_ast/issues/50 and fixes https://github.com/python/mypy/issues/3871

    CLA signed 
    opened by ethanhs 28
  • ast27 gives syntax error for valid code on s390x

    ast27 gives syntax error for valid code on s390x

    This examples comes from the test suite of black

    from typed_ast import ast27
    
    ast27.parse('''#!/usr/bin/env python2.7
    
    def function((_globals, _locals)):
        print _globals, _locals
    ''')
    

    Results in:

    Traceback (most recent call last):
    
      File "/usr/lib/python3.8/site-packages/IPython/core/interactiveshell.py", line 3417, in run_code
        exec(code_obj, self.user_global_ns, self.user_ns)
    
      File "<ipython-input-3-46b135e3f4de>", line 1, in <module>
        ast27.parse('''#!/usr/bin/env python2.7
    
      File "/usr/lib/python3.8/site-packages/typed_ast/ast27.py", line 50, in parse
        return _ast27.parse(source, filename, mode)
    
      File "<unknown>", line 3
    SyntaxError: can't assign to ()
    

    The same code parses fine on python 2.7.18.

    This is with typed-ast 1.4.1. It only happens on s390x on Alpine Linux edge.

    Let me know if you need more information.

    opened by Ikke 26
  • Python 3.8+ features in typeshed stubs

    Python 3.8+ features in typeshed stubs

    If typeshed would start using Python 3.8 only features, such as positional-only arguments, tools such as mypy that use typed-ast when running under 3.7 or earlier would sometimes be unable to parse those stubs, since typed-ast won't get any post-3.7 features according to current policies. This seems to rule out using 3.8 features in typeshed. Similarly, in case Python 3.9 introduces a new syntax for optional types, for example, it looks like we wouldn't be able to use that syntax in typeshed (at least for several years).

    I see a few options that could help with the issue:

    1. Work towards establishing a typeshed policy that stubs should only use syntax that is supported by the oldest maintained Python 3+ release (currently that would be 3.5). We actually already use 3.6 syntax in typeshed, but we could make it an exception.
    2. Revert to the original policy of backporting all new Python syntax to typed-ast.

    Option 1 could become a problem in a few scenarios that don't seem totally implausible:

    • An existing keyword stops being a keyword, so older Python parsers won't be able to represent identifiers with that name. This could mean that we can't represent some stdlib module stubs precisely.
    • Some new type related syntax gets introduced for which we can't design a good fallback syntax for older Python releases.

    @gvanrossum @ilevkivskyi @msullivan What do you think about this?

    opened by JukkaL 21
  • Add Python 3.9 for Windows

    Add Python 3.9 for Windows

    Not sure if this will works, 3.9 is not yet listed on the indicated page.

    Might fix #146 and then also will fix https://github.com/python/mypy/issues/9488

    CLA signed 
    opened by gvanrossum 19
  • Module load fails with Python 3.9.8 (undefined symbol _PyUnicode_DecodeUnicodeEscape)

    Module load fails with Python 3.9.8 (undefined symbol _PyUnicode_DecodeUnicodeEscape)

    Attempting to import the module as installed from PyPI (x86_64 architecture) on Python 3.9.8 produces the following exception:

    Traceback (most recent call last):
      File "/home/runner/.cache/pre-commit/repo8e93dzwn/py_env-python3/bin/black", line 5, in <module>
        from black import patched_main
      File "/home/runner/.cache/pre-commit/repo8e93dzwn/py_env-python3/lib/python3.9/site-packages/black/__init__.py", line 52, in <module>
        from typed_ast import ast3, ast27
      File "/home/runner/.cache/pre-commit/repo8e93dzwn/py_env-python3/lib/python3.9/site-packages/typed_ast/ast3.py", line 40, in <module>
        from typed_ast import _ast3
    ImportError: /home/runner/.cache/pre-commit/repo8e93dzwn/py_env-python3/lib/python3.9/site-packages/typed_ast/_ast3.cpython-39-x86_64-linux-gnu.so: undefined symbol: _PyUnicode_DecodeUnicodeEscape
    

    This appears to have broken between Python 3.9.7 and Python 3.9.8.

    opened by rra 13
  • Implement PEP 526 Variable Annotations Syntax

    Implement PEP 526 Variable Annotations Syntax

    @ddfisher @gvanrossum @JukkaL

    Here is an implementation of the PEP 526 syntax with minimal changes in typed_ast API. The only externally visible change is:

    Assign(expr* targets, expr? value, expr? type_comment)
    

    This requires a tiny change to mypy/fastparse.py, there is an accompanying PR to mypy with this change.

    opened by ilevkivskyi 13
  • typed-ast end of life?

    typed-ast end of life?

    I suggest we officially end of life typed-ast:

    • Officially stop support after Python 3.10 (i.e. close #167).
    • Add recommendation to use ast on Python 3.8+ in the package's long_description and more prominently in the README.
    • Add < 3.11 to python_requires.

    We can keep maintaining it until 3.7 (or 3.10) reaches end of life, and improved ast is generally available.

    opened by srittau 12
  • Error installing on Python 3.9

    Error installing on Python 3.9

    Pretty sure this is the same issue as #126 ~but its really annoying that this occurs for every new python release, especially since the first 3.9 testing release has been out for almost a year and final is supposed to be out in a week.~. Sorry didn't see readme explicitly states that python 3.8+ are not supported.

    opened by BrianMSheldon 12
  • Python 3.8 build fails

    Python 3.8 build fails

    After commit bd75088ea9b03df1618f1e0b8423a496412ae663 (I guess, because it changes _PyObject_FastCall related code) build fails with this message:

    gcc -Wno-unused-result -Wsign-compare -DNDEBUG -g -fwrapv -O3 -Wall -DTHREAD_STACK_SIZE=0x100000 -fPIC -Iast3/Include -I/usr/local/include/python3.8 -c ast3/Python/ast.c -o build/temp.linux-x86_64-3.8/ast3/Python/ast.o
        ast3/Python/ast.c:22:1: error: conflicting types for '_PyObject_FastCall'
         _PyObject_FastCall(PyObject *func, PyObject *const *args, int nargs)
         ^~~~~~~~~~~~~~~~~~
        In file included from /usr/local/include/python3.8/abstract.h:837,
                         from /usr/local/include/python3.8/Python.h:147,
                         from ast3/Python/ast.c:6:
        /usr/local/include/python3.8/cpython/abstract.h:142:1: note: previous definition of '_PyObject_FastCall' was here
         _PyObject_FastCall(PyObject *func, PyObject *const *args, Py_ssize_t nargs)
         ^~~~~~~~~~~~~~~~~~
    

    Environment: Docker Alpine 3.9 Python 3.8 (3.8-rc-alpine3.9) Related bug report in Red Hat tracker

    opened by HarrySky 12
  • Fix cross compile by adjusting includes

    Fix cross compile by adjusting includes

    Header names conflict with python itself, causing cross compile issues. This change forces use of in-package header files.

    Not sure if this solution is a desirable fix for #134, or if there is a better solution available.

    CLA not signed 
    opened by CameronNemo 11
  • add __version__ and version_info

    add __version__ and version_info

    This change allows programs and other packages to do:

      import typed_ast
      if typed_ast.version_info < (1, 1):
          print(typed_ast.__version__)
    

    currently the only way to get that version number is by doing

      import pkg_resources
      pkg_resources.require('typed-ast')[0].version)
    

    (pr on mypy, rejected at least partly, because of the difficulty of extracting the typed_ast version number)

    CLA signed 
    opened by AvdN 11
  • typed_ast end of life (July 2023)

    typed_ast end of life (July 2023)

    typed_ast does not support parsing syntax introduced in Python 3.8 and newer, and never will. Instead, it is recommended to use the stdlib ast module in Python 3.8 and newer, which has been augmented to support extracting type comments and has some support for parsing older versions of Python 3.

    This means the only valid use cases for typed_ast are a) parsing when run with Python 3.7 and older, or b) parsing Python 2.

    typed_ast will continue to be maintained through Python 3.7 EOL (27 June 2023), but will likely become unmaintained soon thereafter.

    Given this, we recommend:

    • Switch your project over to using ast when run on Python 3.8 or newer. Avoid installing typed_ast when running on Python 3.8 or newer by using a PEP 508 requirement, see for example.
    • If your project supports parsing Python 2, make this support an optional extra, so users do not have to install typed_ast unless they need that support, see for example. Also, y'know, consider dropping Python 2 support.

    (To avoid user confusion, please discuss in #170)

    opened by hauntsaninja 0
Owner
Python
Repositories related to the Python Programming language
Python
A Python module for creating Excel XLSX files.

XlsxWriter XlsxWriter is a Python module for writing files in the Excel 2007+ XLSX file format. XlsxWriter can be used to write text, numbers, formula

John McNamara 3.1k Dec 29, 2022
A module filled with many useful functions and modules in various subjects.

Usefulpy Check out the Usefulpy site Usefulpy site is not always up to date Download and Import download and install with with pip download usefulpyth

Austin Garcia 1 Dec 28, 2021
Tool for translation type comments to type annotations in Python

com2ann Tool for translation of type comments to type annotations in Python. The tool requires Python 3.8 to run. But the supported target code versio

Ivan Levkivskyi 123 Nov 12, 2022
Modified fork of Xuebin Qin's U-2-Net Repository. Used for demonstration purposes.

U^2-Net (U square net) Modified version of U2Net used for demonstation purposes. Paper: U^2-Net: Going Deeper with Nested U-Structure for Salient Obje

Shreyas Bhat Kera 13 Aug 28, 2022
A music comments dataset, containing 39,051 comments for 27,384 songs.

Music Comments Dataset A music comments dataset, containing 39,051 comments for 27,384 songs. For academic research use only. Introduction This datase

Zhang Yixiao 2 Jan 10, 2022
Custom Python linting through AST expressions

bellybutton bellybutton is a customizable, easy-to-configure linting engine for Python. What is this good for? Tools like pylint and flake8 provide, o

H. Chase Stevens 249 Dec 31, 2022
Code for the Interspeech 2021 paper "AST: Audio Spectrogram Transformer".

AST: Audio Spectrogram Transformer Introduction Citing Getting Started ESC-50 Recipe Speechcommands Recipe AudioSet Recipe Pretrained Models Contact I

Yuan Gong 603 Jan 7, 2023
Simple, hassle-free, dependency-free, AST based source code refactoring toolkit.

refactor is an end-to-end refactoring framework that is built on top of the 'simple but effective refactorings' assumption. It is much easier to write a simple script with it rather than trying to figure out what sort of a regex you need in order to replace a pattern (if it is even matchable with regexes).

Batuhan Taskaya 385 Jan 6, 2023
AST based refactoring tool for Python.

breakfast AST based refactoring tool. (Very early days, not usable yet.) Why 'breakfast'? I don't know about the most important, but it's a good meal.

eric casteleijn 0 Feb 22, 2022
Get information about what a Python frame is currently doing, particularly the AST node being executed

executing This mini-package lets you get information about what a frame is currently doing, particularly the AST node being executed. Usage Getting th

Alex Hall 211 Jan 1, 2023
Retrieve annotated intron sequences and classify them as minor (U12-type) or major (U2-type)

(intron I nterrogator and C lassifier) intronIC is a program that can be used to classify intron sequences as minor (U12-type) or major (U2-type), usi

Graham Larue 4 Jul 26, 2022
Parses data out of your Google Takeout (History, Activity, Youtube, Locations, etc...)

google_takeout_parser parses both the Historical HTML and new JSON format for Google Takeouts caches individual takeout results behind cachew merge mu

Sean Breckenridge 27 Dec 28, 2022
This tool parses log data and allows to define analysis pipelines for anomaly detection.

logdata-anomaly-miner This tool parses log data and allows to define analysis pipelines for anomaly detection. It was designed to run the analysis wit

AECID 32 Nov 27, 2022
CiteURL is an extensible tool that parses legal citations and makes links to websites where you can read the cited language for free.

CiteURL is an extensible tool that parses legal citations and makes links to websites where you can read the cited language for free. It can be used t

null 15 Dec 27, 2022
The disassembler parses evm bytecode from the command line or from a file.

EVM Bytecode Disassembler The disassembler parses evm bytecode from the command line or from a file. It does not matter whether the bytecode is prefix

alpharush 22 Dec 27, 2022
Chilean Digital Vaccination Pass Parser (CDVPP) parses digital vaccination passes from PDF files

cdvpp Chilean Digital Vaccination Pass Parser (CDVPP) parses digital vaccination passes from PDF files Reads a Digital Vaccination Pass PDF file as in

Esteban Borai 1 Nov 17, 2021
Finds, downloads, parses, and standardizes public bikeshare data into a standard pandas dataframe format

Finds, downloads, parses, and standardizes public bikeshare data into a standard pandas dataframe format.

Brady Law 2 Dec 1, 2021
A Python tool that parses JSON documents using JsonPath

A Python tool that parses JSON documents using JsonPath

null 8 Dec 18, 2022
A Python script that parses and checks public proxies. Multithreading is supported.

A Python script that parses and checks public proxies. Multithreading is supported.

LevPrav 7 Nov 25, 2022