summaryrefslogtreecommitdiff
path: root/astroid
diff options
context:
space:
mode:
authorAndrew Haigh <hello@nelf.in>2021-05-30 05:44:36 +1000
committerGitHub <noreply@github.com>2021-05-29 21:44:36 +0200
commit8a08d50d0b83feae1dfa0b0c3ca1748b0d708429 (patch)
treed438ce90b36ef217156e694fb3f3d749f081cc92 /astroid
parent0689f0e3cd29aae24c135d64c53b05dcf73d4d33 (diff)
downloadastroid-git-8a08d50d0b83feae1dfa0b0c3ca1748b0d708429.tar.gz
Fix unhandled AstroidSyntaxError raised by infer_named_tuple brain (#929)
* Fix uncaught AstroidSyntaxErrors in namedtuple brain Ref #920. This adds a test suite and updates the infer_named_tuple brain with some additional behaviours expected by `collections.namedtuple`, specifically about rejecting invalid type and field names. Some of these cases inferred as namedtuples/`ClassDef` when they would have raised `ValueError` and some of these raise unhandled `AstroidSyntaxError`s due to attempts to parse class fakes with type names that would have raised `ValueError`. For example: from collections import namedtuple Tuple = namedtuple('X', 'abc abc') # Traceback (most recent call last): # ... # ValueError: Encountered duplicate field name: 'abc' import astroid node = astroid.extract_node(""" from collections import namedtuple Tuple = namedtuple('X', 'abc abc') Tuple """) next(node.infer()) # <ClassDef.X l.3 at 0x...> from collections import namedtuple Tuple = namedtuple('123', 'abc') # Traceback (most recent call last): # ... # ValueError: Type names and field names must be valid identifiers: '123' import astroid node = astroid.extract_node(""" from collections import namedtuple Tuple = namedtuple('123', 'abc') Tuple """) next(node.infer()) # Traceback (most recent call last): # ... # KeyError: (<function infer_named_tuple at 0x...>, <Call l.3 at 0x...>) # # During handling of the above exception, another exception occurred: # # Traceback (most recent call last): # ... # File "<unknown>", line 2 # class 123(tuple): # ^ # SyntaxError: invalid syntax # # The above exception was the direct cause of the following exception: # # Traceback (most recent call last): # ... # astroid.exceptions.AstroidSyntaxError: Parsing Python code failed: # invalid syntax (<unknown>, line 2)
Diffstat (limited to 'astroid')
-rw-r--r--astroid/brain/brain_namedtuple_enum.py48
-rw-r--r--astroid/exceptions.py4
2 files changed, 50 insertions, 2 deletions
diff --git a/astroid/brain/brain_namedtuple_enum.py b/astroid/brain/brain_namedtuple_enum.py
index 9a9cc989..a9f15949 100644
--- a/astroid/brain/brain_namedtuple_enum.py
+++ b/astroid/brain/brain_namedtuple_enum.py
@@ -28,6 +28,8 @@ from textwrap import dedent
from astroid import (
MANAGER,
+ AstroidTypeError,
+ AstroidValueError,
InferenceError,
UseInferenceDefault,
arguments,
@@ -130,6 +132,11 @@ def infer_func_form(node, base_type, context=None, enum=False):
except (AttributeError, exceptions.InferenceError) as exc:
raise UseInferenceDefault from exc
+ if not enum:
+ # namedtuple maps sys.intern(str()) over over field_names
+ attributes = [str(attr) for attr in attributes]
+ # XXX this should succeed *unless* __str__/__repr__ is incorrect or throws
+ # in which case we should not have inferred these values and raised earlier
attributes = [attr for attr in attributes if " " not in attr]
# If we can't infer the name of the class, don't crash, up to this point
@@ -185,8 +192,12 @@ def infer_named_tuple(node, context=None):
except InferenceError:
rename = False
- if rename:
- attributes = _get_renamed_namedtuple_attributes(attributes)
+ try:
+ attributes = _check_namedtuple_attributes(name, attributes, rename)
+ except AstroidTypeError as exc:
+ raise UseInferenceDefault("TypeError: " + str(exc)) from exc
+ except AstroidValueError as exc:
+ raise UseInferenceDefault("ValueError: " + str(exc)) from exc
replace_args = ", ".join(f"{arg}=None" for arg in attributes)
field_def = (
@@ -247,6 +258,39 @@ def _get_renamed_namedtuple_attributes(field_names):
return tuple(names)
+def _check_namedtuple_attributes(typename, attributes, rename=False):
+ attributes = tuple(attributes)
+ if rename:
+ attributes = _get_renamed_namedtuple_attributes(attributes)
+
+ # The following snippet is derived from the CPython Lib/collections/__init__.py sources
+ # <snippet>
+ for name in (typename,) + attributes:
+ if not isinstance(name, str):
+ raise AstroidTypeError("Type names and field names must be strings")
+ if not name.isidentifier():
+ raise AstroidValueError(
+ "Type names and field names must be valid" + f"identifiers: {name!r}"
+ )
+ if keyword.iskeyword(name):
+ raise AstroidValueError(
+ f"Type names and field names cannot be a keyword: {name!r}"
+ )
+
+ seen = set()
+ for name in attributes:
+ if name.startswith("_") and not rename:
+ raise AstroidValueError(
+ f"Field names cannot start with an underscore: {name!r}"
+ )
+ if name in seen:
+ raise AstroidValueError(f"Encountered duplicate field name: {name!r}")
+ seen.add(name)
+ # </snippet>
+
+ return attributes
+
+
def infer_enum(node, context=None):
"""Specific inference function for enum Call node."""
enum_meta = extract_node(
diff --git a/astroid/exceptions.py b/astroid/exceptions.py
index df33b571..a20bf47a 100644
--- a/astroid/exceptions.py
+++ b/astroid/exceptions.py
@@ -214,6 +214,10 @@ class AstroidTypeError(AstroidError):
"""Raised when a TypeError would be expected in Python code."""
+class AstroidValueError(AstroidError):
+ """Raised when a ValueError would be expected in Python code."""
+
+
class InferenceOverwriteError(AstroidError):
"""Raised when an inference tip is overwritten