diff options
| author | Daniƫl van Noord <13665637+DanielNoord@users.noreply.github.com> | 2022-07-01 10:22:20 +0200 |
|---|---|---|
| committer | GitHub <noreply@github.com> | 2022-07-01 10:22:20 +0200 |
| commit | 9531e037bba6dcd1edd0e4626883e54ce6e3b6da (patch) | |
| tree | 0703ed0c14376a7b8174e3f35a70001e2f9e4b55 | |
| parent | 49beab3d0cd013080d82fc90581e2018bfbb4732 (diff) | |
| download | astroid-git-9531e037bba6dcd1edd0e4626883e54ce6e3b6da.tar.gz | |
Refactor field inference to ``_get_namedtuple_fields`` (#1413)
| -rw-r--r-- | astroid/brain/brain_namedtuple_enum.py | 32 |
1 files changed, 23 insertions, 9 deletions
diff --git a/astroid/brain/brain_namedtuple_enum.py b/astroid/brain/brain_namedtuple_enum.py index aeedfcff..94b0ae79 100644 --- a/astroid/brain/brain_namedtuple_enum.py +++ b/astroid/brain/brain_namedtuple_enum.py @@ -85,13 +85,17 @@ def infer_func_form( try: name, names = _find_func_form_arguments(node, context) try: - attributes = names.value.replace(",", " ").split() + attributes: list[str] = names.value.replace(",", " ").split() except AttributeError as exc: # Handle attributes of NamedTuples if not enum: - attributes = [ - _infer_first(const, context).value for const in names.elts - ] + attributes = [] + fields = _get_namedtuple_fields(node) + if fields: + fields_node = extract_node(fields) + attributes = [ + _infer_first(const, context).value for const in fields_node.elts + ] # Handle attributes of Enums else: @@ -522,21 +526,31 @@ def infer_typing_namedtuple( if not isinstance(node.args[1], (nodes.List, nodes.Tuple)): raise UseInferenceDefault + return infer_named_tuple(node, context) + + +def _get_namedtuple_fields(node: nodes.Call) -> str: + """Get and return fields of a NamedTuple in code-as-a-string. + + Because the fields are represented in their code form we can + extract a node from them later on. + """ names = [] - for elt in node.args[1].elts: + for elt in next(node.args[1].infer()).elts: + if isinstance(elt, nodes.Const): + names.append(elt.as_string()) + continue if not isinstance(elt, (nodes.List, nodes.Tuple)): raise UseInferenceDefault if len(elt.elts) != 2: raise UseInferenceDefault names.append(elt.elts[0].as_string()) - typename = node.args[0].as_string() if names: field_names = f"({','.join(names)},)" else: - field_names = "''" - node = extract_node(f"namedtuple({typename}, {field_names})") - return infer_named_tuple(node, context) + field_names = "" + return field_names def _is_enum_subclass(cls: astroid.ClassDef) -> bool: |
