11
11
import sys
12
12
import typing
13
13
import warnings
14
- from collections .abc import Generator
14
+ from collections .abc import Generator , Iterable , Mapping
15
15
from functools import lru_cache
16
16
from typing import TYPE_CHECKING , Any , Callable , ClassVar , Optional , TypeVar , Union
17
17
@@ -5375,6 +5375,32 @@ def postinit(self, *, patterns: list[Pattern]) -> None:
5375
5375
}
5376
5376
5377
5377
5378
+ def _create_basic_elements (
5379
+ value : Iterable [Any ], node : List | Set | Tuple
5380
+ ) -> list [NodeNG ]:
5381
+ """Create a list of nodes to function as the elements of a new node."""
5382
+ elements : list [NodeNG ] = []
5383
+ for element in value :
5384
+ element_node = const_factory (element )
5385
+ element_node .parent = node
5386
+ elements .append (element_node )
5387
+ return elements
5388
+
5389
+
5390
+ def _create_dict_items (
5391
+ values : Mapping [Any , Any ], node : Dict
5392
+ ) -> list [tuple [SuccessfulInferenceResult , SuccessfulInferenceResult ]]:
5393
+ """Create a list of node pairs to function as the items of a new dict node."""
5394
+ elements : list [tuple [SuccessfulInferenceResult , SuccessfulInferenceResult ]] = []
5395
+ for key , value in values .items ():
5396
+ key_node = const_factory (key )
5397
+ key_node .parent = node
5398
+ value_node = const_factory (value )
5399
+ value_node .parent = node
5400
+ elements .append ((key_node , value_node ))
5401
+ return elements
5402
+
5403
+
5378
5404
def const_factory (value : Any ) -> List | Set | Tuple | Dict | Const | EmptyNode :
5379
5405
"""Return an astroid node for a python value."""
5380
5406
assert not isinstance (value , NodeNG )
@@ -5387,13 +5413,14 @@ def const_factory(value: Any) -> List | Set | Tuple | Dict | Const | EmptyNode:
5387
5413
node .object = value
5388
5414
return node
5389
5415
5390
- # TODO: We pass an empty list as elements for a sequence
5391
- # or a mapping, in order to avoid transforming
5392
- # each element to an AST. This is fixed in 2.0
5393
- # and this approach is a temporary hack.
5416
+ instance : List | Set | Tuple | Dict
5394
5417
initializer_cls = CONST_CLS [value .__class__ ]
5395
- if issubclass (initializer_cls , (Dict , List , Set , Tuple )):
5418
+ if issubclass (initializer_cls , (List , Set , Tuple )):
5419
+ instance = initializer_cls ()
5420
+ instance .postinit (_create_basic_elements (value , instance ))
5421
+ return instance
5422
+ if issubclass (initializer_cls , Dict ):
5396
5423
instance = initializer_cls ()
5397
- instance .postinit ([] )
5424
+ instance .postinit (_create_dict_items ( value , instance ) )
5398
5425
return instance
5399
5426
return Const (value )
0 commit comments