Python library to statically detect types for AST nodes.
A good use case is a linter that needs to run some rules only for particular types. For instance, to check arguments of something.format(a=b)
only if something
has type str
.
python3 -m pip install astypes
Astypes uses astroid to infer definitions of nodes. So, if your code works with ast nodes, you'll need to convert them into astroid first:
import astroid import astypes module = astroid.parse(source_code) node = astypes.find_node(module, ast_node)
And when you have an astroid node, you can get its type:
node_type = astype.get_node(node) print(node_type.annotation)
Example:
import astroid import astypes node = astroid.extract_node('1 + 2.3') t = astypes.get_type(node) print(t.annotation) # 'float'
For a real-world usage example, check out infer-types. It is a CLI tool that automatically adds type annotations into Python code using astypes.
You can find most of the logic in astypes/_handlers.py. In short:
13
is always int
.list(x)
returns type list
. It might be not true if you shadow list
with something else.RetroSearch is an open source project built by @garambo | Open a GitHub Issue
Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo
HTML:
3.2
| Encoding:
UTF-8
| Version:
0.7.4