def _infer_instance_from_annotation(node: NodeNG, ctx: context.InferenceContext = None ) -> Generator: """Infer an instance corresponding to the type annotation represented by node. Currently has limited support for the typing module. """ klass = None try: klass = next(node.infer(context=ctx)) except (InferenceError, StopIteration): yield Uninferable if not isinstance(klass, ClassDef): yield Uninferable elif klass.root().name in { "typing", "_collections_abc", "", }: # "" because of synthetic nodes in brain_typing.py if klass.name in _INFERABLE_TYPING_TYPES: yield klass.instantiate_class() else: yield Uninferable else: yield klass.instantiate_class()
def _looks_like_dataclass_decorator( node: NodeNG, decorator_names: FrozenSet[str] = DATACLASSES_DECORATORS) -> bool: """Return True if node looks like a dataclass decorator. Uses inference to lookup the value of the node, and if that fails, matches against specific names. """ if isinstance(node, Call): # decorator with arguments node = node.func try: inferred = next(node.infer()) except (InferenceError, StopIteration): inferred = Uninferable if inferred is Uninferable: if isinstance(node, Name): return node.name in decorator_names if isinstance(node, Attribute): return node.attrname in decorator_names return False return (isinstance(inferred, FunctionDef) and inferred.name in decorator_names and inferred.root().name in DATACLASS_MODULES)
def _is_init_var(node: NodeNG) -> bool: """Return True if node is an InitVar, with or without subscripting.""" try: inferred = next(node.infer()) except (InferenceError, StopIteration): return False return getattr(inferred, "name", "") == "InitVar"
def _is_class_var(node: NodeNG) -> bool: """Return True if node is a ClassVar, with or without subscripting.""" if PY39_PLUS: try: inferred = next(node.infer()) except (InferenceError, StopIteration): return False return getattr(inferred, "name", "") == "ClassVar" # Before Python 3.9, inference returns typing._SpecialForm instead of ClassVar. # Our backup is to inspect the node's structure. return isinstance(node, Subscript) and ( isinstance(node.value, Name) and node.value.name == "ClassVar" or isinstance(node.value, Attribute) and node.value.attrname == "ClassVar")
def looks_like_numpy_member(member_name: str, node: NodeNG) -> bool: """ Returns True if the node is a member of numpy whose name is member_name. :param member_name: name of the member :param node: node to test :return: True if the node is a member of numpy """ if (isinstance(node, Attribute) and node.attrname == member_name and isinstance(node.expr, Name) and _is_a_numpy_module(node.expr)): return True if (isinstance(node, Name) and node.name == member_name and node.root().name.startswith("numpy")): return True return False