1# Licensed under the LGPL: https://www.gnu.org/licenses/old-licenses/lgpl-2.1.en.html
2# For details: https://github.com/pylint-dev/astroid/blob/main/LICENSE
3# Copyright (c) https://github.com/pylint-dev/astroid/blob/main/CONTRIBUTORS.txt
4
5"""Astroid hooks for the Python standard library."""
6
7from __future__ import annotations
8
9import functools
10import keyword
11import unicodedata
12from collections.abc import Iterator
13from textwrap import dedent
14from typing import Final
15
16from astroid import arguments, bases, nodes, util
17from astroid.builder import AstroidBuilder, _extract_single_node, extract_node
18from astroid.context import InferenceContext
19from astroid.exceptions import (
20 AstroidError,
21 AstroidTypeError,
22 AstroidValueError,
23 InferenceError,
24 MroError,
25 UseInferenceDefault,
26)
27from astroid.inference_tip import inference_tip
28from astroid.manager import AstroidManager
29from astroid.nodes.scoped_nodes.scoped_nodes import SYNTHETIC_ROOT
30
31ENUM_QNAME: Final[str] = "enum.Enum"
32TYPING_NAMEDTUPLE_QUALIFIED: Final = {
33 "typing.NamedTuple",
34 "typing_extensions.NamedTuple",
35}
36TYPING_NAMEDTUPLE_BASENAMES: Final = {
37 "NamedTuple",
38 "typing.NamedTuple",
39 "typing_extensions.NamedTuple",
40}
41# The class ``typing.NamedTuple`` infers to, as typeshed declares it. A subclass
42# keeps it among its ancestors, so ``self`` in a method of the subclass finds the
43# namedtuple API and the tuple methods through it. ``__new__`` builds a tuple or
44# dict whose items are unknown, where ``()`` or ``{}`` would be read as empty.
45TYPING_NAMEDTUPLE_CLASS: Final = """
46class NamedTuple(tuple):
47 _field_defaults = dict.__new__(dict)
48 _fields = tuple.__new__(tuple)
49 @classmethod
50 def _make(cls, iterable):
51 return tuple.__new__(cls, iterable)
52 def _asdict(self):
53 return dict.__new__(dict)
54 def _replace(self, **kwargs):
55 return self
56"""
57
58
59def _infer_first(node, context):
60 if isinstance(node, util.UninferableBase):
61 raise UseInferenceDefault
62 try:
63 value = next(node.infer(context=context))
64 except StopIteration as exc:
65 raise InferenceError from exc
66 if isinstance(value, util.UninferableBase):
67 raise UseInferenceDefault()
68 return value
69
70
71def _find_func_form_arguments(node, context):
72 def _extract_namedtuple_arg_or_keyword( # pylint: disable=inconsistent-return-statements
73 position, key_name=None
74 ):
75 if len(args) > position:
76 return _infer_first(args[position], context)
77 if key_name and key_name in found_keywords:
78 return _infer_first(found_keywords[key_name], context)
79
80 args = node.args
81 keywords = node.keywords
82 found_keywords = (
83 {keyword.arg: keyword.value for keyword in keywords} if keywords else {}
84 )
85
86 name = _extract_namedtuple_arg_or_keyword(position=0, key_name="typename")
87 names = _extract_namedtuple_arg_or_keyword(position=1, key_name="field_names")
88 if name and names:
89 return name.value, names
90
91 raise UseInferenceDefault()
92
93
94def infer_func_form(
95 node: nodes.Call,
96 base_type: nodes.NodeNG,
97 *,
98 parent: nodes.NodeNG,
99 context: InferenceContext | None = None,
100 enum: bool = False,
101) -> tuple[nodes.ClassDef, str, list[str]]:
102 """Specific inference function for namedtuple or Python 3 enum."""
103 # node is a Call node, class name as first argument and generated class
104 # attributes as second argument
105
106 # namedtuple or enums list of attributes can be a list of strings or a
107 # whitespace-separate string
108 try:
109 name, names = _find_func_form_arguments(node, context)
110 try:
111 attributes: list[str] = names.value.replace(",", " ").split()
112 except (AttributeError, TypeError) as exc:
113 # ``names`` is not a whitespace-separated string: it is either a
114 # container node, which has no ``value`` (AttributeError), or a
115 # constant of another type such as bytes (TypeError).
116
117 # Handle attributes of NamedTuples
118 if not enum:
119 attributes = []
120 fields = _get_namedtuple_fields(node)
121 if fields:
122 fields_node = extract_node(fields)
123 attributes = [
124 _infer_first(const, context).value for const in fields_node.elts
125 ]
126
127 # Handle attributes of Enums
128 else:
129 # Enums supports either iterator of (name, value) pairs
130 # or mappings.
131 if hasattr(names, "items") and isinstance(names.items, list):
132 attributes = [
133 _infer_first(const[0], context).value
134 for const in names.items
135 if isinstance(const[0], nodes.Const)
136 ]
137 elif hasattr(names, "elts"):
138 # Enums can support either ["a", "b", "c"]
139 # or [("a", 1), ("b", 2), ...], but they can't
140 # be mixed.
141 if all(isinstance(const, nodes.Tuple) for const in names.elts):
142 attributes = [
143 _infer_first(const.elts[0], context).value
144 for const in names.elts
145 if const.elts
146 ]
147 else:
148 attributes = [
149 _infer_first(const, context).value for const in names.elts
150 ]
151 else:
152 raise AttributeError from exc
153 if not attributes:
154 raise AttributeError from exc
155 except (AttributeError, InferenceError) as exc:
156 raise UseInferenceDefault from exc
157
158 if not enum:
159 # namedtuple maps sys.intern(str()) over over field_names
160 attributes = [str(attr) for attr in attributes]
161 # XXX this should succeed *unless* __str__/__repr__ is incorrect or throws
162 # in which case we should not have inferred these values and raised earlier
163 if any(not isinstance(attr, str) for attr in attributes):
164 # Enum members must be named by strings; a non-string attribute (e.g.
165 # ``Enum("e", (1,))``) means the definition is invalid, so fall back to
166 # the default inference instead of crashing.
167 raise UseInferenceDefault
168 if enum and not isinstance(name, str):
169 # Enum class names must be strings; inferring a class with any other
170 # name can make consumers crash when they perform string operations.
171 raise UseInferenceDefault
172 attributes = [attr for attr in attributes if " " not in attr]
173
174 # If we can't infer the name of the class, don't crash, up to this point
175 # we know it is a namedtuple anyway.
176 name = name or "Uninferable"
177 # we want to return a Class node instance with proper attributes set
178 class_node = nodes.ClassDef(
179 name,
180 lineno=node.lineno,
181 col_offset=node.col_offset,
182 end_lineno=node.end_lineno,
183 end_col_offset=node.end_col_offset,
184 parent=parent,
185 )
186 class_node.postinit(
187 bases=[base_type],
188 body=[],
189 decorators=None,
190 )
191 # XXX add __init__(*attributes) method
192 for attr in attributes:
193 fake_node = nodes.EmptyNode()
194 fake_node.parent = class_node
195 fake_node.attrname = attr
196 class_node.instance_attrs[attr] = [fake_node]
197 return class_node, name, attributes
198
199
200def _has_namedtuple_base(node: nodes.ClassDef) -> bool:
201 """Predicate for class inference tip."""
202 return bool(set(node.basenames) & TYPING_NAMEDTUPLE_BASENAMES)
203
204
205def _looks_like(node, name) -> bool:
206 func = node.func
207 if isinstance(func, nodes.Attribute):
208 return func.attrname == name
209 if isinstance(func, nodes.Name):
210 return func.name == name
211 return False
212
213
214_looks_like_namedtuple = functools.partial(_looks_like, name="namedtuple")
215_looks_like_enum = functools.partial(_looks_like, name="Enum")
216_looks_like_typing_namedtuple = functools.partial(_looks_like, name="NamedTuple")
217
218
219def infer_named_tuple(
220 node: nodes.Call, context: InferenceContext | None = None
221) -> Iterator[nodes.ClassDef]:
222 """Specific inference function for namedtuple Call node."""
223 tuple_base: nodes.Name = _extract_single_node("tuple")
224 class_node, name, attributes = infer_func_form(
225 node, tuple_base, parent=SYNTHETIC_ROOT, context=context
226 )
227
228 call_site = arguments.CallSite.from_call(node, context=context)
229 func = util.safe_infer(
230 _extract_single_node("import collections; collections.namedtuple")
231 )
232 # Without the factory signature ``rename=`` cannot be bound: assume the
233 # default rather than throwing the whole namedtuple away.
234 rename = False
235 if isinstance(func, nodes.NodeNG):
236 try:
237 rename_arg_bool_value = next(
238 call_site.infer_argument(func, "rename", context or InferenceContext())
239 ).bool_value()
240 rename = rename_arg_bool_value is True
241 except (InferenceError, StopIteration):
242 pass
243
244 try:
245 attributes = _check_namedtuple_attributes(name, attributes, rename)
246 except AstroidTypeError as exc:
247 raise UseInferenceDefault("TypeError: " + str(exc)) from exc
248 except AstroidValueError as exc:
249 raise UseInferenceDefault("ValueError: " + str(exc)) from exc
250
251 if tuple(class_node.instance_attrs) != tuple(attributes):
252 # ``infer_func_form`` recorded the field names as written, but ``rename=True``
253 # replaces invalid, keyword or duplicate names with ``_N``, so the instance
254 # would otherwise carry names the namedtuple does not actually have (and lose
255 # the duplicated ones entirely). Rebuild them from the renamed fields.
256 class_node.instance_attrs.clear()
257 for attr in attributes:
258 fake_node = nodes.EmptyNode()
259 fake_node.parent = class_node
260 fake_node.attrname = attr
261 class_node.instance_attrs[attr] = [fake_node]
262
263 replace_args = ", ".join(f"{arg}=None" for arg in attributes)
264 field_def = (
265 " {name} = property(lambda self: self[{index:d}], "
266 "doc='Alias for field number {index:d}')"
267 )
268 field_defs = "\n".join(
269 field_def.format(name=name, index=index)
270 for index, name in enumerate(attributes)
271 )
272 fake = AstroidBuilder(AstroidManager()).string_build(f"""
273class {name}(tuple):
274 __slots__ = ()
275 _fields = {attributes!r}
276 def _asdict(self):
277 return self.__dict__
278 @classmethod
279 def _make(cls, iterable, new=tuple.__new__, len=len):
280 return new(cls, iterable)
281 def _replace(self, {replace_args}):
282 return self
283 def __getnewargs__(self):
284 return tuple(self)
285{field_defs}
286 """)
287 class_node.locals["_asdict"] = fake.body[0].locals["_asdict"]
288 class_node.locals["_make"] = fake.body[0].locals["_make"]
289 class_node.locals["_replace"] = fake.body[0].locals["_replace"]
290 class_node.locals["_fields"] = fake.body[0].locals["_fields"]
291 for attr in attributes:
292 # Python normalises identifiers to NFKC, so a field named "\u00b5" (MICRO SIGN)
293 # is stored by the parser as "\u03bc" (GREEK SMALL LETTER MU). Looking the
294 # attribute up under the name as written raises KeyError on a definition
295 # namedtuple itself accepts, so use the name the parser actually used.
296 normalized = unicodedata.normalize("NFKC", attr)
297 class_node.locals[normalized] = fake.body[0].locals[normalized]
298 # we use UseInferenceDefault, we can't be a generator so return an iterator
299 return iter([class_node])
300
301
302def _get_renamed_namedtuple_attributes(field_names):
303 names = list(field_names)
304 seen = set()
305 for i, name in enumerate(field_names):
306 # pylint: disable = too-many-boolean-expressions
307 if (
308 not all(c.isalnum() or c == "_" for c in name)
309 or keyword.iskeyword(name)
310 or not name
311 or name[0].isdigit()
312 or name.startswith("_")
313 or name in seen
314 ):
315 names[i] = f"_{i}"
316 seen.add(name)
317 return tuple(names)
318
319
320def _check_namedtuple_attributes(typename, attributes, rename=False):
321 attributes = tuple(attributes)
322 if rename:
323 attributes = _get_renamed_namedtuple_attributes(attributes)
324
325 # The following snippet is derived from the CPython Lib/collections/__init__.py sources
326 # <snippet>
327 for name in (typename, *attributes):
328 if not isinstance(name, str):
329 raise AstroidTypeError(
330 f"Type names and field names must be strings, not {type(name)!r}"
331 )
332 if not name.isidentifier():
333 raise AstroidValueError(
334 "Type names and field names must be valid" + f"identifiers: {name!r}"
335 )
336 if keyword.iskeyword(name):
337 raise AstroidValueError(
338 f"Type names and field names cannot be a keyword: {name!r}"
339 )
340
341 seen = set()
342 for name in attributes:
343 if name.startswith("_") and not rename:
344 raise AstroidValueError(
345 f"Field names cannot start with an underscore: {name!r}"
346 )
347 if name in seen:
348 raise AstroidValueError(f"Encountered duplicate field name: {name!r}")
349 seen.add(name)
350 # </snippet>
351
352 return attributes
353
354
355def infer_enum(
356 node: nodes.Call, context: InferenceContext | None = None
357) -> Iterator[bases.Instance]:
358 """Specific inference function for enum Call node."""
359 # Raise `UseInferenceDefault` if `node` is a call to a a user-defined Enum.
360 try:
361 inferred = node.func.infer(context)
362 except (InferenceError, StopIteration) as exc:
363 raise UseInferenceDefault from exc
364
365 if not any(
366 isinstance(item, nodes.ClassDef) and item.qname() == ENUM_QNAME
367 for item in inferred
368 ):
369 raise UseInferenceDefault
370
371 enum_meta = _extract_single_node("""
372 class EnumMeta(object):
373 'docstring'
374 def __call__(self, node):
375 class EnumAttribute(object):
376 name = ''
377 value = 0
378 return EnumAttribute()
379 def __iter__(self):
380 class EnumAttribute(object):
381 name = ''
382 value = 0
383 return [EnumAttribute()]
384 def __reversed__(self):
385 class EnumAttribute(object):
386 name = ''
387 value = 0
388 return (EnumAttribute, )
389 def __next__(self):
390 return next(iter(self))
391 def __getitem__(self, attr):
392 class Value(object):
393 @property
394 def name(self):
395 return ''
396 @property
397 def value(self):
398 return attr
399
400 return Value()
401 __members__ = ['']
402 """)
403
404 # FIXME arguably, the base here shouldn't be the EnumMeta class definition
405 # itself, but a reference (Name) to it. Otherwise, the invariant that all
406 # children of a node have that node as their parent is broken.
407 class_node = infer_func_form(
408 node,
409 enum_meta,
410 parent=SYNTHETIC_ROOT,
411 context=context,
412 enum=True,
413 )[0]
414 return iter([class_node.instantiate_class()])
415
416
417INT_FLAG_ADDITION_METHODS = """
418 def __or__(self, other):
419 return {name}(self.value | other.value)
420 def __and__(self, other):
421 return {name}(self.value & other.value)
422 def __xor__(self, other):
423 return {name}(self.value ^ other.value)
424 def __add__(self, other):
425 return {name}(self.value + other.value)
426 def __div__(self, other):
427 return {name}(self.value / other.value)
428 def __invert__(self):
429 return {name}(~self.value)
430 def __mul__(self, other):
431 return {name}(self.value * other.value)
432"""
433
434
435def _binds_descriptor(stmt: nodes.Import | nodes.ImportFrom, name: str) -> bool:
436 """Return whether ``name``, bound by the import ``stmt``, is a descriptor.
437
438 ``Enum`` keeps a descriptor, such as a function or a class defining
439 ``__get__``, as a plain attribute rather than turning it into a member.
440 """
441 context = InferenceContext()
442 context.lookupname = name
443 inferred = util.safe_infer(stmt, context)
444 if isinstance(inferred, (nodes.FunctionDef, nodes.Lambda)):
445 return True
446 if not isinstance(inferred, nodes.ClassDef):
447 return False
448 return any(
449 method in klass.locals
450 for klass in (inferred, *inferred.ancestors())
451 for method in ("__get__", "__set__", "__delete__")
452 )
453
454
455def infer_enum_class(node: nodes.ClassDef) -> nodes.ClassDef:
456 """Specific inference for enums."""
457 try:
458 mro = node.mro()
459 except MroError:
460 # A malformed class hierarchy (e.g. duplicate bases) has no resolvable
461 # MRO; leave the node untransformed rather than crashing.
462 return node
463 for basename in (b for cls in mro for b in cls.basenames):
464 if node.root().name == "enum":
465 # Skip if the class is directly from enum module.
466 break
467 dunder_members = {}
468 target_names = set()
469 for local, values in node.locals.items():
470 if local == "_ignore_":
471 continue
472
473 stmt = values[0].statement()
474 import_stmt = ""
475 if all(
476 isinstance(value, (nodes.Import, nodes.ImportFrom)) for value in values
477 ):
478 # A name bound by an import in the class body is a member,
479 # just like a name bound by an assignment. Its value is
480 # whatever the import binds, so replay the import when
481 # inferring ``value``.
482 if _binds_descriptor(stmt, local):
483 continue
484 import_stmt = stmt.as_string()
485 targets = [
486 nodes.AssignName(
487 local,
488 lineno=stmt.lineno,
489 col_offset=stmt.col_offset,
490 parent=stmt.parent,
491 end_lineno=stmt.end_lineno,
492 end_col_offset=stmt.end_col_offset,
493 )
494 ]
495 elif any(not isinstance(value, nodes.AssignName) for value in values):
496 continue
497 elif isinstance(stmt, nodes.Assign):
498 if isinstance(stmt.targets[0], nodes.Tuple):
499 targets = stmt.targets[0].itered()
500 else:
501 targets = stmt.targets
502 elif isinstance(stmt, nodes.AnnAssign):
503 targets = [stmt.target]
504 else:
505 continue
506
507 inferred_return_value = None
508 if import_stmt:
509 inferred_return_value = local
510 elif stmt.value is not None:
511 inferred_return_value = stmt.value.as_string()
512
513 new_targets = []
514 for target in targets:
515 if not isinstance(target, nodes.AssignName):
516 # ``Starred`` targets, and attribute/subscript targets from a
517 # chained assignment such as ``x = a.b = 1``, do not name an
518 # enum member and have no ``name`` attribute.
519 continue
520 target_names.add(target.name)
521 # Replace all the assignments with our mocked class.
522 classdef = dedent(
523 """
524 class {name}({types}):
525 @property
526 def value(self):
527 {import_stmt}
528 return {return_value}
529 @property
530 def _value_(self):
531 {import_stmt}
532 return {return_value}
533 @property
534 def name(self):
535 return "{name}"
536 @property
537 def _name_(self):
538 return "{name}"
539 """.format(
540 name=target.name,
541 types=", ".join(node.basenames),
542 return_value=inferred_return_value,
543 import_stmt=import_stmt,
544 )
545 )
546 if "IntFlag" in basename:
547 # Alright, we need to add some additional methods.
548 # Unfortunately we still can't infer the resulting objects as
549 # Enum members, but once we'll be able to do that, the following
550 # should result in some nice symbolic execution
551 classdef += INT_FLAG_ADDITION_METHODS.format(name=target.name)
552
553 fake = AstroidBuilder(
554 AstroidManager(), apply_transforms=False
555 ).string_build(classdef)[target.name]
556 fake.parent = target.parent
557 for method in node.mymethods():
558 fake.locals[method.name] = [method]
559 new_targets.append(fake.instantiate_class())
560 if not import_stmt and stmt.value is None:
561 continue
562 dunder_members[local] = fake
563 node.locals[local] = new_targets
564
565 # The undocumented `_value2member_map_` member:
566 node.locals["_value2member_map_"] = [
567 nodes.Dict(
568 parent=node,
569 lineno=node.lineno,
570 col_offset=node.col_offset,
571 end_lineno=node.end_lineno,
572 end_col_offset=node.end_col_offset,
573 )
574 ]
575
576 members = nodes.Dict(
577 parent=node,
578 lineno=node.lineno,
579 col_offset=node.col_offset,
580 end_lineno=node.end_lineno,
581 end_col_offset=node.end_col_offset,
582 )
583 members.postinit(
584 [
585 (
586 nodes.Const(k, parent=members),
587 nodes.Name(
588 v.name,
589 parent=members,
590 lineno=v.lineno,
591 col_offset=v.col_offset,
592 end_lineno=v.end_lineno,
593 end_col_offset=v.end_col_offset,
594 ),
595 )
596 for k, v in dunder_members.items()
597 ]
598 )
599 node.locals["__members__"] = [members]
600 # The enum.Enum class itself defines two @DynamicClassAttribute data-descriptors
601 # "name" and "value" (which we override in the mocked class for each enum member
602 # above). When dealing with inference of an arbitrary instance of the enum
603 # class, e.g. in a method defined in the class body like:
604 # class SomeEnum(enum.Enum):
605 # def method(self):
606 # self.name # <- here
607 # In the absence of an enum member called "name" or "value", these attributes
608 # should resolve to the descriptor on that particular instance, i.e. enum member.
609 # For "value", we have no idea what that should be, but for "name", we at least
610 # know that it should be a string, so infer that as a guess.
611 if "name" not in target_names:
612 code = dedent('''
613 @property
614 def name(self):
615 """The name of the Enum member.
616
617 This is a reconstruction by astroid: enums are too dynamic to understand, but we at least
618 know 'name' should be a string, so this is astroid's best guess.
619 """
620 return ''
621 ''')
622 name_dynamicclassattr = AstroidBuilder(AstroidManager()).string_build(code)[
623 "name"
624 ]
625 node.locals["name"] = [name_dynamicclassattr]
626 break
627 return node
628
629
630def infer_typing_namedtuple_class(class_node, context: InferenceContext | None = None):
631 """Infer a subclass of typing.NamedTuple."""
632 # Check if it has the corresponding bases
633 annassigns_fields = [
634 annassign.target.name
635 for annassign in class_node.body
636 if isinstance(annassign, nodes.AnnAssign)
637 and isinstance(annassign.target, nodes.AssignName)
638 ]
639 code = dedent("""
640 from collections import namedtuple
641 namedtuple({typename!r}, {fields!r})
642 """).format(typename=class_node.name, fields=",".join(annassigns_fields))
643 node = extract_node(code)
644 try:
645 generated_class_node = next(infer_named_tuple(node, context))
646 except StopIteration as e:
647 raise InferenceError(node=node, context=context) from e
648 for method in class_node.mymethods():
649 generated_class_node.locals[method.name] = [method]
650
651 for body_node in class_node.body:
652 if isinstance(body_node, nodes.Assign):
653 for target in body_node.targets:
654 # A target is not necessarily a single name: ``cat.color = ...``
655 # and ``basket[0] = ...`` define no class attribute at all, while
656 # ``apple, banana = ...`` defines one per unpacked element.
657 for assign_name in target.nodes_of_class(nodes.AssignName):
658 attr = assign_name.name
659 generated_class_node.locals[attr] = class_node.locals[attr]
660 elif isinstance(body_node, nodes.ClassDef):
661 generated_class_node.locals[body_node.name] = [body_node]
662
663 return iter((generated_class_node,))
664
665
666def infer_typing_namedtuple_function(node, context: InferenceContext | None = None):
667 """
668 Starting with python3.9, NamedTuple is a function of the typing module.
669 The class NamedTuple is build dynamically through a call to `type` during
670 initialization of the `_NamedTuple` variable, which
671 `_typing_namedtuple_transform` replaces with the class typeshed declares.
672 """
673 klass = extract_node("""
674 from typing import _NamedTuple
675 _NamedTuple
676 """)
677 return klass.infer(context)
678
679
680def _typing_namedtuple_transform(node: nodes.Module) -> nodes.Module:
681 """Define ``typing._NamedTuple`` as the class typeshed declares for NamedTuple.
682
683 At runtime it is an empty class, whose metaclass builds a namedtuple from
684 the subclass. Astroid keeps the subclass as written instead, so the class
685 has to provide the namedtuple API and the tuple base for it.
686 """
687 class_node = _extract_single_node(TYPING_NAMEDTUPLE_CLASS)
688 class_node.parent = node
689 node.locals["_NamedTuple"] = [class_node]
690 # The transform visitor stops at a transform that returns None, which would
691 # skip the ones registered after this one, such as the typing module
692 # extender of brain_typing.
693 return node
694
695
696def infer_typing_namedtuple(
697 node: nodes.Call, context: InferenceContext | None = None
698) -> Iterator[nodes.ClassDef]:
699 """Infer a typing.NamedTuple(...) call."""
700 # This is essentially a namedtuple with different arguments
701 # so we extract the args and infer a named tuple.
702 try:
703 func = next(node.func.infer())
704 except (InferenceError, StopIteration) as exc:
705 raise UseInferenceDefault from exc
706
707 if func.qname() not in TYPING_NAMEDTUPLE_QUALIFIED:
708 raise UseInferenceDefault
709
710 if len(node.args) != 2:
711 raise UseInferenceDefault
712
713 if not isinstance(node.args[1], (nodes.List, nodes.Tuple)):
714 raise UseInferenceDefault
715
716 return infer_named_tuple(node, context)
717
718
719def _get_namedtuple_fields(node: nodes.Call) -> str:
720 """Get and return fields of a NamedTuple in code-as-a-string.
721
722 Because the fields are represented in their code form we can
723 extract a node from them later on.
724 """
725 names = []
726 container = None
727 try:
728 container = next(node.args[1].infer())
729 except (InferenceError, StopIteration) as exc:
730 raise UseInferenceDefault from exc
731 # We pass on IndexError as we'll try to infer 'field_names' from the keywords
732 except IndexError:
733 pass
734 if not container:
735 for keyword_node in node.keywords:
736 if keyword_node.arg == "field_names":
737 try:
738 container = next(keyword_node.value.infer())
739 except (InferenceError, StopIteration) as exc:
740 raise UseInferenceDefault from exc
741 break
742 if not isinstance(container, nodes.BaseContainer):
743 raise UseInferenceDefault
744 for elt in container.elts:
745 if isinstance(elt, nodes.Const):
746 names.append(elt.as_string())
747 continue
748 if not isinstance(elt, (nodes.List, nodes.Tuple)):
749 raise UseInferenceDefault
750 if len(elt.elts) != 2:
751 raise UseInferenceDefault
752 names.append(elt.elts[0].as_string())
753
754 if names:
755 field_names = f"({','.join(names)},)"
756 else:
757 field_names = ""
758 return field_names
759
760
761def _is_enum_subclass(cls: nodes.ClassDef) -> bool:
762 """Return whether cls is a subclass of an Enum."""
763 try:
764 return cls.is_subtype_of("enum.Enum")
765 except AstroidError:
766 return False
767
768
769def register(manager: AstroidManager) -> None:
770 manager.register_transform(
771 nodes.Call, inference_tip(infer_named_tuple), _looks_like_namedtuple
772 )
773 manager.register_transform(nodes.Call, inference_tip(infer_enum), _looks_like_enum)
774 manager.register_transform(
775 nodes.ClassDef, infer_enum_class, predicate=_is_enum_subclass
776 )
777 manager.register_transform(
778 nodes.ClassDef,
779 inference_tip(infer_typing_namedtuple_class),
780 _has_namedtuple_base,
781 )
782 manager.register_transform(
783 nodes.FunctionDef,
784 inference_tip(infer_typing_namedtuple_function),
785 lambda node: node.name == "NamedTuple"
786 and getattr(node.root(), "name", None) == "typing",
787 )
788 manager.register_transform(
789 nodes.Module,
790 _typing_namedtuple_transform,
791 lambda node: node.name == "typing",
792 )
793 manager.register_transform(
794 nodes.Call,
795 inference_tip(infer_typing_namedtuple),
796 _looks_like_typing_namedtuple,
797 )