diff options
author | Torsten Marek <tmarek@google.com> | 2013-11-03 09:50:19 -0800 |
---|---|---|
committer | Torsten Marek <tmarek@google.com> | 2013-11-03 09:50:19 -0800 |
commit | baf53b84cdaf74ed279ab5af38087ebb0faa161d (patch) | |
tree | 0dfba1249baf63291c81b7189a914e7abda51fda /brain/py2stdlib.py | |
parent | 813ea6fd7863fcc9f67dcd1deaddd226c12eed77 (diff) | |
download | astroid-git-baf53b84cdaf74ed279ab5af38087ebb0faa161d.tar.gz |
Add support for inferring the arguments to namedtuple invocations, to support cases like this:
fields = ['a', 'b', 'c']
A = collections.namedtuple('A', fields)
Diffstat (limited to 'brain/py2stdlib.py')
-rw-r--r-- | brain/py2stdlib.py | 22 |
1 files changed, 17 insertions, 5 deletions
diff --git a/brain/py2stdlib.py b/brain/py2stdlib.py index 31a2477e..27507ec4 100644 --- a/brain/py2stdlib.py +++ b/brain/py2stdlib.py @@ -5,7 +5,8 @@ Currently help understanding of : * hashlib.md5 and hashlib.sha1 """ -from astroid import MANAGER, AsStringRegexpPredicate, UseInferenceDefault, inference_tip +from astroid import MANAGER, AsStringRegexpPredicate, UseInferenceDefault, inference_tip, YES +from astroid import exceptions from astroid import nodes from astroid.builder import AstroidBuilder @@ -183,6 +184,16 @@ MODULE_TRANSFORMS['subprocess'] = subprocess_transform def infer_named_tuple(node, context=None): """Specific inference function for namedtuple CallFunc node""" + def infer_first(node): + try: + value = node.infer().next() + if value is YES: + raise UseInferenceDefault() + else: + return value + except StopIteration: + raise InferenceError() + # node is a CallFunc node, class name as first argument and generated class # attributes as second argument if len(node.args) != 2: @@ -191,12 +202,13 @@ def infer_named_tuple(node, context=None): # namedtuple list of attributes can be a list of strings or a # whitespace-separate string try: - name = node.args[0].value + name = infer_first(node.args[0]).value + names = infer_first(node.args[1]) try: - attributes = node.args[1].value.split() + attributes = names.value.split() except AttributeError: - attributes = [const.value for const in node.args[1].elts] - except AttributeError: + attributes = [infer_first(const).value for const in names.elts] + except (AttributeError, exceptions.InferenceError): raise UseInferenceDefault() # we want to return a Class node instance with proper attributes set class_node = nodes.Class(name, 'docstring') |