summaryrefslogtreecommitdiff
path: root/astroid/_ast.py
diff options
context:
space:
mode:
authorClaudiu Popa <pcmanticore@gmail.com>2018-06-03 12:13:39 +0800
committerClaudiu Popa <pcmanticore@gmail.com>2018-06-04 06:52:05 -0700
commita4f500b3c960bffd09ec90caa41863a64479487d (patch)
treefabf257986bf8328989f0d5606a3691adac83812 /astroid/_ast.py
parent085ed07aaa11b1b62c7fe6f3d646596f393e81ff (diff)
downloadastroid-git-a4f500b3c960bffd09ec90caa41863a64479487d.tar.gz
Add support for parsing function type comments
This commit exposes two new attributes to the FunctionDef nodes, type_comment_args respectively type_comment_annotations. These two attributes hold the type annotations provided via type comments.
Diffstat (limited to 'astroid/_ast.py')
-rw-r--r--astroid/_ast.py17
1 files changed, 17 insertions, 0 deletions
diff --git a/astroid/_ast.py b/astroid/_ast.py
index 8220e108..58a58c77 100644
--- a/astroid/_ast.py
+++ b/astroid/_ast.py
@@ -1,4 +1,6 @@
import ast
+from collections import namedtuple
+from typing import Optional
_ast_py2 = _ast_py3 = None
try:
@@ -8,6 +10,9 @@ except ImportError:
pass
+FunctionType = namedtuple('FunctionType', ['argtypes', 'returns'])
+
+
def _get_parser_module(parse_python_two: bool = False):
if parse_python_two:
parser_module = _ast_py2
@@ -19,3 +24,15 @@ def _get_parser_module(parse_python_two: bool = False):
def _parse(string: str,
parse_python_two: bool = False):
return _get_parser_module(parse_python_two=parse_python_two).parse(string)
+
+
+def parse_function_type_comment(type_comment: str) -> Optional[FunctionType]:
+ """Given a correct type comment, obtain a FunctionType object"""
+ if _ast_py3 is None:
+ return None
+
+ func_type = _ast_py3.parse(type_comment, "<type_comment>", "func_type")
+ return FunctionType(
+ argtypes=func_type.argtypes,
+ returns=func_type.returns,
+ )