畢竟 mypy 是個命令列程式︰
rock64@rock64:~ mypy my_program.py my_src_folder For more information on getting started, see: - http://mypy.readthedocs.io/en/latest/getting_started.html For more details on both running mypy and using the flags below, see: - http://mypy.readthedocs.io/en/latest/running_mypy.html - http://mypy.readthedocs.io/en/latest/command_line.html ...
打算深入了解 Python
26.1. typing
— Support for type hints
New in version 3.5.
Source code: Lib/typing.py
This module supports type hints as specified by PEP 484. The most fundamental support consists of the types Any
,Union
, Tuple
, Callable
, TypeVar
, and Generic
. For full specification please see PEP 484. For a simplified introduction to type hints see PEP 483.
The function below takes and returns a string and is annotated as follows:
def greeting(name: str) -> str: return 'Hello ' + name
In the function greeting
, the argument name
is expected to be of type str
and the return type str
. Subtypes are accepted as arguments.
或喜多所見聞也︰
Typed Python AST (abstract syntax tree) unparser
The typed-astunparse Python package is to typed-ast as astunparse is to ast. In 10 words: it enables unparsing of Python 3 AST with type comments.
The built-in ast module can parse Python source code into AST. It can’t, however, generate source code from the AST. That’s where astunparse comes in. Using a refactored version of an obscure script found in official Python repository, it provides code generation capability for native Python AST.
The ast and astunparse modules, however, completely ignore type comments introduced in PEP 484. They treat them like all other comments, so when you parse the code using compile()
, your type comments will be lost. There is no place for them in the AST, so obviously they also cannot be unparsed.
The typed-ast module provides an updated AST including type comments defined in PEP 484 and a parser for Python code that contains such comments.
Unfortunately, typed-ast doesn’t provide any means to go from AST back to source code with type comments. This is where this module, typed-astunparse, comes in. It provides unparser for AST defined in typed-ast.
links
-
ast:
-
astunparse:
https://pypi.python.org/pypi/astunparse
-
PEP 483 – The Theory of Type Hints:
-
PEP 484 – Type Hints:
-
PEP 3107 – Function Annotations:
-
PEP 526 – Syntax for Variable Annotations:
-
typed-ast:
也許可藉
/static-typing
Add static type information into Python abstract syntax trees.
static-typing
Attempt to add static type information to Python abstract syntax trees (ASTs).
Works best with ASTs from typed_ast
module, however it also works with built-in ast
module.
Be advised that this is an ongoing work, and current implementation is subject to sudden changes.
Contents
想想可能的應用哩☆
※ 註︰ Python 3.6 前之版本, AST 驗證不可用。
故省略部分範例程式碼。