def test_async_comprehensions(self): async_comprehensions = [ extract_node("async def f(): return __([i async for i in aiter() if i % 2])"), extract_node("async def f(): return __({i async for i in aiter() if i % 2})"), extract_node("async def f(): return __((i async for i in aiter() if i % 2))"), extract_node("async def f(): return __({i: i async for i in aiter() if i % 2})") ] non_async_comprehensions = [ extract_node("async def f(): return __({i: i for i in iter() if i % 2})") ] for comp in async_comprehensions: self.assertTrue(comp.generators[0].is_async) for comp in non_async_comprehensions: self.assertFalse(comp.generators[0].is_async)
def test_super_data_model(self): ast_nodes = builder.extract_node(''' class X(object): pass class A(X): def __init__(self): super(A, self) #@ super(A, A) #@ super(X, A) #@ ''') first = next(ast_nodes[0].infer()) thisclass = first.getattr('__thisclass__')[0] self.assertIsInstance(thisclass, nodes.ClassDef) self.assertEqual(thisclass.name, 'A') selfclass = first.getattr('__self_class__')[0] self.assertIsInstance(selfclass, nodes.ClassDef) self.assertEqual(selfclass.name, 'A') self_ = first.getattr('__self__')[0] self.assertIsInstance(self_, bases.Instance) self.assertEqual(self_.name, 'A') cls = first.getattr('__class__')[0] self.assertEqual(cls, first._proxied) second = next(ast_nodes[1].infer()) thisclass = second.getattr('__thisclass__')[0] self.assertEqual(thisclass.name, 'A') self_ = second.getattr('__self__')[0] self.assertIsInstance(self_, nodes.ClassDef) self.assertEqual(self_.name, 'A') third = next(ast_nodes[2].infer()) thisclass = third.getattr('__thisclass__')[0] self.assertEqual(thisclass.name, 'X') selfclass = third.getattr('__self_class__')[0] self.assertEqual(selfclass.name, 'A')
def _inferred_queue_instance(self): node = builder.extract_node(""" import collections q = collections.deque([]) q """) return next(node.infer())
def test__path__not_a_package(self): ast_node = builder.extract_node(''' import sys sys.__path__ #@ ''') with self.assertRaises(exceptions.InferenceError): next(ast_node.infer())
def test_model(self): ast_nodes = builder.extract_node(''' def test(): "a" yield gen = test() gen.__name__ #@ gen.__doc__ #@ gen.gi_code #@ gen.gi_frame #@ gen.send #@ ''') name = next(ast_nodes[0].infer()) self.assertEqual(name.value, 'test') doc = next(ast_nodes[1].infer()) self.assertEqual(doc.value, 'a') gi_code = next(ast_nodes[2].infer()) self.assertIsInstance(gi_code, astroid.ClassDef) self.assertEqual(gi_code.name, 'gi_code') gi_frame = next(ast_nodes[3].infer()) self.assertIsInstance(gi_frame, astroid.ClassDef) self.assertEqual(gi_frame.name, 'gi_frame') send = next(ast_nodes[4].infer()) self.assertIsInstance(send, astroid.BoundMethod)
def test_inferring_invalid_supers(self): ast_nodes = builder.extract_node(''' class Super(object): def __init__(self): # MRO pointer is not a type super(1, self) #@ # MRO type is not a subtype super(Super, 1) #@ # self is not a subtype of Bupper super(Bupper, self) #@ class Bupper(Super): pass ''') first = next(ast_nodes[0].infer()) self.assertIsInstance(first, objects.Super) with self.assertRaises(exceptions.SuperError) as cm: first.super_mro() self.assertIsInstance(cm.exception.super_.mro_pointer, nodes.Const) self.assertEqual(cm.exception.super_.mro_pointer.value, 1) for node, invalid_type in zip(ast_nodes[1:], (nodes.Const, bases.Instance)): inferred = next(node.infer()) self.assertIsInstance(inferred, objects.Super, node) with self.assertRaises(exceptions.SuperError) as cm: inferred.super_mro() self.assertIsInstance(cm.exception.super_.type, invalid_type)
def test_ssl_protocol(self): node = extract_node(''' import ssl ssl.PROTOCOL_TLSv1 ''') inferred = next(node.infer()) self.assertIsInstance(inferred, nodes.Const)
def test_unbound_method_model(self): ast_nodes = builder.extract_node(''' class A: def test(self): pass t = A.test t.__class__ #@ t.__func__ #@ t.__self__ #@ t.im_class #@ t.im_func #@ t.im_self #@ ''') cls = next(ast_nodes[0].infer()) self.assertIsInstance(cls, astroid.ClassDef) if six.PY2: unbound = BUILTINS.locals[types.MethodType.__name__][0] else: unbound = BUILTINS.locals[types.FunctionType.__name__][0] self.assertEqual(cls.name, unbound.name) func = next(ast_nodes[1].infer()) self.assertIsInstance(func, astroid.FunctionDef) self.assertEqual(func.name, 'test') self_ = next(ast_nodes[2].infer()) self.assertIsInstance(self_, astroid.Const) self.assertIsNone(self_.value) self.assertEqual(cls.name, next(ast_nodes[3].infer()).name) self.assertEqual(func, next(ast_nodes[4].infer())) self.assertIsNone(next(ast_nodes[5].infer()).value)
def infer_enum(node, context=None): """ Specific inference function for enum Call node. """ enum_meta = extract_node(''' class EnumMeta(object): 'docstring' def __call__(self, node): class EnumAttribute(object): name = '' value = 0 return EnumAttribute() def __iter__(self): class EnumAttribute(object): name = '' value = 0 return [EnumAttribute()] def __next__(self): return next(iter(self)) def __getitem__(self, attr): class Value(object): @property def name(self): return '' @property def value(self): return attr return Value() __members__ = [''] ''') class_node = infer_func_form(node, enum_meta, context=context, enum=True)[0] return iter([class_node.instantiate_class()])
def test_not_implemented(self): node = builder.extract_node(''' NotImplemented #@ ''') inferred = next(node.infer()) self.assertIsInstance(inferred, nodes.Const) self.assertEqual(inferred.value, NotImplemented)
def test_unpacking_in_dicts(self): code = "{'x': 1, **{'y': 2}}" node = extract_node(code) self.assertEqual(node.as_string(), code) keys = [key for (key, _) in node.items] self.assertIsInstance(keys[0], nodes.Const) self.assertIsInstance(keys[1], nodes.DictUnpack)
def test_numpy(self): node = builder.extract_node(''' import numpy numpy.ones #@ ''') inferred = next(node.infer()) self.assertIsInstance(inferred, nodes.FunctionDef)
def _test_lock_object(self, object_name): lock_instance = builder.extract_node(""" import threading threading.{0}() """.format(object_name)) inferred = next(lock_instance.infer()) self.assert_is_valid_lock(inferred)
def test_instance_special_model(self): ast_nodes = builder.extract_node(''' class A: "test" def __init__(self): self.a = 42 a = A() a.__class__ #@ a.__module__ #@ a.__doc__ #@ a.__dict__ #@ ''', module_name='collections') cls = next(ast_nodes[0].infer()) self.assertIsInstance(cls, astroid.ClassDef) self.assertEqual(cls.name, 'A') module = next(ast_nodes[1].infer()) self.assertIsInstance(module, astroid.Const) self.assertEqual(module.value, 'collections') doc = next(ast_nodes[2].infer()) self.assertIsInstance(doc, astroid.Const) self.assertEqual(doc.value, 'test') dunder_dict = next(ast_nodes[3].infer()) self.assertIsInstance(dunder_dict, astroid.Dict) attr = next(dunder_dict.getitem('a').infer()) self.assertIsInstance(attr, astroid.Const) self.assertEqual(attr.value, 42)
def test_function_model_for_python2(self): ast_nodes = builder.extract_node(''' def test(a=1): "a" test.func_name #@ test.func_doc #@ test.func_dict #@ test.func_globals #@ test.func_defaults #@ test.func_code #@ test.func_closure #@ ''') name = next(ast_nodes[0].infer()) self.assertIsInstance(name, astroid.Const) self.assertEqual(name.value, 'test') doc = next(ast_nodes[1].infer()) self.assertIsInstance(doc, astroid.Const) self.assertEqual(doc.value, 'a') pydict = next(ast_nodes[2].infer()) self.assertIsInstance(pydict, astroid.Dict) pyglobals = next(ast_nodes[3].infer()) self.assertIsInstance(pyglobals, astroid.Dict) defaults = next(ast_nodes[4].infer()) self.assertIsInstance(defaults, astroid.Tuple) for node in ast_nodes[5:]: self.assertIs(next(node.infer()), astroid.Uninferable)
def test_super_complex_mro(self): ast_nodes = builder.extract_node(''' class A(object): def spam(self): return "A" def foo(self): return "A" @staticmethod def static(self): pass class B(A): def boo(self): return "B" def spam(self): return "B" class C(A): def boo(self): return "C" class E(C, B): def __init__(self): super(E, self).boo #@ super(C, self).boo #@ super(E, self).spam #@ super(E, self).foo #@ super(E, self).static #@ ''') first = next(ast_nodes[0].infer()) self.assertIsInstance(first, bases.BoundMethod) self.assertEqual(first.bound.name, 'C') second = next(ast_nodes[1].infer()) self.assertIsInstance(second, bases.BoundMethod) self.assertEqual(second.bound.name, 'B') third = next(ast_nodes[2].infer()) self.assertIsInstance(third, bases.BoundMethod) self.assertEqual(third.bound.name, 'B') fourth = next(ast_nodes[3].infer()) self.assertEqual(fourth.bound.name, 'A') static = next(ast_nodes[4].infer()) self.assertIsInstance(static, nodes.FunctionDef) self.assertEqual(static.parent.scope().name, 'A')
def test_super_mro(self): ast_nodes = builder.extract_node(''' class A(object): pass class B(A): pass class C(A): pass class E(C, B): def __init__(self): super(E, self) #@ super(C, self) #@ super(B, self) #@ super(B, 1) #@ super(1, B) #@ ''') first = next(ast_nodes[0].infer()) self.assertEqualMro(first, ['C', 'B', 'A', 'object']) second = next(ast_nodes[1].infer()) self.assertEqualMro(second, ['B', 'A', 'object']) third = next(ast_nodes[2].infer()) self.assertEqualMro(third, ['A', 'object']) fourth = next(ast_nodes[3].infer()) with self.assertRaises(exceptions.SuperError): fourth.super_mro() fifth = next(ast_nodes[4].infer()) with self.assertRaises(exceptions.SuperError): fifth.super_mro()
def test_unbound_method_model(self): ast_nodes = builder.extract_node(''' class A: def test(self): pass t = A.test t.__class__ #@ t.__func__ #@ t.__self__ #@ t.im_class #@ t.im_func #@ t.im_self #@ ''') cls = next(ast_nodes[0].infer()) self.assertIsInstance(cls, astroid.ClassDef) unbound_name = 'function' self.assertEqual(cls.name, unbound_name) func = next(ast_nodes[1].infer()) self.assertIsInstance(func, astroid.FunctionDef) self.assertEqual(func.name, 'test') self_ = next(ast_nodes[2].infer()) self.assertIsInstance(self_, astroid.Const) self.assertIsNone(self_.value) self.assertEqual(cls.name, next(ast_nodes[3].infer()).name) self.assertEqual(func, next(ast_nodes[4].infer())) self.assertIsNone(next(ast_nodes[5].infer()).value)
def test_inferring_super_outside_methods(self): ast_nodes = builder.extract_node(''' class Module(object): pass class StaticMethod(object): @staticmethod def static(): # valid, but we don't bother with it. return super(StaticMethod, StaticMethod) #@ # super outside methods aren't inferred super(Module, Module) #@ # no argument super is not recognised outside methods as well. super() #@ ''') in_static = next(ast_nodes[0].value.infer()) self.assertIsInstance(in_static, bases.Instance) self.assertEqual(in_static.qname(), "%s.super" % bases.BUILTINS) module_level = next(ast_nodes[1].infer()) self.assertIsInstance(module_level, bases.Instance) self.assertEqual(in_static.qname(), "%s.super" % bases.BUILTINS) no_arguments = next(ast_nodes[2].infer()) self.assertIsInstance(no_arguments, bases.Instance) self.assertEqual(no_arguments.qname(), "%s.super" % bases.BUILTINS)
def _inferred_ordered_dict_instance(self): node = builder.extract_node(""" import collections d = collections.OrderedDict() d """) return next(node.infer())
def test_builtin_fromlineno_missing(self): cls = builder.extract_node(''' class Foo(Exception): #@ pass ''') new = cls.getattr('__new__')[-1] self.assertEqual(new.args.fromlineno, 0)
def test_unpack_infer_empty_tuple(self): node = builder.extract_node(''' () ''') inferred = next(node.infer()) with self.assertRaises(InferenceError) as cm: unpacked = list(node_classes.unpack_infer(inferred))
def infer_typing_namedtuple(node, context=None): """Infer a typing.NamedTuple(...) call.""" # This is essentially a namedtuple with different arguments # so we extract the args and infer a named tuple. try: func = next(node.func.infer()) except InferenceError: raise UseInferenceDefault if func.qname() != 'typing.NamedTuple': raise UseInferenceDefault if len(node.args) != 2: raise UseInferenceDefault if not isinstance(node.args[1], (nodes.List, nodes.Tuple)): raise UseInferenceDefault names = [] for elt in node.args[1].elts: 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() node = extract_node('namedtuple(%(typename)s, (%(fields)s,)) ' % {'typename': typename, 'fields': ",".join(names)}) return infer_named_tuple(node, context)
def test_class_model(self): ast_nodes = builder.extract_node(''' class A(object): "test" class B(A): pass class C(A): pass A.__module__ #@ A.__name__ #@ A.__qualname__ #@ A.__doc__ #@ A.__mro__ #@ A.mro() #@ A.__bases__ #@ A.__class__ #@ A.__dict__ #@ A.__subclasses__() #@ ''', module_name='collections') module = next(ast_nodes[0].infer()) self.assertIsInstance(module, astroid.Const) self.assertEqual(module.value, 'collections') name = next(ast_nodes[1].infer()) self.assertIsInstance(name, astroid.Const) self.assertEqual(name.value, 'A') qualname = next(ast_nodes[2].infer()) self.assertIsInstance(qualname, astroid.Const) self.assertEqual(qualname.value, 'collections.A') doc = next(ast_nodes[3].infer()) self.assertIsInstance(doc, astroid.Const) self.assertEqual(doc.value, 'test') mro = next(ast_nodes[4].infer()) self.assertIsInstance(mro, astroid.Tuple) self.assertEqual([cls.name for cls in mro.elts], ['A', 'object']) called_mro = next(ast_nodes[5].infer()) self.assertEqual(called_mro.elts, mro.elts) bases = next(ast_nodes[6].infer()) self.assertIsInstance(bases, astroid.Tuple) self.assertEqual([cls.name for cls in bases.elts], ['object']) cls = next(ast_nodes[7].infer()) self.assertIsInstance(cls, astroid.ClassDef) self.assertEqual(cls.name, 'type') cls_dict = next(ast_nodes[8].infer()) self.assertIsInstance(cls_dict, astroid.Dict) subclasses = next(ast_nodes[9].infer()) self.assertIsInstance(subclasses, astroid.List) self.assertEqual([cls.name for cls in subclasses.elts], ['B', 'C'])
def test_namedtuple_few_fields(self): result = builder.extract_node(''' from typing import NamedTuple NamedTuple("A", [("a",), ("b", str), ("c", bytes)]) ''') inferred = next(result.infer()) self.assertIsInstance(inferred, astroid.Instance) self.assertEqual(inferred.qname(), "typing.NamedTuple")
def test_namedtuple_instance_attrs(self): result = builder.extract_node(''' from typing import NamedTuple NamedTuple("A", [("a", int), ("b", str), ("c", bytes)])(1, 2, 3) #@ ''') inferred = next(result.infer()) for name, attr in inferred.instance_attrs.items(): self.assertEqual(attr[0].attrname, name)
def test_namedtuple_few_args(self): result = builder.extract_node(''' from typing import NamedTuple NamedTuple("A") ''') inferred = next(result.infer()) self.assertIsInstance(inferred, astroid.Instance) self.assertEqual(inferred.qname(), "typing.NamedTuple")
def test_uuid_has_int_member(self): node = builder.extract_node(''' import uuid u = uuid.UUID('{12345678-1234-5678-1234-567812345678}') u.int ''') inferred = next(node.infer()) self.assertIsInstance(inferred, nodes.Const)
def test_module_name(self): module = builder.extract_node(""" import multiprocessing multiprocessing.SyncManager() """) inferred_sync_mgr = next(module.infer()) module = inferred_sync_mgr.root() self.assertEqual(module.name, 'multiprocessing.managers')
def test_namedtuple_simple(self): result = builder.extract_node(''' from typing import NamedTuple NamedTuple("A", [("a", int), ("b", str), ("c", bytes)]) ''') inferred = next(result.infer()) self.assertIsInstance(inferred, nodes.ClassDef) self.assertSetEqual({"a", "b", "c"}, set(inferred.instance_attrs))
def test__class__(self): ast_node = builder.extract_node("{}.__class__") inferred = next(ast_node.infer()) self.assertIsInstance(inferred, astroid.ClassDef) self.assertEqual(inferred.name, "dict")
def test_unpacking_in_dict_getitem(self): node = extract_node("{1:2, **{2:3, 3:4}, **{5: 6}}") for key, expected in ((1, 2), (2, 3), (3, 4), (5, 6)): value = node.getitem(nodes.Const(key)) self.assertIsInstance(value, nodes.Const) self.assertEqual(value.value, expected)
def _inferred_numpy_attribute(self, func_name): node = builder.extract_node(""" import numpy.random.mtrand as tested_module func = tested_module.{:s} func""".format(func_name)) return next(node.infer())
def test_super_simple_cases(self): ast_nodes = builder.extract_node(""" class First(object): pass class Second(First): pass class Third(First): def test(self): super(Third, self) #@ super(Second, self) #@ # mro position and the type super(Third, Third) #@ super(Third, Second) #@ super(Fourth, Fourth) #@ class Fourth(Third): pass """) # .type is the object which provides the mro. # .mro_pointer is the position in the mro from where # the lookup should be done. # super(Third, self) first = next(ast_nodes[0].infer()) self.assertIsInstance(first, objects.Super) self.assertIsInstance(first.type, bases.Instance) self.assertEqual(first.type.name, "Third") self.assertIsInstance(first.mro_pointer, nodes.ClassDef) self.assertEqual(first.mro_pointer.name, "Third") # super(Second, self) second = next(ast_nodes[1].infer()) self.assertIsInstance(second, objects.Super) self.assertIsInstance(second.type, bases.Instance) self.assertEqual(second.type.name, "Third") self.assertIsInstance(first.mro_pointer, nodes.ClassDef) self.assertEqual(second.mro_pointer.name, "Second") # super(Third, Third) third = next(ast_nodes[2].infer()) self.assertIsInstance(third, objects.Super) self.assertIsInstance(third.type, nodes.ClassDef) self.assertEqual(third.type.name, "Third") self.assertIsInstance(third.mro_pointer, nodes.ClassDef) self.assertEqual(third.mro_pointer.name, "Third") # super(Third, second) fourth = next(ast_nodes[3].infer()) self.assertIsInstance(fourth, objects.Super) self.assertIsInstance(fourth.type, nodes.ClassDef) self.assertEqual(fourth.type.name, "Second") self.assertIsInstance(fourth.mro_pointer, nodes.ClassDef) self.assertEqual(fourth.mro_pointer.name, "Third") # Super(Fourth, Fourth) fifth = next(ast_nodes[4].infer()) self.assertIsInstance(fifth, objects.Super) self.assertIsInstance(fifth.type, nodes.ClassDef) self.assertEqual(fifth.type.name, "Fourth") self.assertIsInstance(fifth.mro_pointer, nodes.ClassDef) self.assertEqual(fifth.mro_pointer.name, "Fourth")
def test_tuple_store(self): with self.assertRaises(exceptions.AstroidSyntaxError): builder.extract_node("(1, ) = 3")
def test_starred_load(self): node = builder.extract_node("a = *b") starred = node.value self.assertIs(starred.ctx, astroid.Load)
def test_starred_store(self): node = builder.extract_node("a, *b = 1, 2") starred = node.targets[0].elts[1] self.assertIs(starred.ctx, astroid.Store)
def test_nested_unpacking_in_dicts(self): code = "{'x': 1, **{'y': 2, **{'z': 3}}}" node = extract_node(code) self.assertEqual(node.as_string(), code)
def easy_class_getitem_inference(node, context=None): # Here __class_getitem__ exists but is quite a mess to infer thus # put an easy inference tip func_to_add = extract_node(CLASS_GET_ITEM_TEMPLATE) node.locals["__class_getitem__"] = [func_to_add]
def test_attribute_access(self): ast_nodes = builder.extract_node(''' import six six.moves.http_client #@ six.moves.urllib_parse #@ six.moves.urllib_error #@ six.moves.urllib.request #@ ''') http_client = next(ast_nodes[0].infer()) self.assertIsInstance(http_client, nodes.Module) self.assertEqual(http_client.name, 'http.client' if six.PY3 else 'httplib') urllib_parse = next(ast_nodes[1].infer()) if six.PY3: self.assertIsInstance(urllib_parse, nodes.Module) self.assertEqual(urllib_parse.name, 'urllib.parse') else: # On Python 2, this is a fake module, the same behaviour # being mimicked in brain's tip for six.moves. self.assertIsInstance(urllib_parse, astroid.Instance) urljoin = next(urllib_parse.igetattr('urljoin')) urlencode = next(urllib_parse.igetattr('urlencode')) if six.PY2: # In reality it's a function, but our implementations # transforms it into a method. self.assertIsInstance(urljoin, astroid.BoundMethod) self.assertEqual(urljoin.qname(), 'urlparse.urljoin') self.assertIsInstance(urlencode, astroid.BoundMethod) self.assertEqual(urlencode.qname(), 'urllib.urlencode') else: self.assertIsInstance(urljoin, nodes.FunctionDef) self.assertEqual(urljoin.qname(), 'urllib.parse.urljoin') self.assertIsInstance(urlencode, nodes.FunctionDef) self.assertEqual(urlencode.qname(), 'urllib.parse.urlencode') urllib_error = next(ast_nodes[2].infer()) if six.PY3: self.assertIsInstance(urllib_error, nodes.Module) self.assertEqual(urllib_error.name, 'urllib.error') else: # On Python 2, this is a fake module, the same behaviour # being mimicked in brain's tip for six.moves. self.assertIsInstance(urllib_error, astroid.Instance) urlerror = next(urllib_error.igetattr('URLError')) self.assertIsInstance(urlerror, nodes.ClassDef) content_too_short = next(urllib_error.igetattr('ContentTooShortError')) self.assertIsInstance(content_too_short, nodes.ClassDef) urllib_request = next(ast_nodes[3].infer()) if six.PY3: self.assertIsInstance(urllib_request, nodes.Module) self.assertEqual(urllib_request.name, 'urllib.request') else: self.assertIsInstance(urllib_request, astroid.Instance) urlopen = next(urllib_request.igetattr('urlopen')) urlretrieve = next(urllib_request.igetattr('urlretrieve')) if six.PY2: # In reality it's a function, but our implementations # transforms it into a method. self.assertIsInstance(urlopen, astroid.BoundMethod) self.assertEqual(urlopen.qname(), 'urllib2.urlopen') self.assertIsInstance(urlretrieve, astroid.BoundMethod) self.assertEqual(urlretrieve.qname(), 'urllib.urlretrieve') else: self.assertIsInstance(urlopen, nodes.FunctionDef) self.assertEqual(urlopen.qname(), 'urllib.request.urlopen') self.assertIsInstance(urlretrieve, nodes.FunctionDef) self.assertEqual(urlretrieve.qname(), 'urllib.request.urlretrieve')
def test_inference_errors(self): node = builder.extract_node(""" from unknown import Unknown u = Unknown #@ """) self.assertEqual(helpers.object_type(node), util.Uninferable)
def test_tuple_load(self): node = builder.extract_node("(1, )") self.assertIs(node.ctx, astroid.Load)
def test_subscript_del(self): node = builder.extract_node('del f[1]') self.assertIs(node.targets[0].ctx, astroid.Del)
def test_list_store(self): with self.assertRaises(exceptions.AstroidSyntaxError): builder.extract_node("[0] = 2")
def _inferred_numpy_attribute(self, attrib): node = builder.extract_node(""" import numpy.core.numerictypes as tested_module missing_type = tested_module.{:s}""".format(attrib)) return next(node.value.infer())
def test_list_del(self): node = builder.extract_node("del []") self.assertIs(node.targets[0].ctx, astroid.Del)
def _inferred_numpy_attribute(self, func_name): node = builder.extract_node(f""" import numpy.core.umath as tested_module func = tested_module.{func_name:s} func""") return next(node.infer())
def test_list_load(self): node = builder.extract_node("[]") self.assertIs(node.ctx, astroid.Load)
def test_subscript_store(self): node = builder.extract_node("f[1] = 2") subscript = node.targets[0] self.assertIs(subscript.ctx, astroid.Store)
def test_subscript_load(self): node = builder.extract_node("f[1]") self.assertIs(node.ctx, astroid.Load)
def infer_named_tuple(node, context=None): """Specific inference function for namedtuple Call node""" tuple_base_name = nodes.Name(name="tuple", parent=node.root()) class_node, name, attributes = infer_func_form( node, tuple_base_name, context=context ) call_site = arguments.CallSite.from_call(node, context=context) node = extract_node("import collections; collections.namedtuple") try: func = next(node.infer()) except StopIteration as e: raise InferenceError(node=node) from e try: rename = next(call_site.infer_argument(func, "rename", context)).bool_value() except (InferenceError, StopIteration): rename = False 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 = ( " {name} = property(lambda self: self[{index:d}], " "doc='Alias for field number {index:d}')" ) field_defs = "\n".join( field_def.format(name=name, index=index) for index, name in enumerate(attributes) ) fake = AstroidBuilder(AstroidManager()).string_build( """ class %(name)s(tuple): __slots__ = () _fields = %(fields)r def _asdict(self): return self.__dict__ @classmethod def _make(cls, iterable, new=tuple.__new__, len=len): return new(cls, iterable) def _replace(self, %(replace_args)s): return self def __getnewargs__(self): return tuple(self) %(field_defs)s """ % { "name": name, "fields": attributes, "field_defs": field_defs, "replace_args": replace_args, } ) class_node.locals["_asdict"] = fake.body[0].locals["_asdict"] class_node.locals["_make"] = fake.body[0].locals["_make"] class_node.locals["_replace"] = fake.body[0].locals["_replace"] class_node.locals["_fields"] = fake.body[0].locals["_fields"] for attr in attributes: class_node.locals[attr] = fake.body[0].locals[attr] # we use UseInferenceDefault, we can't be a generator so return an iterator return iter([class_node])
def test_format_string(self): code = "f'{greetings} {person}'" node = extract_node(code) self.assertEqual(node.as_string(), code)
def infer_numpy_member(src, node, context=None): node = extract_node(src) return node.infer(context=context)
def test_uninferable_string_argument_of_namedtuple(self): node = extract_node(''' import collections collections.namedtuple('{}'.format("a"), '')() ''') next(node.infer())