id int32 0 252k | repo stringlengths 7 55 | path stringlengths 4 127 | func_name stringlengths 1 88 | original_string stringlengths 75 19.8k | language stringclasses 1
value | code stringlengths 51 19.8k | code_tokens list | docstring stringlengths 3 17.3k | docstring_tokens list | sha stringlengths 40 40 | url stringlengths 87 242 |
|---|---|---|---|---|---|---|---|---|---|---|---|
227,200 | PyCQA/astroid | astroid/protocols.py | _resolve_looppart | def _resolve_looppart(parts, assign_path, context):
"""recursive function to resolve multiple assignments on loops"""
assign_path = assign_path[:]
index = assign_path.pop(0)
for part in parts:
if part is util.Uninferable:
continue
if not hasattr(part, "itered"):
continue
try:
itered = part.itered()
except TypeError:
continue
for stmt in itered:
index_node = nodes.Const(index)
try:
assigned = stmt.getitem(index_node, context)
except (
AttributeError,
exceptions.AstroidTypeError,
exceptions.AstroidIndexError,
):
continue
if not assign_path:
# we achieved to resolved the assignment path,
# don't infer the last part
yield assigned
elif assigned is util.Uninferable:
break
else:
# we are not yet on the last part of the path
# search on each possibly inferred value
try:
yield from _resolve_looppart(
assigned.infer(context), assign_path, context
)
except exceptions.InferenceError:
break | python | def _resolve_looppart(parts, assign_path, context):
assign_path = assign_path[:]
index = assign_path.pop(0)
for part in parts:
if part is util.Uninferable:
continue
if not hasattr(part, "itered"):
continue
try:
itered = part.itered()
except TypeError:
continue
for stmt in itered:
index_node = nodes.Const(index)
try:
assigned = stmt.getitem(index_node, context)
except (
AttributeError,
exceptions.AstroidTypeError,
exceptions.AstroidIndexError,
):
continue
if not assign_path:
# we achieved to resolved the assignment path,
# don't infer the last part
yield assigned
elif assigned is util.Uninferable:
break
else:
# we are not yet on the last part of the path
# search on each possibly inferred value
try:
yield from _resolve_looppart(
assigned.infer(context), assign_path, context
)
except exceptions.InferenceError:
break | [
"def",
"_resolve_looppart",
"(",
"parts",
",",
"assign_path",
",",
"context",
")",
":",
"assign_path",
"=",
"assign_path",
"[",
":",
"]",
"index",
"=",
"assign_path",
".",
"pop",
"(",
"0",
")",
"for",
"part",
"in",
"parts",
":",
"if",
"part",
"is",
"ut... | recursive function to resolve multiple assignments on loops | [
"recursive",
"function",
"to",
"resolve",
"multiple",
"assignments",
"on",
"loops"
] | e0a298df55b15abcb77c2a93253f5ab7be52d0fb | https://github.com/PyCQA/astroid/blob/e0a298df55b15abcb77c2a93253f5ab7be52d0fb/astroid/protocols.py#L229-L266 |
227,201 | PyCQA/astroid | astroid/protocols.py | _resolve_assignment_parts | def _resolve_assignment_parts(parts, assign_path, context):
"""recursive function to resolve multiple assignments"""
assign_path = assign_path[:]
index = assign_path.pop(0)
for part in parts:
assigned = None
if isinstance(part, nodes.Dict):
# A dictionary in an iterating context
try:
assigned, _ = part.items[index]
except IndexError:
return
elif hasattr(part, "getitem"):
index_node = nodes.Const(index)
try:
assigned = part.getitem(index_node, context)
except (exceptions.AstroidTypeError, exceptions.AstroidIndexError):
return
if not assigned:
return
if not assign_path:
# we achieved to resolved the assignment path, don't infer the
# last part
yield assigned
elif assigned is util.Uninferable:
return
else:
# we are not yet on the last part of the path search on each
# possibly inferred value
try:
yield from _resolve_assignment_parts(
assigned.infer(context), assign_path, context
)
except exceptions.InferenceError:
return | python | def _resolve_assignment_parts(parts, assign_path, context):
assign_path = assign_path[:]
index = assign_path.pop(0)
for part in parts:
assigned = None
if isinstance(part, nodes.Dict):
# A dictionary in an iterating context
try:
assigned, _ = part.items[index]
except IndexError:
return
elif hasattr(part, "getitem"):
index_node = nodes.Const(index)
try:
assigned = part.getitem(index_node, context)
except (exceptions.AstroidTypeError, exceptions.AstroidIndexError):
return
if not assigned:
return
if not assign_path:
# we achieved to resolved the assignment path, don't infer the
# last part
yield assigned
elif assigned is util.Uninferable:
return
else:
# we are not yet on the last part of the path search on each
# possibly inferred value
try:
yield from _resolve_assignment_parts(
assigned.infer(context), assign_path, context
)
except exceptions.InferenceError:
return | [
"def",
"_resolve_assignment_parts",
"(",
"parts",
",",
"assign_path",
",",
"context",
")",
":",
"assign_path",
"=",
"assign_path",
"[",
":",
"]",
"index",
"=",
"assign_path",
".",
"pop",
"(",
"0",
")",
"for",
"part",
"in",
"parts",
":",
"assigned",
"=",
... | recursive function to resolve multiple assignments | [
"recursive",
"function",
"to",
"resolve",
"multiple",
"assignments"
] | e0a298df55b15abcb77c2a93253f5ab7be52d0fb | https://github.com/PyCQA/astroid/blob/e0a298df55b15abcb77c2a93253f5ab7be52d0fb/astroid/protocols.py#L402-L439 |
227,202 | PyCQA/astroid | astroid/inference.py | _infer_sequence_helper | def _infer_sequence_helper(node, context=None):
"""Infer all values based on _BaseContainer.elts"""
values = []
for elt in node.elts:
if isinstance(elt, nodes.Starred):
starred = helpers.safe_infer(elt.value, context)
if not starred:
raise exceptions.InferenceError(node=node, context=context)
if not hasattr(starred, "elts"):
raise exceptions.InferenceError(node=node, context=context)
values.extend(_infer_sequence_helper(starred))
else:
values.append(elt)
return values | python | def _infer_sequence_helper(node, context=None):
values = []
for elt in node.elts:
if isinstance(elt, nodes.Starred):
starred = helpers.safe_infer(elt.value, context)
if not starred:
raise exceptions.InferenceError(node=node, context=context)
if not hasattr(starred, "elts"):
raise exceptions.InferenceError(node=node, context=context)
values.extend(_infer_sequence_helper(starred))
else:
values.append(elt)
return values | [
"def",
"_infer_sequence_helper",
"(",
"node",
",",
"context",
"=",
"None",
")",
":",
"values",
"=",
"[",
"]",
"for",
"elt",
"in",
"node",
".",
"elts",
":",
"if",
"isinstance",
"(",
"elt",
",",
"nodes",
".",
"Starred",
")",
":",
"starred",
"=",
"helpe... | Infer all values based on _BaseContainer.elts | [
"Infer",
"all",
"values",
"based",
"on",
"_BaseContainer",
".",
"elts"
] | e0a298df55b15abcb77c2a93253f5ab7be52d0fb | https://github.com/PyCQA/astroid/blob/e0a298df55b15abcb77c2a93253f5ab7be52d0fb/astroid/inference.py#L62-L76 |
227,203 | PyCQA/astroid | astroid/inference.py | _update_with_replacement | def _update_with_replacement(lhs_dict, rhs_dict):
"""Delete nodes that equate to duplicate keys
Since an astroid node doesn't 'equal' another node with the same value,
this function uses the as_string method to make sure duplicate keys
don't get through
Note that both the key and the value are astroid nodes
Fixes issue with DictUnpack causing duplicte keys
in inferred Dict items
:param dict(nodes.NodeNG, nodes.NodeNG) lhs_dict: Dictionary to 'merge' nodes into
:param dict(nodes.NodeNG, nodes.NodeNG) rhs_dict: Dictionary with nodes to pull from
:return dict(nodes.NodeNG, nodes.NodeNG): merged dictionary of nodes
"""
combined_dict = itertools.chain(lhs_dict.items(), rhs_dict.items())
# Overwrite keys which have the same string values
string_map = {key.as_string(): (key, value) for key, value in combined_dict}
# Return to dictionary
return dict(string_map.values()) | python | def _update_with_replacement(lhs_dict, rhs_dict):
combined_dict = itertools.chain(lhs_dict.items(), rhs_dict.items())
# Overwrite keys which have the same string values
string_map = {key.as_string(): (key, value) for key, value in combined_dict}
# Return to dictionary
return dict(string_map.values()) | [
"def",
"_update_with_replacement",
"(",
"lhs_dict",
",",
"rhs_dict",
")",
":",
"combined_dict",
"=",
"itertools",
".",
"chain",
"(",
"lhs_dict",
".",
"items",
"(",
")",
",",
"rhs_dict",
".",
"items",
"(",
")",
")",
"# Overwrite keys which have the same string valu... | Delete nodes that equate to duplicate keys
Since an astroid node doesn't 'equal' another node with the same value,
this function uses the as_string method to make sure duplicate keys
don't get through
Note that both the key and the value are astroid nodes
Fixes issue with DictUnpack causing duplicte keys
in inferred Dict items
:param dict(nodes.NodeNG, nodes.NodeNG) lhs_dict: Dictionary to 'merge' nodes into
:param dict(nodes.NodeNG, nodes.NodeNG) rhs_dict: Dictionary with nodes to pull from
:return dict(nodes.NodeNG, nodes.NodeNG): merged dictionary of nodes | [
"Delete",
"nodes",
"that",
"equate",
"to",
"duplicate",
"keys"
] | e0a298df55b15abcb77c2a93253f5ab7be52d0fb | https://github.com/PyCQA/astroid/blob/e0a298df55b15abcb77c2a93253f5ab7be52d0fb/astroid/inference.py#L108-L128 |
227,204 | PyCQA/astroid | astroid/inference.py | _infer_map | def _infer_map(node, context):
"""Infer all values based on Dict.items"""
values = {}
for name, value in node.items:
if isinstance(name, nodes.DictUnpack):
double_starred = helpers.safe_infer(value, context)
if not double_starred:
raise exceptions.InferenceError
if not isinstance(double_starred, nodes.Dict):
raise exceptions.InferenceError(node=node, context=context)
unpack_items = _infer_map(double_starred, context)
values = _update_with_replacement(values, unpack_items)
else:
key = helpers.safe_infer(name, context=context)
value = helpers.safe_infer(value, context=context)
if any(not elem for elem in (key, value)):
raise exceptions.InferenceError(node=node, context=context)
values = _update_with_replacement(values, {key: value})
return values | python | def _infer_map(node, context):
values = {}
for name, value in node.items:
if isinstance(name, nodes.DictUnpack):
double_starred = helpers.safe_infer(value, context)
if not double_starred:
raise exceptions.InferenceError
if not isinstance(double_starred, nodes.Dict):
raise exceptions.InferenceError(node=node, context=context)
unpack_items = _infer_map(double_starred, context)
values = _update_with_replacement(values, unpack_items)
else:
key = helpers.safe_infer(name, context=context)
value = helpers.safe_infer(value, context=context)
if any(not elem for elem in (key, value)):
raise exceptions.InferenceError(node=node, context=context)
values = _update_with_replacement(values, {key: value})
return values | [
"def",
"_infer_map",
"(",
"node",
",",
"context",
")",
":",
"values",
"=",
"{",
"}",
"for",
"name",
",",
"value",
"in",
"node",
".",
"items",
":",
"if",
"isinstance",
"(",
"name",
",",
"nodes",
".",
"DictUnpack",
")",
":",
"double_starred",
"=",
"hel... | Infer all values based on Dict.items | [
"Infer",
"all",
"values",
"based",
"on",
"Dict",
".",
"items"
] | e0a298df55b15abcb77c2a93253f5ab7be52d0fb | https://github.com/PyCQA/astroid/blob/e0a298df55b15abcb77c2a93253f5ab7be52d0fb/astroid/inference.py#L131-L149 |
227,205 | PyCQA/astroid | astroid/inference.py | _higher_function_scope | def _higher_function_scope(node):
""" Search for the first function which encloses the given
scope. This can be used for looking up in that function's
scope, in case looking up in a lower scope for a particular
name fails.
:param node: A scope node.
:returns:
``None``, if no parent function scope was found,
otherwise an instance of :class:`astroid.scoped_nodes.Function`,
which encloses the given node.
"""
current = node
while current.parent and not isinstance(current.parent, nodes.FunctionDef):
current = current.parent
if current and current.parent:
return current.parent
return None | python | def _higher_function_scope(node):
current = node
while current.parent and not isinstance(current.parent, nodes.FunctionDef):
current = current.parent
if current and current.parent:
return current.parent
return None | [
"def",
"_higher_function_scope",
"(",
"node",
")",
":",
"current",
"=",
"node",
"while",
"current",
".",
"parent",
"and",
"not",
"isinstance",
"(",
"current",
".",
"parent",
",",
"nodes",
".",
"FunctionDef",
")",
":",
"current",
"=",
"current",
".",
"paren... | Search for the first function which encloses the given
scope. This can be used for looking up in that function's
scope, in case looking up in a lower scope for a particular
name fails.
:param node: A scope node.
:returns:
``None``, if no parent function scope was found,
otherwise an instance of :class:`astroid.scoped_nodes.Function`,
which encloses the given node. | [
"Search",
"for",
"the",
"first",
"function",
"which",
"encloses",
"the",
"given",
"scope",
".",
"This",
"can",
"be",
"used",
"for",
"looking",
"up",
"in",
"that",
"function",
"s",
"scope",
"in",
"case",
"looking",
"up",
"in",
"a",
"lower",
"scope",
"for"... | e0a298df55b15abcb77c2a93253f5ab7be52d0fb | https://github.com/PyCQA/astroid/blob/e0a298df55b15abcb77c2a93253f5ab7be52d0fb/astroid/inference.py#L155-L172 |
227,206 | PyCQA/astroid | astroid/inference.py | infer_call | def infer_call(self, context=None):
"""infer a Call node by trying to guess what the function returns"""
callcontext = contextmod.copy_context(context)
callcontext.callcontext = contextmod.CallContext(
args=self.args, keywords=self.keywords
)
callcontext.boundnode = None
if context is not None:
callcontext.extra_context = _populate_context_lookup(self, context.clone())
for callee in self.func.infer(context):
if callee is util.Uninferable:
yield callee
continue
try:
if hasattr(callee, "infer_call_result"):
yield from callee.infer_call_result(caller=self, context=callcontext)
except exceptions.InferenceError:
continue
return dict(node=self, context=context) | python | def infer_call(self, context=None):
callcontext = contextmod.copy_context(context)
callcontext.callcontext = contextmod.CallContext(
args=self.args, keywords=self.keywords
)
callcontext.boundnode = None
if context is not None:
callcontext.extra_context = _populate_context_lookup(self, context.clone())
for callee in self.func.infer(context):
if callee is util.Uninferable:
yield callee
continue
try:
if hasattr(callee, "infer_call_result"):
yield from callee.infer_call_result(caller=self, context=callcontext)
except exceptions.InferenceError:
continue
return dict(node=self, context=context) | [
"def",
"infer_call",
"(",
"self",
",",
"context",
"=",
"None",
")",
":",
"callcontext",
"=",
"contextmod",
".",
"copy_context",
"(",
"context",
")",
"callcontext",
".",
"callcontext",
"=",
"contextmod",
".",
"CallContext",
"(",
"args",
"=",
"self",
".",
"a... | infer a Call node by trying to guess what the function returns | [
"infer",
"a",
"Call",
"node",
"by",
"trying",
"to",
"guess",
"what",
"the",
"function",
"returns"
] | e0a298df55b15abcb77c2a93253f5ab7be52d0fb | https://github.com/PyCQA/astroid/blob/e0a298df55b15abcb77c2a93253f5ab7be52d0fb/astroid/inference.py#L203-L222 |
227,207 | PyCQA/astroid | astroid/inference.py | infer_attribute | def infer_attribute(self, context=None):
"""infer an Attribute node by using getattr on the associated object"""
for owner in self.expr.infer(context):
if owner is util.Uninferable:
yield owner
continue
if context and context.boundnode:
# This handles the situation where the attribute is accessed through a subclass
# of a base class and the attribute is defined at the base class's level,
# by taking in consideration a redefinition in the subclass.
if isinstance(owner, bases.Instance) and isinstance(
context.boundnode, bases.Instance
):
try:
if helpers.is_subtype(
helpers.object_type(context.boundnode),
helpers.object_type(owner),
):
owner = context.boundnode
except exceptions._NonDeducibleTypeHierarchy:
# Can't determine anything useful.
pass
try:
context.boundnode = owner
yield from owner.igetattr(self.attrname, context)
context.boundnode = None
except (exceptions.AttributeInferenceError, exceptions.InferenceError):
context.boundnode = None
except AttributeError:
# XXX method / function
context.boundnode = None
return dict(node=self, context=context) | python | def infer_attribute(self, context=None):
for owner in self.expr.infer(context):
if owner is util.Uninferable:
yield owner
continue
if context and context.boundnode:
# This handles the situation where the attribute is accessed through a subclass
# of a base class and the attribute is defined at the base class's level,
# by taking in consideration a redefinition in the subclass.
if isinstance(owner, bases.Instance) and isinstance(
context.boundnode, bases.Instance
):
try:
if helpers.is_subtype(
helpers.object_type(context.boundnode),
helpers.object_type(owner),
):
owner = context.boundnode
except exceptions._NonDeducibleTypeHierarchy:
# Can't determine anything useful.
pass
try:
context.boundnode = owner
yield from owner.igetattr(self.attrname, context)
context.boundnode = None
except (exceptions.AttributeInferenceError, exceptions.InferenceError):
context.boundnode = None
except AttributeError:
# XXX method / function
context.boundnode = None
return dict(node=self, context=context) | [
"def",
"infer_attribute",
"(",
"self",
",",
"context",
"=",
"None",
")",
":",
"for",
"owner",
"in",
"self",
".",
"expr",
".",
"infer",
"(",
"context",
")",
":",
"if",
"owner",
"is",
"util",
".",
"Uninferable",
":",
"yield",
"owner",
"continue",
"if",
... | infer an Attribute node by using getattr on the associated object | [
"infer",
"an",
"Attribute",
"node",
"by",
"using",
"getattr",
"on",
"the",
"associated",
"object"
] | e0a298df55b15abcb77c2a93253f5ab7be52d0fb | https://github.com/PyCQA/astroid/blob/e0a298df55b15abcb77c2a93253f5ab7be52d0fb/astroid/inference.py#L277-L310 |
227,208 | PyCQA/astroid | astroid/inference.py | infer_subscript | def infer_subscript(self, context=None):
"""Inference for subscripts
We're understanding if the index is a Const
or a slice, passing the result of inference
to the value's `getitem` method, which should
handle each supported index type accordingly.
"""
found_one = False
for value in self.value.infer(context):
if value is util.Uninferable:
yield util.Uninferable
return None
for index in self.slice.infer(context):
if index is util.Uninferable:
yield util.Uninferable
return None
# Try to deduce the index value.
index_value = _SUBSCRIPT_SENTINEL
if value.__class__ == bases.Instance:
index_value = index
else:
if index.__class__ == bases.Instance:
instance_as_index = helpers.class_instance_as_index(index)
if instance_as_index:
index_value = instance_as_index
else:
index_value = index
if index_value is _SUBSCRIPT_SENTINEL:
raise exceptions.InferenceError(node=self, context=context)
try:
assigned = value.getitem(index_value, context)
except (
exceptions.AstroidTypeError,
exceptions.AstroidIndexError,
exceptions.AttributeInferenceError,
AttributeError,
) as exc:
raise exceptions.InferenceError(node=self, context=context) from exc
# Prevent inferring if the inferred subscript
# is the same as the original subscripted object.
if self is assigned or assigned is util.Uninferable:
yield util.Uninferable
return None
yield from assigned.infer(context)
found_one = True
if found_one:
return dict(node=self, context=context)
return None | python | def infer_subscript(self, context=None):
found_one = False
for value in self.value.infer(context):
if value is util.Uninferable:
yield util.Uninferable
return None
for index in self.slice.infer(context):
if index is util.Uninferable:
yield util.Uninferable
return None
# Try to deduce the index value.
index_value = _SUBSCRIPT_SENTINEL
if value.__class__ == bases.Instance:
index_value = index
else:
if index.__class__ == bases.Instance:
instance_as_index = helpers.class_instance_as_index(index)
if instance_as_index:
index_value = instance_as_index
else:
index_value = index
if index_value is _SUBSCRIPT_SENTINEL:
raise exceptions.InferenceError(node=self, context=context)
try:
assigned = value.getitem(index_value, context)
except (
exceptions.AstroidTypeError,
exceptions.AstroidIndexError,
exceptions.AttributeInferenceError,
AttributeError,
) as exc:
raise exceptions.InferenceError(node=self, context=context) from exc
# Prevent inferring if the inferred subscript
# is the same as the original subscripted object.
if self is assigned or assigned is util.Uninferable:
yield util.Uninferable
return None
yield from assigned.infer(context)
found_one = True
if found_one:
return dict(node=self, context=context)
return None | [
"def",
"infer_subscript",
"(",
"self",
",",
"context",
"=",
"None",
")",
":",
"found_one",
"=",
"False",
"for",
"value",
"in",
"self",
".",
"value",
".",
"infer",
"(",
"context",
")",
":",
"if",
"value",
"is",
"util",
".",
"Uninferable",
":",
"yield",
... | Inference for subscripts
We're understanding if the index is a Const
or a slice, passing the result of inference
to the value's `getitem` method, which should
handle each supported index type accordingly. | [
"Inference",
"for",
"subscripts"
] | e0a298df55b15abcb77c2a93253f5ab7be52d0fb | https://github.com/PyCQA/astroid/blob/e0a298df55b15abcb77c2a93253f5ab7be52d0fb/astroid/inference.py#L340-L393 |
227,209 | PyCQA/astroid | astroid/inference.py | _invoke_binop_inference | def _invoke_binop_inference(instance, opnode, op, other, context, method_name):
"""Invoke binary operation inference on the given instance."""
methods = dunder_lookup.lookup(instance, method_name)
context = contextmod.bind_context_to_node(context, instance)
method = methods[0]
inferred = next(method.infer(context=context))
if inferred is util.Uninferable:
raise exceptions.InferenceError
return instance.infer_binary_op(opnode, op, other, context, inferred) | python | def _invoke_binop_inference(instance, opnode, op, other, context, method_name):
methods = dunder_lookup.lookup(instance, method_name)
context = contextmod.bind_context_to_node(context, instance)
method = methods[0]
inferred = next(method.infer(context=context))
if inferred is util.Uninferable:
raise exceptions.InferenceError
return instance.infer_binary_op(opnode, op, other, context, inferred) | [
"def",
"_invoke_binop_inference",
"(",
"instance",
",",
"opnode",
",",
"op",
",",
"other",
",",
"context",
",",
"method_name",
")",
":",
"methods",
"=",
"dunder_lookup",
".",
"lookup",
"(",
"instance",
",",
"method_name",
")",
"context",
"=",
"contextmod",
"... | Invoke binary operation inference on the given instance. | [
"Invoke",
"binary",
"operation",
"inference",
"on",
"the",
"given",
"instance",
"."
] | e0a298df55b15abcb77c2a93253f5ab7be52d0fb | https://github.com/PyCQA/astroid/blob/e0a298df55b15abcb77c2a93253f5ab7be52d0fb/astroid/inference.py#L543-L551 |
227,210 | PyCQA/astroid | astroid/inference.py | _aug_op | def _aug_op(instance, opnode, op, other, context, reverse=False):
"""Get an inference callable for an augmented binary operation."""
method_name = protocols.AUGMENTED_OP_METHOD[op]
return functools.partial(
_invoke_binop_inference,
instance=instance,
op=op,
opnode=opnode,
other=other,
context=context,
method_name=method_name,
) | python | def _aug_op(instance, opnode, op, other, context, reverse=False):
method_name = protocols.AUGMENTED_OP_METHOD[op]
return functools.partial(
_invoke_binop_inference,
instance=instance,
op=op,
opnode=opnode,
other=other,
context=context,
method_name=method_name,
) | [
"def",
"_aug_op",
"(",
"instance",
",",
"opnode",
",",
"op",
",",
"other",
",",
"context",
",",
"reverse",
"=",
"False",
")",
":",
"method_name",
"=",
"protocols",
".",
"AUGMENTED_OP_METHOD",
"[",
"op",
"]",
"return",
"functools",
".",
"partial",
"(",
"_... | Get an inference callable for an augmented binary operation. | [
"Get",
"an",
"inference",
"callable",
"for",
"an",
"augmented",
"binary",
"operation",
"."
] | e0a298df55b15abcb77c2a93253f5ab7be52d0fb | https://github.com/PyCQA/astroid/blob/e0a298df55b15abcb77c2a93253f5ab7be52d0fb/astroid/inference.py#L554-L565 |
227,211 | PyCQA/astroid | astroid/inference.py | _bin_op | def _bin_op(instance, opnode, op, other, context, reverse=False):
"""Get an inference callable for a normal binary operation.
If *reverse* is True, then the reflected method will be used instead.
"""
if reverse:
method_name = protocols.REFLECTED_BIN_OP_METHOD[op]
else:
method_name = protocols.BIN_OP_METHOD[op]
return functools.partial(
_invoke_binop_inference,
instance=instance,
op=op,
opnode=opnode,
other=other,
context=context,
method_name=method_name,
) | python | def _bin_op(instance, opnode, op, other, context, reverse=False):
if reverse:
method_name = protocols.REFLECTED_BIN_OP_METHOD[op]
else:
method_name = protocols.BIN_OP_METHOD[op]
return functools.partial(
_invoke_binop_inference,
instance=instance,
op=op,
opnode=opnode,
other=other,
context=context,
method_name=method_name,
) | [
"def",
"_bin_op",
"(",
"instance",
",",
"opnode",
",",
"op",
",",
"other",
",",
"context",
",",
"reverse",
"=",
"False",
")",
":",
"if",
"reverse",
":",
"method_name",
"=",
"protocols",
".",
"REFLECTED_BIN_OP_METHOD",
"[",
"op",
"]",
"else",
":",
"method... | Get an inference callable for a normal binary operation.
If *reverse* is True, then the reflected method will be used instead. | [
"Get",
"an",
"inference",
"callable",
"for",
"a",
"normal",
"binary",
"operation",
"."
] | e0a298df55b15abcb77c2a93253f5ab7be52d0fb | https://github.com/PyCQA/astroid/blob/e0a298df55b15abcb77c2a93253f5ab7be52d0fb/astroid/inference.py#L568-L585 |
227,212 | PyCQA/astroid | astroid/inference.py | _get_binop_contexts | def _get_binop_contexts(context, left, right):
"""Get contexts for binary operations.
This will return two inference contexts, the first one
for x.__op__(y), the other one for y.__rop__(x), where
only the arguments are inversed.
"""
# The order is important, since the first one should be
# left.__op__(right).
for arg in (right, left):
new_context = context.clone()
new_context.callcontext = contextmod.CallContext(args=[arg])
new_context.boundnode = None
yield new_context | python | def _get_binop_contexts(context, left, right):
# The order is important, since the first one should be
# left.__op__(right).
for arg in (right, left):
new_context = context.clone()
new_context.callcontext = contextmod.CallContext(args=[arg])
new_context.boundnode = None
yield new_context | [
"def",
"_get_binop_contexts",
"(",
"context",
",",
"left",
",",
"right",
")",
":",
"# The order is important, since the first one should be",
"# left.__op__(right).",
"for",
"arg",
"in",
"(",
"right",
",",
"left",
")",
":",
"new_context",
"=",
"context",
".",
"clone... | Get contexts for binary operations.
This will return two inference contexts, the first one
for x.__op__(y), the other one for y.__rop__(x), where
only the arguments are inversed. | [
"Get",
"contexts",
"for",
"binary",
"operations",
"."
] | e0a298df55b15abcb77c2a93253f5ab7be52d0fb | https://github.com/PyCQA/astroid/blob/e0a298df55b15abcb77c2a93253f5ab7be52d0fb/astroid/inference.py#L588-L601 |
227,213 | PyCQA/astroid | astroid/inference.py | _get_binop_flow | def _get_binop_flow(
left, left_type, binary_opnode, right, right_type, context, reverse_context
):
"""Get the flow for binary operations.
The rules are a bit messy:
* if left and right have the same type, then only one
method will be called, left.__op__(right)
* if left and right are unrelated typewise, then first
left.__op__(right) is tried and if this does not exist
or returns NotImplemented, then right.__rop__(left) is tried.
* if left is a subtype of right, then only left.__op__(right)
is tried.
* if left is a supertype of right, then right.__rop__(left)
is first tried and then left.__op__(right)
"""
op = binary_opnode.op
if _same_type(left_type, right_type):
methods = [_bin_op(left, binary_opnode, op, right, context)]
elif helpers.is_subtype(left_type, right_type):
methods = [_bin_op(left, binary_opnode, op, right, context)]
elif helpers.is_supertype(left_type, right_type):
methods = [
_bin_op(right, binary_opnode, op, left, reverse_context, reverse=True),
_bin_op(left, binary_opnode, op, right, context),
]
else:
methods = [
_bin_op(left, binary_opnode, op, right, context),
_bin_op(right, binary_opnode, op, left, reverse_context, reverse=True),
]
return methods | python | def _get_binop_flow(
left, left_type, binary_opnode, right, right_type, context, reverse_context
):
op = binary_opnode.op
if _same_type(left_type, right_type):
methods = [_bin_op(left, binary_opnode, op, right, context)]
elif helpers.is_subtype(left_type, right_type):
methods = [_bin_op(left, binary_opnode, op, right, context)]
elif helpers.is_supertype(left_type, right_type):
methods = [
_bin_op(right, binary_opnode, op, left, reverse_context, reverse=True),
_bin_op(left, binary_opnode, op, right, context),
]
else:
methods = [
_bin_op(left, binary_opnode, op, right, context),
_bin_op(right, binary_opnode, op, left, reverse_context, reverse=True),
]
return methods | [
"def",
"_get_binop_flow",
"(",
"left",
",",
"left_type",
",",
"binary_opnode",
",",
"right",
",",
"right_type",
",",
"context",
",",
"reverse_context",
")",
":",
"op",
"=",
"binary_opnode",
".",
"op",
"if",
"_same_type",
"(",
"left_type",
",",
"right_type",
... | Get the flow for binary operations.
The rules are a bit messy:
* if left and right have the same type, then only one
method will be called, left.__op__(right)
* if left and right are unrelated typewise, then first
left.__op__(right) is tried and if this does not exist
or returns NotImplemented, then right.__rop__(left) is tried.
* if left is a subtype of right, then only left.__op__(right)
is tried.
* if left is a supertype of right, then right.__rop__(left)
is first tried and then left.__op__(right) | [
"Get",
"the",
"flow",
"for",
"binary",
"operations",
"."
] | e0a298df55b15abcb77c2a93253f5ab7be52d0fb | https://github.com/PyCQA/astroid/blob/e0a298df55b15abcb77c2a93253f5ab7be52d0fb/astroid/inference.py#L609-L641 |
227,214 | PyCQA/astroid | astroid/inference.py | _get_aug_flow | def _get_aug_flow(
left, left_type, aug_opnode, right, right_type, context, reverse_context
):
"""Get the flow for augmented binary operations.
The rules are a bit messy:
* if left and right have the same type, then left.__augop__(right)
is first tried and then left.__op__(right).
* if left and right are unrelated typewise, then
left.__augop__(right) is tried, then left.__op__(right)
is tried and then right.__rop__(left) is tried.
* if left is a subtype of right, then left.__augop__(right)
is tried and then left.__op__(right).
* if left is a supertype of right, then left.__augop__(right)
is tried, then right.__rop__(left) and then
left.__op__(right)
"""
bin_op = aug_opnode.op.strip("=")
aug_op = aug_opnode.op
if _same_type(left_type, right_type):
methods = [
_aug_op(left, aug_opnode, aug_op, right, context),
_bin_op(left, aug_opnode, bin_op, right, context),
]
elif helpers.is_subtype(left_type, right_type):
methods = [
_aug_op(left, aug_opnode, aug_op, right, context),
_bin_op(left, aug_opnode, bin_op, right, context),
]
elif helpers.is_supertype(left_type, right_type):
methods = [
_aug_op(left, aug_opnode, aug_op, right, context),
_bin_op(right, aug_opnode, bin_op, left, reverse_context, reverse=True),
_bin_op(left, aug_opnode, bin_op, right, context),
]
else:
methods = [
_aug_op(left, aug_opnode, aug_op, right, context),
_bin_op(left, aug_opnode, bin_op, right, context),
_bin_op(right, aug_opnode, bin_op, left, reverse_context, reverse=True),
]
return methods | python | def _get_aug_flow(
left, left_type, aug_opnode, right, right_type, context, reverse_context
):
bin_op = aug_opnode.op.strip("=")
aug_op = aug_opnode.op
if _same_type(left_type, right_type):
methods = [
_aug_op(left, aug_opnode, aug_op, right, context),
_bin_op(left, aug_opnode, bin_op, right, context),
]
elif helpers.is_subtype(left_type, right_type):
methods = [
_aug_op(left, aug_opnode, aug_op, right, context),
_bin_op(left, aug_opnode, bin_op, right, context),
]
elif helpers.is_supertype(left_type, right_type):
methods = [
_aug_op(left, aug_opnode, aug_op, right, context),
_bin_op(right, aug_opnode, bin_op, left, reverse_context, reverse=True),
_bin_op(left, aug_opnode, bin_op, right, context),
]
else:
methods = [
_aug_op(left, aug_opnode, aug_op, right, context),
_bin_op(left, aug_opnode, bin_op, right, context),
_bin_op(right, aug_opnode, bin_op, left, reverse_context, reverse=True),
]
return methods | [
"def",
"_get_aug_flow",
"(",
"left",
",",
"left_type",
",",
"aug_opnode",
",",
"right",
",",
"right_type",
",",
"context",
",",
"reverse_context",
")",
":",
"bin_op",
"=",
"aug_opnode",
".",
"op",
".",
"strip",
"(",
"\"=\"",
")",
"aug_op",
"=",
"aug_opnode... | Get the flow for augmented binary operations.
The rules are a bit messy:
* if left and right have the same type, then left.__augop__(right)
is first tried and then left.__op__(right).
* if left and right are unrelated typewise, then
left.__augop__(right) is tried, then left.__op__(right)
is tried and then right.__rop__(left) is tried.
* if left is a subtype of right, then left.__augop__(right)
is tried and then left.__op__(right).
* if left is a supertype of right, then left.__augop__(right)
is tried, then right.__rop__(left) and then
left.__op__(right) | [
"Get",
"the",
"flow",
"for",
"augmented",
"binary",
"operations",
"."
] | e0a298df55b15abcb77c2a93253f5ab7be52d0fb | https://github.com/PyCQA/astroid/blob/e0a298df55b15abcb77c2a93253f5ab7be52d0fb/astroid/inference.py#L644-L686 |
227,215 | PyCQA/astroid | astroid/inference.py | _infer_binary_operation | def _infer_binary_operation(left, right, binary_opnode, context, flow_factory):
"""Infer a binary operation between a left operand and a right operand
This is used by both normal binary operations and augmented binary
operations, the only difference is the flow factory used.
"""
context, reverse_context = _get_binop_contexts(context, left, right)
left_type = helpers.object_type(left)
right_type = helpers.object_type(right)
methods = flow_factory(
left, left_type, binary_opnode, right, right_type, context, reverse_context
)
for method in methods:
try:
results = list(method())
except AttributeError:
continue
except exceptions.AttributeInferenceError:
continue
except exceptions.InferenceError:
yield util.Uninferable
return
else:
if any(result is util.Uninferable for result in results):
yield util.Uninferable
return
if all(map(_is_not_implemented, results)):
continue
not_implemented = sum(
1 for result in results if _is_not_implemented(result)
)
if not_implemented and not_implemented != len(results):
# Can't infer yet what this is.
yield util.Uninferable
return
yield from results
return
# The operation doesn't seem to be supported so let the caller know about it
yield util.BadBinaryOperationMessage(left_type, binary_opnode.op, right_type) | python | def _infer_binary_operation(left, right, binary_opnode, context, flow_factory):
context, reverse_context = _get_binop_contexts(context, left, right)
left_type = helpers.object_type(left)
right_type = helpers.object_type(right)
methods = flow_factory(
left, left_type, binary_opnode, right, right_type, context, reverse_context
)
for method in methods:
try:
results = list(method())
except AttributeError:
continue
except exceptions.AttributeInferenceError:
continue
except exceptions.InferenceError:
yield util.Uninferable
return
else:
if any(result is util.Uninferable for result in results):
yield util.Uninferable
return
if all(map(_is_not_implemented, results)):
continue
not_implemented = sum(
1 for result in results if _is_not_implemented(result)
)
if not_implemented and not_implemented != len(results):
# Can't infer yet what this is.
yield util.Uninferable
return
yield from results
return
# The operation doesn't seem to be supported so let the caller know about it
yield util.BadBinaryOperationMessage(left_type, binary_opnode.op, right_type) | [
"def",
"_infer_binary_operation",
"(",
"left",
",",
"right",
",",
"binary_opnode",
",",
"context",
",",
"flow_factory",
")",
":",
"context",
",",
"reverse_context",
"=",
"_get_binop_contexts",
"(",
"context",
",",
"left",
",",
"right",
")",
"left_type",
"=",
"... | Infer a binary operation between a left operand and a right operand
This is used by both normal binary operations and augmented binary
operations, the only difference is the flow factory used. | [
"Infer",
"a",
"binary",
"operation",
"between",
"a",
"left",
"operand",
"and",
"a",
"right",
"operand"
] | e0a298df55b15abcb77c2a93253f5ab7be52d0fb | https://github.com/PyCQA/astroid/blob/e0a298df55b15abcb77c2a93253f5ab7be52d0fb/astroid/inference.py#L689-L730 |
227,216 | PyCQA/astroid | astroid/inference.py | _infer_binop | def _infer_binop(self, context):
"""Binary operation inference logic."""
left = self.left
right = self.right
# we use two separate contexts for evaluating lhs and rhs because
# 1. evaluating lhs may leave some undesired entries in context.path
# which may not let us infer right value of rhs
context = context or contextmod.InferenceContext()
lhs_context = contextmod.copy_context(context)
rhs_context = contextmod.copy_context(context)
lhs_iter = left.infer(context=lhs_context)
rhs_iter = right.infer(context=rhs_context)
for lhs, rhs in itertools.product(lhs_iter, rhs_iter):
if any(value is util.Uninferable for value in (rhs, lhs)):
# Don't know how to process this.
yield util.Uninferable
return
try:
yield from _infer_binary_operation(lhs, rhs, self, context, _get_binop_flow)
except exceptions._NonDeducibleTypeHierarchy:
yield util.Uninferable | python | def _infer_binop(self, context):
left = self.left
right = self.right
# we use two separate contexts for evaluating lhs and rhs because
# 1. evaluating lhs may leave some undesired entries in context.path
# which may not let us infer right value of rhs
context = context or contextmod.InferenceContext()
lhs_context = contextmod.copy_context(context)
rhs_context = contextmod.copy_context(context)
lhs_iter = left.infer(context=lhs_context)
rhs_iter = right.infer(context=rhs_context)
for lhs, rhs in itertools.product(lhs_iter, rhs_iter):
if any(value is util.Uninferable for value in (rhs, lhs)):
# Don't know how to process this.
yield util.Uninferable
return
try:
yield from _infer_binary_operation(lhs, rhs, self, context, _get_binop_flow)
except exceptions._NonDeducibleTypeHierarchy:
yield util.Uninferable | [
"def",
"_infer_binop",
"(",
"self",
",",
"context",
")",
":",
"left",
"=",
"self",
".",
"left",
"right",
"=",
"self",
".",
"right",
"# we use two separate contexts for evaluating lhs and rhs because",
"# 1. evaluating lhs may leave some undesired entries in context.path",
"# ... | Binary operation inference logic. | [
"Binary",
"operation",
"inference",
"logic",
"."
] | e0a298df55b15abcb77c2a93253f5ab7be52d0fb | https://github.com/PyCQA/astroid/blob/e0a298df55b15abcb77c2a93253f5ab7be52d0fb/astroid/inference.py#L733-L755 |
227,217 | PyCQA/astroid | astroid/inference.py | _infer_augassign | def _infer_augassign(self, context=None):
"""Inference logic for augmented binary operations."""
if context is None:
context = contextmod.InferenceContext()
rhs_context = context.clone()
lhs_iter = self.target.infer_lhs(context=context)
rhs_iter = self.value.infer(context=rhs_context)
for lhs, rhs in itertools.product(lhs_iter, rhs_iter):
if any(value is util.Uninferable for value in (rhs, lhs)):
# Don't know how to process this.
yield util.Uninferable
return
try:
yield from _infer_binary_operation(
left=lhs,
right=rhs,
binary_opnode=self,
context=context,
flow_factory=_get_aug_flow,
)
except exceptions._NonDeducibleTypeHierarchy:
yield util.Uninferable | python | def _infer_augassign(self, context=None):
if context is None:
context = contextmod.InferenceContext()
rhs_context = context.clone()
lhs_iter = self.target.infer_lhs(context=context)
rhs_iter = self.value.infer(context=rhs_context)
for lhs, rhs in itertools.product(lhs_iter, rhs_iter):
if any(value is util.Uninferable for value in (rhs, lhs)):
# Don't know how to process this.
yield util.Uninferable
return
try:
yield from _infer_binary_operation(
left=lhs,
right=rhs,
binary_opnode=self,
context=context,
flow_factory=_get_aug_flow,
)
except exceptions._NonDeducibleTypeHierarchy:
yield util.Uninferable | [
"def",
"_infer_augassign",
"(",
"self",
",",
"context",
"=",
"None",
")",
":",
"if",
"context",
"is",
"None",
":",
"context",
"=",
"contextmod",
".",
"InferenceContext",
"(",
")",
"rhs_context",
"=",
"context",
".",
"clone",
"(",
")",
"lhs_iter",
"=",
"s... | Inference logic for augmented binary operations. | [
"Inference",
"logic",
"for",
"augmented",
"binary",
"operations",
"."
] | e0a298df55b15abcb77c2a93253f5ab7be52d0fb | https://github.com/PyCQA/astroid/blob/e0a298df55b15abcb77c2a93253f5ab7be52d0fb/astroid/inference.py#L770-L794 |
227,218 | PyCQA/astroid | astroid/brain/brain_nose.py | _nose_tools_functions | def _nose_tools_functions():
"""Get an iterator of names and bound methods."""
module = _BUILDER.string_build(
textwrap.dedent(
"""
import unittest
class Test(unittest.TestCase):
pass
a = Test()
"""
)
)
try:
case = next(module["a"].infer())
except astroid.InferenceError:
return
for method in case.methods():
if method.name.startswith("assert") and "_" not in method.name:
pep8_name = _pep8(method.name)
yield pep8_name, astroid.BoundMethod(method, case)
if method.name == "assertEqual":
# nose also exports assert_equals.
yield "assert_equals", astroid.BoundMethod(method, case) | python | def _nose_tools_functions():
module = _BUILDER.string_build(
textwrap.dedent(
"""
import unittest
class Test(unittest.TestCase):
pass
a = Test()
"""
)
)
try:
case = next(module["a"].infer())
except astroid.InferenceError:
return
for method in case.methods():
if method.name.startswith("assert") and "_" not in method.name:
pep8_name = _pep8(method.name)
yield pep8_name, astroid.BoundMethod(method, case)
if method.name == "assertEqual":
# nose also exports assert_equals.
yield "assert_equals", astroid.BoundMethod(method, case) | [
"def",
"_nose_tools_functions",
"(",
")",
":",
"module",
"=",
"_BUILDER",
".",
"string_build",
"(",
"textwrap",
".",
"dedent",
"(",
"\"\"\"\n import unittest\n\n class Test(unittest.TestCase):\n pass\n a = Test()\n \"\"\"",
")",
")",
"try",
":",
"case",
"... | Get an iterator of names and bound methods. | [
"Get",
"an",
"iterator",
"of",
"names",
"and",
"bound",
"methods",
"."
] | e0a298df55b15abcb77c2a93253f5ab7be52d0fb | https://github.com/PyCQA/astroid/blob/e0a298df55b15abcb77c2a93253f5ab7be52d0fb/astroid/brain/brain_nose.py#L23-L46 |
227,219 | PyCQA/astroid | astroid/brain/brain_nose.py | _nose_tools_trivial_transform | def _nose_tools_trivial_transform():
"""Custom transform for the nose.tools module."""
stub = _BUILDER.string_build("""__all__ = []""")
all_entries = ["ok_", "eq_"]
for pep8_name, method in _nose_tools_functions():
all_entries.append(pep8_name)
stub[pep8_name] = method
# Update the __all__ variable, since nose.tools
# does this manually with .append.
all_assign = stub["__all__"].parent
all_object = astroid.List(all_entries)
all_object.parent = all_assign
all_assign.value = all_object
return stub | python | def _nose_tools_trivial_transform():
stub = _BUILDER.string_build("""__all__ = []""")
all_entries = ["ok_", "eq_"]
for pep8_name, method in _nose_tools_functions():
all_entries.append(pep8_name)
stub[pep8_name] = method
# Update the __all__ variable, since nose.tools
# does this manually with .append.
all_assign = stub["__all__"].parent
all_object = astroid.List(all_entries)
all_object.parent = all_assign
all_assign.value = all_object
return stub | [
"def",
"_nose_tools_trivial_transform",
"(",
")",
":",
"stub",
"=",
"_BUILDER",
".",
"string_build",
"(",
"\"\"\"__all__ = []\"\"\"",
")",
"all_entries",
"=",
"[",
"\"ok_\"",
",",
"\"eq_\"",
"]",
"for",
"pep8_name",
",",
"method",
"in",
"_nose_tools_functions",
"(... | Custom transform for the nose.tools module. | [
"Custom",
"transform",
"for",
"the",
"nose",
".",
"tools",
"module",
"."
] | e0a298df55b15abcb77c2a93253f5ab7be52d0fb | https://github.com/PyCQA/astroid/blob/e0a298df55b15abcb77c2a93253f5ab7be52d0fb/astroid/brain/brain_nose.py#L54-L69 |
227,220 | PyCQA/astroid | astroid/brain/brain_numpy.py | _looks_like_numpy_function | def _looks_like_numpy_function(func_name, numpy_module_name, node):
"""
Return True if the current node correspond to the function inside
the numpy module in parameters
:param node: the current node
:type node: FunctionDef
:param func_name: name of the function
:type func_name: str
:param numpy_module_name: name of the numpy module
:type numpy_module_name: str
:return: True if the current node correspond to the function looked for
:rtype: bool
"""
return node.name == func_name and node.parent.name == numpy_module_name | python | def _looks_like_numpy_function(func_name, numpy_module_name, node):
return node.name == func_name and node.parent.name == numpy_module_name | [
"def",
"_looks_like_numpy_function",
"(",
"func_name",
",",
"numpy_module_name",
",",
"node",
")",
":",
"return",
"node",
".",
"name",
"==",
"func_name",
"and",
"node",
".",
"parent",
".",
"name",
"==",
"numpy_module_name"
] | Return True if the current node correspond to the function inside
the numpy module in parameters
:param node: the current node
:type node: FunctionDef
:param func_name: name of the function
:type func_name: str
:param numpy_module_name: name of the numpy module
:type numpy_module_name: str
:return: True if the current node correspond to the function looked for
:rtype: bool | [
"Return",
"True",
"if",
"the",
"current",
"node",
"correspond",
"to",
"the",
"function",
"inside",
"the",
"numpy",
"module",
"in",
"parameters"
] | e0a298df55b15abcb77c2a93253f5ab7be52d0fb | https://github.com/PyCQA/astroid/blob/e0a298df55b15abcb77c2a93253f5ab7be52d0fb/astroid/brain/brain_numpy.py#L485-L499 |
227,221 | PyCQA/astroid | astroid/brain/brain_numpy.py | numpy_function_infer_call_result | def numpy_function_infer_call_result(node):
"""
A wrapper around infer_call_result method bounded to the node.
:param node: the node which infer_call_result should be filtered
:type node: FunctionDef
:return: a function that filter the results of the call to node.infer_call_result
:rtype: function
"""
# Put the origin infer_call_result method into the closure
origin_infer_call_result = node.infer_call_result
def infer_call_result_wrapper(caller=None, context=None):
"""
Call the origin infer_call_result method bounded to the node instance and
filter the results to remove List and Tuple instances
"""
unfiltered_infer_call_result = origin_infer_call_result(caller, context)
return (
x
for x in unfiltered_infer_call_result
if not isinstance(x, (astroid.List, astroid.Tuple))
)
return infer_call_result_wrapper | python | def numpy_function_infer_call_result(node):
# Put the origin infer_call_result method into the closure
origin_infer_call_result = node.infer_call_result
def infer_call_result_wrapper(caller=None, context=None):
"""
Call the origin infer_call_result method bounded to the node instance and
filter the results to remove List and Tuple instances
"""
unfiltered_infer_call_result = origin_infer_call_result(caller, context)
return (
x
for x in unfiltered_infer_call_result
if not isinstance(x, (astroid.List, astroid.Tuple))
)
return infer_call_result_wrapper | [
"def",
"numpy_function_infer_call_result",
"(",
"node",
")",
":",
"# Put the origin infer_call_result method into the closure",
"origin_infer_call_result",
"=",
"node",
".",
"infer_call_result",
"def",
"infer_call_result_wrapper",
"(",
"caller",
"=",
"None",
",",
"context",
... | A wrapper around infer_call_result method bounded to the node.
:param node: the node which infer_call_result should be filtered
:type node: FunctionDef
:return: a function that filter the results of the call to node.infer_call_result
:rtype: function | [
"A",
"wrapper",
"around",
"infer_call_result",
"method",
"bounded",
"to",
"the",
"node",
"."
] | e0a298df55b15abcb77c2a93253f5ab7be52d0fb | https://github.com/PyCQA/astroid/blob/e0a298df55b15abcb77c2a93253f5ab7be52d0fb/astroid/brain/brain_numpy.py#L502-L526 |
227,222 | PyCQA/astroid | astroid/node_classes.py | unpack_infer | def unpack_infer(stmt, context=None):
"""recursively generate nodes inferred by the given statement.
If the inferred value is a list or a tuple, recurse on the elements
"""
if isinstance(stmt, (List, Tuple)):
for elt in stmt.elts:
if elt is util.Uninferable:
yield elt
continue
yield from unpack_infer(elt, context)
return dict(node=stmt, context=context)
# if inferred is a final node, return it and stop
inferred = next(stmt.infer(context))
if inferred is stmt:
yield inferred
return dict(node=stmt, context=context)
# else, infer recursively, except Uninferable object that should be returned as is
for inferred in stmt.infer(context):
if inferred is util.Uninferable:
yield inferred
else:
yield from unpack_infer(inferred, context)
return dict(node=stmt, context=context) | python | def unpack_infer(stmt, context=None):
if isinstance(stmt, (List, Tuple)):
for elt in stmt.elts:
if elt is util.Uninferable:
yield elt
continue
yield from unpack_infer(elt, context)
return dict(node=stmt, context=context)
# if inferred is a final node, return it and stop
inferred = next(stmt.infer(context))
if inferred is stmt:
yield inferred
return dict(node=stmt, context=context)
# else, infer recursively, except Uninferable object that should be returned as is
for inferred in stmt.infer(context):
if inferred is util.Uninferable:
yield inferred
else:
yield from unpack_infer(inferred, context)
return dict(node=stmt, context=context) | [
"def",
"unpack_infer",
"(",
"stmt",
",",
"context",
"=",
"None",
")",
":",
"if",
"isinstance",
"(",
"stmt",
",",
"(",
"List",
",",
"Tuple",
")",
")",
":",
"for",
"elt",
"in",
"stmt",
".",
"elts",
":",
"if",
"elt",
"is",
"util",
".",
"Uninferable",
... | recursively generate nodes inferred by the given statement.
If the inferred value is a list or a tuple, recurse on the elements | [
"recursively",
"generate",
"nodes",
"inferred",
"by",
"the",
"given",
"statement",
".",
"If",
"the",
"inferred",
"value",
"is",
"a",
"list",
"or",
"a",
"tuple",
"recurse",
"on",
"the",
"elements"
] | e0a298df55b15abcb77c2a93253f5ab7be52d0fb | https://github.com/PyCQA/astroid/blob/e0a298df55b15abcb77c2a93253f5ab7be52d0fb/astroid/node_classes.py#L56-L79 |
227,223 | PyCQA/astroid | astroid/node_classes.py | are_exclusive | def are_exclusive(
stmt1, stmt2, exceptions=None
): # pylint: disable=redefined-outer-name
"""return true if the two given statements are mutually exclusive
`exceptions` may be a list of exception names. If specified, discard If
branches and check one of the statement is in an exception handler catching
one of the given exceptions.
algorithm :
1) index stmt1's parents
2) climb among stmt2's parents until we find a common parent
3) if the common parent is a If or TryExcept statement, look if nodes are
in exclusive branches
"""
# index stmt1's parents
stmt1_parents = {}
children = {}
node = stmt1.parent
previous = stmt1
while node:
stmt1_parents[node] = 1
children[node] = previous
previous = node
node = node.parent
# climb among stmt2's parents until we find a common parent
node = stmt2.parent
previous = stmt2
while node:
if node in stmt1_parents:
# if the common parent is a If or TryExcept statement, look if
# nodes are in exclusive branches
if isinstance(node, If) and exceptions is None:
if (
node.locate_child(previous)[1]
is not node.locate_child(children[node])[1]
):
return True
elif isinstance(node, TryExcept):
c2attr, c2node = node.locate_child(previous)
c1attr, c1node = node.locate_child(children[node])
if c1node is not c2node:
first_in_body_caught_by_handlers = (
c2attr == "handlers"
and c1attr == "body"
and previous.catch(exceptions)
)
second_in_body_caught_by_handlers = (
c2attr == "body"
and c1attr == "handlers"
and children[node].catch(exceptions)
)
first_in_else_other_in_handlers = (
c2attr == "handlers" and c1attr == "orelse"
)
second_in_else_other_in_handlers = (
c2attr == "orelse" and c1attr == "handlers"
)
if any(
(
first_in_body_caught_by_handlers,
second_in_body_caught_by_handlers,
first_in_else_other_in_handlers,
second_in_else_other_in_handlers,
)
):
return True
elif c2attr == "handlers" and c1attr == "handlers":
return previous is not children[node]
return False
previous = node
node = node.parent
return False | python | def are_exclusive(
stmt1, stmt2, exceptions=None
): # pylint: disable=redefined-outer-name
# index stmt1's parents
stmt1_parents = {}
children = {}
node = stmt1.parent
previous = stmt1
while node:
stmt1_parents[node] = 1
children[node] = previous
previous = node
node = node.parent
# climb among stmt2's parents until we find a common parent
node = stmt2.parent
previous = stmt2
while node:
if node in stmt1_parents:
# if the common parent is a If or TryExcept statement, look if
# nodes are in exclusive branches
if isinstance(node, If) and exceptions is None:
if (
node.locate_child(previous)[1]
is not node.locate_child(children[node])[1]
):
return True
elif isinstance(node, TryExcept):
c2attr, c2node = node.locate_child(previous)
c1attr, c1node = node.locate_child(children[node])
if c1node is not c2node:
first_in_body_caught_by_handlers = (
c2attr == "handlers"
and c1attr == "body"
and previous.catch(exceptions)
)
second_in_body_caught_by_handlers = (
c2attr == "body"
and c1attr == "handlers"
and children[node].catch(exceptions)
)
first_in_else_other_in_handlers = (
c2attr == "handlers" and c1attr == "orelse"
)
second_in_else_other_in_handlers = (
c2attr == "orelse" and c1attr == "handlers"
)
if any(
(
first_in_body_caught_by_handlers,
second_in_body_caught_by_handlers,
first_in_else_other_in_handlers,
second_in_else_other_in_handlers,
)
):
return True
elif c2attr == "handlers" and c1attr == "handlers":
return previous is not children[node]
return False
previous = node
node = node.parent
return False | [
"def",
"are_exclusive",
"(",
"stmt1",
",",
"stmt2",
",",
"exceptions",
"=",
"None",
")",
":",
"# pylint: disable=redefined-outer-name",
"# index stmt1's parents",
"stmt1_parents",
"=",
"{",
"}",
"children",
"=",
"{",
"}",
"node",
"=",
"stmt1",
".",
"parent",
"pr... | return true if the two given statements are mutually exclusive
`exceptions` may be a list of exception names. If specified, discard If
branches and check one of the statement is in an exception handler catching
one of the given exceptions.
algorithm :
1) index stmt1's parents
2) climb among stmt2's parents until we find a common parent
3) if the common parent is a If or TryExcept statement, look if nodes are
in exclusive branches | [
"return",
"true",
"if",
"the",
"two",
"given",
"statements",
"are",
"mutually",
"exclusive"
] | e0a298df55b15abcb77c2a93253f5ab7be52d0fb | https://github.com/PyCQA/astroid/blob/e0a298df55b15abcb77c2a93253f5ab7be52d0fb/astroid/node_classes.py#L82-L154 |
227,224 | PyCQA/astroid | astroid/node_classes.py | _slice_value | def _slice_value(index, context=None):
"""Get the value of the given slice index."""
if isinstance(index, Const):
if isinstance(index.value, (int, type(None))):
return index.value
elif index is None:
return None
else:
# Try to infer what the index actually is.
# Since we can't return all the possible values,
# we'll stop at the first possible value.
try:
inferred = next(index.infer(context=context))
except exceptions.InferenceError:
pass
else:
if isinstance(inferred, Const):
if isinstance(inferred.value, (int, type(None))):
return inferred.value
# Use a sentinel, because None can be a valid
# value that this function can return,
# as it is the case for unspecified bounds.
return _SLICE_SENTINEL | python | def _slice_value(index, context=None):
if isinstance(index, Const):
if isinstance(index.value, (int, type(None))):
return index.value
elif index is None:
return None
else:
# Try to infer what the index actually is.
# Since we can't return all the possible values,
# we'll stop at the first possible value.
try:
inferred = next(index.infer(context=context))
except exceptions.InferenceError:
pass
else:
if isinstance(inferred, Const):
if isinstance(inferred.value, (int, type(None))):
return inferred.value
# Use a sentinel, because None can be a valid
# value that this function can return,
# as it is the case for unspecified bounds.
return _SLICE_SENTINEL | [
"def",
"_slice_value",
"(",
"index",
",",
"context",
"=",
"None",
")",
":",
"if",
"isinstance",
"(",
"index",
",",
"Const",
")",
":",
"if",
"isinstance",
"(",
"index",
".",
"value",
",",
"(",
"int",
",",
"type",
"(",
"None",
")",
")",
")",
":",
"... | Get the value of the given slice index. | [
"Get",
"the",
"value",
"of",
"the",
"given",
"slice",
"index",
"."
] | e0a298df55b15abcb77c2a93253f5ab7be52d0fb | https://github.com/PyCQA/astroid/blob/e0a298df55b15abcb77c2a93253f5ab7be52d0fb/astroid/node_classes.py#L162-L186 |
227,225 | PyCQA/astroid | astroid/node_classes.py | _update_const_classes | def _update_const_classes():
"""update constant classes, so the keys of CONST_CLS can be reused"""
klasses = (bool, int, float, complex, str, bytes)
for kls in klasses:
CONST_CLS[kls] = Const | python | def _update_const_classes():
klasses = (bool, int, float, complex, str, bytes)
for kls in klasses:
CONST_CLS[kls] = Const | [
"def",
"_update_const_classes",
"(",
")",
":",
"klasses",
"=",
"(",
"bool",
",",
"int",
",",
"float",
",",
"complex",
",",
"str",
",",
"bytes",
")",
"for",
"kls",
"in",
"klasses",
":",
"CONST_CLS",
"[",
"kls",
"]",
"=",
"Const"
] | update constant classes, so the keys of CONST_CLS can be reused | [
"update",
"constant",
"classes",
"so",
"the",
"keys",
"of",
"CONST_CLS",
"can",
"be",
"reused"
] | e0a298df55b15abcb77c2a93253f5ab7be52d0fb | https://github.com/PyCQA/astroid/blob/e0a298df55b15abcb77c2a93253f5ab7be52d0fb/astroid/node_classes.py#L4638-L4642 |
227,226 | PyCQA/astroid | astroid/node_classes.py | const_factory | def const_factory(value):
"""return an astroid node for a python value"""
# XXX we should probably be stricter here and only consider stuff in
# CONST_CLS or do better treatment: in case where value is not in CONST_CLS,
# we should rather recall the builder on this value than returning an empty
# node (another option being that const_factory shouldn't be called with something
# not in CONST_CLS)
assert not isinstance(value, NodeNG)
# Hack for ignoring elements of a sequence
# or a mapping, in order to avoid transforming
# each element to an AST. This is fixed in 2.0
# and this approach is a temporary hack.
if isinstance(value, (list, set, tuple, dict)):
elts = []
else:
elts = value
try:
initializer_cls = CONST_CLS[value.__class__]
initializer = _CONST_CLS_CONSTRUCTORS[initializer_cls]
return initializer(initializer_cls, elts)
except (KeyError, AttributeError):
node = EmptyNode()
node.object = value
return node | python | def const_factory(value):
# XXX we should probably be stricter here and only consider stuff in
# CONST_CLS or do better treatment: in case where value is not in CONST_CLS,
# we should rather recall the builder on this value than returning an empty
# node (another option being that const_factory shouldn't be called with something
# not in CONST_CLS)
assert not isinstance(value, NodeNG)
# Hack for ignoring elements of a sequence
# or a mapping, in order to avoid transforming
# each element to an AST. This is fixed in 2.0
# and this approach is a temporary hack.
if isinstance(value, (list, set, tuple, dict)):
elts = []
else:
elts = value
try:
initializer_cls = CONST_CLS[value.__class__]
initializer = _CONST_CLS_CONSTRUCTORS[initializer_cls]
return initializer(initializer_cls, elts)
except (KeyError, AttributeError):
node = EmptyNode()
node.object = value
return node | [
"def",
"const_factory",
"(",
"value",
")",
":",
"# XXX we should probably be stricter here and only consider stuff in",
"# CONST_CLS or do better treatment: in case where value is not in CONST_CLS,",
"# we should rather recall the builder on this value than returning an empty",
"# node (another op... | return an astroid node for a python value | [
"return",
"an",
"astroid",
"node",
"for",
"a",
"python",
"value"
] | e0a298df55b15abcb77c2a93253f5ab7be52d0fb | https://github.com/PyCQA/astroid/blob/e0a298df55b15abcb77c2a93253f5ab7be52d0fb/astroid/node_classes.py#L4669-L4694 |
227,227 | PyCQA/astroid | astroid/node_classes.py | is_from_decorator | def is_from_decorator(node):
"""Return True if the given node is the child of a decorator"""
parent = node.parent
while parent is not None:
if isinstance(parent, Decorators):
return True
parent = parent.parent
return False | python | def is_from_decorator(node):
parent = node.parent
while parent is not None:
if isinstance(parent, Decorators):
return True
parent = parent.parent
return False | [
"def",
"is_from_decorator",
"(",
"node",
")",
":",
"parent",
"=",
"node",
".",
"parent",
"while",
"parent",
"is",
"not",
"None",
":",
"if",
"isinstance",
"(",
"parent",
",",
"Decorators",
")",
":",
"return",
"True",
"parent",
"=",
"parent",
".",
"parent"... | Return True if the given node is the child of a decorator | [
"Return",
"True",
"if",
"the",
"given",
"node",
"is",
"the",
"child",
"of",
"a",
"decorator"
] | e0a298df55b15abcb77c2a93253f5ab7be52d0fb | https://github.com/PyCQA/astroid/blob/e0a298df55b15abcb77c2a93253f5ab7be52d0fb/astroid/node_classes.py#L4697-L4704 |
227,228 | PyCQA/astroid | astroid/node_classes.py | NodeNG.infer | def infer(self, context=None, **kwargs):
"""Get a generator of the inferred values.
This is the main entry point to the inference system.
.. seealso:: :ref:`inference`
If the instance has some explicit inference function set, it will be
called instead of the default interface.
:returns: The inferred values.
:rtype: iterable
"""
if context is not None:
context = context.extra_context.get(self, context)
if self._explicit_inference is not None:
# explicit_inference is not bound, give it self explicitly
try:
# pylint: disable=not-callable
return self._explicit_inference(self, context, **kwargs)
except exceptions.UseInferenceDefault:
pass
if not context:
return self._infer(context, **kwargs)
key = (self, context.lookupname, context.callcontext, context.boundnode)
if key in context.inferred:
return iter(context.inferred[key])
gen = context.cache_generator(key, self._infer(context, **kwargs))
return util.limit_inference(gen, MANAGER.max_inferable_values) | python | def infer(self, context=None, **kwargs):
if context is not None:
context = context.extra_context.get(self, context)
if self._explicit_inference is not None:
# explicit_inference is not bound, give it self explicitly
try:
# pylint: disable=not-callable
return self._explicit_inference(self, context, **kwargs)
except exceptions.UseInferenceDefault:
pass
if not context:
return self._infer(context, **kwargs)
key = (self, context.lookupname, context.callcontext, context.boundnode)
if key in context.inferred:
return iter(context.inferred[key])
gen = context.cache_generator(key, self._infer(context, **kwargs))
return util.limit_inference(gen, MANAGER.max_inferable_values) | [
"def",
"infer",
"(",
"self",
",",
"context",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"context",
"is",
"not",
"None",
":",
"context",
"=",
"context",
".",
"extra_context",
".",
"get",
"(",
"self",
",",
"context",
")",
"if",
"self",
"."... | Get a generator of the inferred values.
This is the main entry point to the inference system.
.. seealso:: :ref:`inference`
If the instance has some explicit inference function set, it will be
called instead of the default interface.
:returns: The inferred values.
:rtype: iterable | [
"Get",
"a",
"generator",
"of",
"the",
"inferred",
"values",
"."
] | e0a298df55b15abcb77c2a93253f5ab7be52d0fb | https://github.com/PyCQA/astroid/blob/e0a298df55b15abcb77c2a93253f5ab7be52d0fb/astroid/node_classes.py#L333-L364 |
227,229 | PyCQA/astroid | astroid/node_classes.py | NodeNG._repr_name | def _repr_name(self):
"""Get a name for nice representation.
This is either :attr:`name`, :attr:`attrname`, or the empty string.
:returns: The nice name.
:rtype: str
"""
names = {"name", "attrname"}
if all(name not in self._astroid_fields for name in names):
return getattr(self, "name", getattr(self, "attrname", ""))
return "" | python | def _repr_name(self):
names = {"name", "attrname"}
if all(name not in self._astroid_fields for name in names):
return getattr(self, "name", getattr(self, "attrname", ""))
return "" | [
"def",
"_repr_name",
"(",
"self",
")",
":",
"names",
"=",
"{",
"\"name\"",
",",
"\"attrname\"",
"}",
"if",
"all",
"(",
"name",
"not",
"in",
"self",
".",
"_astroid_fields",
"for",
"name",
"in",
"names",
")",
":",
"return",
"getattr",
"(",
"self",
",",
... | Get a name for nice representation.
This is either :attr:`name`, :attr:`attrname`, or the empty string.
:returns: The nice name.
:rtype: str | [
"Get",
"a",
"name",
"for",
"nice",
"representation",
"."
] | e0a298df55b15abcb77c2a93253f5ab7be52d0fb | https://github.com/PyCQA/astroid/blob/e0a298df55b15abcb77c2a93253f5ab7be52d0fb/astroid/node_classes.py#L366-L377 |
227,230 | PyCQA/astroid | astroid/node_classes.py | NodeNG.accept | def accept(self, visitor):
"""Visit this node using the given visitor."""
func = getattr(visitor, "visit_" + self.__class__.__name__.lower())
return func(self) | python | def accept(self, visitor):
func = getattr(visitor, "visit_" + self.__class__.__name__.lower())
return func(self) | [
"def",
"accept",
"(",
"self",
",",
"visitor",
")",
":",
"func",
"=",
"getattr",
"(",
"visitor",
",",
"\"visit_\"",
"+",
"self",
".",
"__class__",
".",
"__name__",
".",
"lower",
"(",
")",
")",
"return",
"func",
"(",
"self",
")"
] | Visit this node using the given visitor. | [
"Visit",
"this",
"node",
"using",
"the",
"given",
"visitor",
"."
] | e0a298df55b15abcb77c2a93253f5ab7be52d0fb | https://github.com/PyCQA/astroid/blob/e0a298df55b15abcb77c2a93253f5ab7be52d0fb/astroid/node_classes.py#L418-L421 |
227,231 | PyCQA/astroid | astroid/node_classes.py | NodeNG.parent_of | def parent_of(self, node):
"""Check if this node is the parent of the given node.
:param node: The node to check if it is the child.
:type node: NodeNG
:returns: True if this node is the parent of the given node,
False otherwise.
:rtype: bool
"""
parent = node.parent
while parent is not None:
if self is parent:
return True
parent = parent.parent
return False | python | def parent_of(self, node):
parent = node.parent
while parent is not None:
if self is parent:
return True
parent = parent.parent
return False | [
"def",
"parent_of",
"(",
"self",
",",
"node",
")",
":",
"parent",
"=",
"node",
".",
"parent",
"while",
"parent",
"is",
"not",
"None",
":",
"if",
"self",
"is",
"parent",
":",
"return",
"True",
"parent",
"=",
"parent",
".",
"parent",
"return",
"False"
] | Check if this node is the parent of the given node.
:param node: The node to check if it is the child.
:type node: NodeNG
:returns: True if this node is the parent of the given node,
False otherwise.
:rtype: bool | [
"Check",
"if",
"this",
"node",
"is",
"the",
"parent",
"of",
"the",
"given",
"node",
"."
] | e0a298df55b15abcb77c2a93253f5ab7be52d0fb | https://github.com/PyCQA/astroid/blob/e0a298df55b15abcb77c2a93253f5ab7be52d0fb/astroid/node_classes.py#L454-L469 |
227,232 | PyCQA/astroid | astroid/node_classes.py | NodeNG.child_sequence | def child_sequence(self, child):
"""Search for the sequence that contains this child.
:param child: The child node to search sequences for.
:type child: NodeNG
:returns: The sequence containing the given child node.
:rtype: iterable(NodeNG)
:raises AstroidError: If no sequence could be found that contains
the given child.
"""
for field in self._astroid_fields:
node_or_sequence = getattr(self, field)
if node_or_sequence is child:
return [node_or_sequence]
# /!\ compiler.ast Nodes have an __iter__ walking over child nodes
if (
isinstance(node_or_sequence, (tuple, list))
and child in node_or_sequence
):
return node_or_sequence
msg = "Could not find %s in %s's children"
raise exceptions.AstroidError(msg % (repr(child), repr(self))) | python | def child_sequence(self, child):
for field in self._astroid_fields:
node_or_sequence = getattr(self, field)
if node_or_sequence is child:
return [node_or_sequence]
# /!\ compiler.ast Nodes have an __iter__ walking over child nodes
if (
isinstance(node_or_sequence, (tuple, list))
and child in node_or_sequence
):
return node_or_sequence
msg = "Could not find %s in %s's children"
raise exceptions.AstroidError(msg % (repr(child), repr(self))) | [
"def",
"child_sequence",
"(",
"self",
",",
"child",
")",
":",
"for",
"field",
"in",
"self",
".",
"_astroid_fields",
":",
"node_or_sequence",
"=",
"getattr",
"(",
"self",
",",
"field",
")",
"if",
"node_or_sequence",
"is",
"child",
":",
"return",
"[",
"node_... | Search for the sequence that contains this child.
:param child: The child node to search sequences for.
:type child: NodeNG
:returns: The sequence containing the given child node.
:rtype: iterable(NodeNG)
:raises AstroidError: If no sequence could be found that contains
the given child. | [
"Search",
"for",
"the",
"sequence",
"that",
"contains",
"this",
"child",
"."
] | e0a298df55b15abcb77c2a93253f5ab7be52d0fb | https://github.com/PyCQA/astroid/blob/e0a298df55b15abcb77c2a93253f5ab7be52d0fb/astroid/node_classes.py#L510-L534 |
227,233 | PyCQA/astroid | astroid/node_classes.py | NodeNG.nearest | def nearest(self, nodes):
"""Get the node closest to this one from the given list of nodes.
:param nodes: The list of nodes to search. All of these nodes must
belong to the same module as this one. The list should be
sorted by the line number of the nodes, smallest first.
:type nodes: iterable(NodeNG)
:returns: The node closest to this one in the source code,
or None if one could not be found.
:rtype: NodeNG or None
"""
myroot = self.root()
mylineno = self.fromlineno
nearest = None, 0
for node in nodes:
assert node.root() is myroot, (
"nodes %s and %s are not from the same module" % (self, node)
)
lineno = node.fromlineno
if node.fromlineno > mylineno:
break
if lineno > nearest[1]:
nearest = node, lineno
# FIXME: raise an exception if nearest is None ?
return nearest[0] | python | def nearest(self, nodes):
myroot = self.root()
mylineno = self.fromlineno
nearest = None, 0
for node in nodes:
assert node.root() is myroot, (
"nodes %s and %s are not from the same module" % (self, node)
)
lineno = node.fromlineno
if node.fromlineno > mylineno:
break
if lineno > nearest[1]:
nearest = node, lineno
# FIXME: raise an exception if nearest is None ?
return nearest[0] | [
"def",
"nearest",
"(",
"self",
",",
"nodes",
")",
":",
"myroot",
"=",
"self",
".",
"root",
"(",
")",
"mylineno",
"=",
"self",
".",
"fromlineno",
"nearest",
"=",
"None",
",",
"0",
"for",
"node",
"in",
"nodes",
":",
"assert",
"node",
".",
"root",
"("... | Get the node closest to this one from the given list of nodes.
:param nodes: The list of nodes to search. All of these nodes must
belong to the same module as this one. The list should be
sorted by the line number of the nodes, smallest first.
:type nodes: iterable(NodeNG)
:returns: The node closest to this one in the source code,
or None if one could not be found.
:rtype: NodeNG or None | [
"Get",
"the",
"node",
"closest",
"to",
"this",
"one",
"from",
"the",
"given",
"list",
"of",
"nodes",
"."
] | e0a298df55b15abcb77c2a93253f5ab7be52d0fb | https://github.com/PyCQA/astroid/blob/e0a298df55b15abcb77c2a93253f5ab7be52d0fb/astroid/node_classes.py#L581-L606 |
227,234 | PyCQA/astroid | astroid/node_classes.py | NodeNG.tolineno | def tolineno(self):
"""The last line that this node appears on in the source code.
:type: int or None
"""
if not self._astroid_fields:
# can't have children
lastchild = None
else:
lastchild = self.last_child()
if lastchild is None:
return self.fromlineno
return lastchild.tolineno | python | def tolineno(self):
if not self._astroid_fields:
# can't have children
lastchild = None
else:
lastchild = self.last_child()
if lastchild is None:
return self.fromlineno
return lastchild.tolineno | [
"def",
"tolineno",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"_astroid_fields",
":",
"# can't have children",
"lastchild",
"=",
"None",
"else",
":",
"lastchild",
"=",
"self",
".",
"last_child",
"(",
")",
"if",
"lastchild",
"is",
"None",
":",
"return... | The last line that this node appears on in the source code.
:type: int or None | [
"The",
"last",
"line",
"that",
"this",
"node",
"appears",
"on",
"in",
"the",
"source",
"code",
"."
] | e0a298df55b15abcb77c2a93253f5ab7be52d0fb | https://github.com/PyCQA/astroid/blob/e0a298df55b15abcb77c2a93253f5ab7be52d0fb/astroid/node_classes.py#L623-L636 |
227,235 | PyCQA/astroid | astroid/node_classes.py | NodeNG._fixed_source_line | def _fixed_source_line(self):
"""Attempt to find the line that this node appears on.
We need this method since not all nodes have :attr:`lineno` set.
:returns: The line number of this node,
or None if this could not be determined.
:rtype: int or None
"""
line = self.lineno
_node = self
try:
while line is None:
_node = next(_node.get_children())
line = _node.lineno
except StopIteration:
_node = self.parent
while _node and line is None:
line = _node.lineno
_node = _node.parent
return line | python | def _fixed_source_line(self):
line = self.lineno
_node = self
try:
while line is None:
_node = next(_node.get_children())
line = _node.lineno
except StopIteration:
_node = self.parent
while _node and line is None:
line = _node.lineno
_node = _node.parent
return line | [
"def",
"_fixed_source_line",
"(",
"self",
")",
":",
"line",
"=",
"self",
".",
"lineno",
"_node",
"=",
"self",
"try",
":",
"while",
"line",
"is",
"None",
":",
"_node",
"=",
"next",
"(",
"_node",
".",
"get_children",
"(",
")",
")",
"line",
"=",
"_node"... | Attempt to find the line that this node appears on.
We need this method since not all nodes have :attr:`lineno` set.
:returns: The line number of this node,
or None if this could not be determined.
:rtype: int or None | [
"Attempt",
"to",
"find",
"the",
"line",
"that",
"this",
"node",
"appears",
"on",
"."
] | e0a298df55b15abcb77c2a93253f5ab7be52d0fb | https://github.com/PyCQA/astroid/blob/e0a298df55b15abcb77c2a93253f5ab7be52d0fb/astroid/node_classes.py#L638-L658 |
227,236 | PyCQA/astroid | astroid/node_classes.py | Statement.next_sibling | def next_sibling(self):
"""The next sibling statement node.
:returns: The next sibling statement node.
:rtype: NodeNG or None
"""
stmts = self.parent.child_sequence(self)
index = stmts.index(self)
try:
return stmts[index + 1]
except IndexError:
pass | python | def next_sibling(self):
stmts = self.parent.child_sequence(self)
index = stmts.index(self)
try:
return stmts[index + 1]
except IndexError:
pass | [
"def",
"next_sibling",
"(",
"self",
")",
":",
"stmts",
"=",
"self",
".",
"parent",
".",
"child_sequence",
"(",
"self",
")",
"index",
"=",
"stmts",
".",
"index",
"(",
"self",
")",
"try",
":",
"return",
"stmts",
"[",
"index",
"+",
"1",
"]",
"except",
... | The next sibling statement node.
:returns: The next sibling statement node.
:rtype: NodeNG or None | [
"The",
"next",
"sibling",
"statement",
"node",
"."
] | e0a298df55b15abcb77c2a93253f5ab7be52d0fb | https://github.com/PyCQA/astroid/blob/e0a298df55b15abcb77c2a93253f5ab7be52d0fb/astroid/node_classes.py#L962-L973 |
227,237 | PyCQA/astroid | astroid/node_classes.py | Statement.previous_sibling | def previous_sibling(self):
"""The previous sibling statement.
:returns: The previous sibling statement node.
:rtype: NodeNG or None
"""
stmts = self.parent.child_sequence(self)
index = stmts.index(self)
if index >= 1:
return stmts[index - 1]
return None | python | def previous_sibling(self):
stmts = self.parent.child_sequence(self)
index = stmts.index(self)
if index >= 1:
return stmts[index - 1]
return None | [
"def",
"previous_sibling",
"(",
"self",
")",
":",
"stmts",
"=",
"self",
".",
"parent",
".",
"child_sequence",
"(",
"self",
")",
"index",
"=",
"stmts",
".",
"index",
"(",
"self",
")",
"if",
"index",
">=",
"1",
":",
"return",
"stmts",
"[",
"index",
"-"... | The previous sibling statement.
:returns: The previous sibling statement node.
:rtype: NodeNG or None | [
"The",
"previous",
"sibling",
"statement",
"."
] | e0a298df55b15abcb77c2a93253f5ab7be52d0fb | https://github.com/PyCQA/astroid/blob/e0a298df55b15abcb77c2a93253f5ab7be52d0fb/astroid/node_classes.py#L975-L985 |
227,238 | PyCQA/astroid | astroid/node_classes.py | _BaseContainer.from_elements | def from_elements(cls, elts=None):
"""Create a node of this type from the given list of elements.
:param elts: The list of elements that the node should contain.
:type elts: list(NodeNG)
:returns: A new node containing the given elements.
:rtype: NodeNG
"""
node = cls()
if elts is None:
node.elts = []
else:
node.elts = [const_factory(e) if _is_const(e) else e for e in elts]
return node | python | def from_elements(cls, elts=None):
node = cls()
if elts is None:
node.elts = []
else:
node.elts = [const_factory(e) if _is_const(e) else e for e in elts]
return node | [
"def",
"from_elements",
"(",
"cls",
",",
"elts",
"=",
"None",
")",
":",
"node",
"=",
"cls",
"(",
")",
"if",
"elts",
"is",
"None",
":",
"node",
".",
"elts",
"=",
"[",
"]",
"else",
":",
"node",
".",
"elts",
"=",
"[",
"const_factory",
"(",
"e",
")... | Create a node of this type from the given list of elements.
:param elts: The list of elements that the node should contain.
:type elts: list(NodeNG)
:returns: A new node containing the given elements.
:rtype: NodeNG | [
"Create",
"a",
"node",
"of",
"this",
"type",
"from",
"the",
"given",
"list",
"of",
"elements",
"."
] | e0a298df55b15abcb77c2a93253f5ab7be52d0fb | https://github.com/PyCQA/astroid/blob/e0a298df55b15abcb77c2a93253f5ab7be52d0fb/astroid/node_classes.py#L1024-L1038 |
227,239 | PyCQA/astroid | astroid/node_classes.py | LookupMixIn.ilookup | def ilookup(self, name):
"""Lookup the inferred values of the given variable.
:param name: The variable name to find values for.
:type name: str
:returns: The inferred values of the statements returned from
:meth:`lookup`.
:rtype: iterable
"""
frame, stmts = self.lookup(name)
context = contextmod.InferenceContext()
return bases._infer_stmts(stmts, context, frame) | python | def ilookup(self, name):
frame, stmts = self.lookup(name)
context = contextmod.InferenceContext()
return bases._infer_stmts(stmts, context, frame) | [
"def",
"ilookup",
"(",
"self",
",",
"name",
")",
":",
"frame",
",",
"stmts",
"=",
"self",
".",
"lookup",
"(",
"name",
")",
"context",
"=",
"contextmod",
".",
"InferenceContext",
"(",
")",
"return",
"bases",
".",
"_infer_stmts",
"(",
"stmts",
",",
"cont... | Lookup the inferred values of the given variable.
:param name: The variable name to find values for.
:type name: str
:returns: The inferred values of the statements returned from
:meth:`lookup`.
:rtype: iterable | [
"Lookup",
"the",
"inferred",
"values",
"of",
"the",
"given",
"variable",
"."
] | e0a298df55b15abcb77c2a93253f5ab7be52d0fb | https://github.com/PyCQA/astroid/blob/e0a298df55b15abcb77c2a93253f5ab7be52d0fb/astroid/node_classes.py#L1089-L1101 |
227,240 | PyCQA/astroid | astroid/node_classes.py | LookupMixIn._filter_stmts | def _filter_stmts(self, stmts, frame, offset):
"""Filter the given list of statements to remove ignorable statements.
If self is not a frame itself and the name is found in the inner
frame locals, statements will be filtered to remove ignorable
statements according to self's location.
:param stmts: The statements to filter.
:type stmts: list(NodeNG)
:param frame: The frame that all of the given statements belong to.
:type frame: NodeNG
:param offset: The line offset to filter statements up to.
:type offset: int
:returns: The filtered statements.
:rtype: list(NodeNG)
"""
# if offset == -1, my actual frame is not the inner frame but its parent
#
# class A(B): pass
#
# we need this to resolve B correctly
if offset == -1:
myframe = self.frame().parent.frame()
else:
myframe = self.frame()
# If the frame of this node is the same as the statement
# of this node, then the node is part of a class or
# a function definition and the frame of this node should be the
# the upper frame, not the frame of the definition.
# For more information why this is important,
# see Pylint issue #295.
# For example, for 'b', the statement is the same
# as the frame / scope:
#
# def test(b=1):
# ...
if self.statement() is myframe and myframe.parent:
myframe = myframe.parent.frame()
mystmt = self.statement()
# line filtering if we are in the same frame
#
# take care node may be missing lineno information (this is the case for
# nodes inserted for living objects)
if myframe is frame and mystmt.fromlineno is not None:
assert mystmt.fromlineno is not None, mystmt
mylineno = mystmt.fromlineno + offset
else:
# disabling lineno filtering
mylineno = 0
_stmts = []
_stmt_parents = []
statements = self._get_filtered_node_statements(stmts)
for node, stmt in statements:
# line filtering is on and we have reached our location, break
if stmt.fromlineno > mylineno > 0:
break
# Ignore decorators with the same name as the
# decorated function
# Fixes issue #375
if mystmt is stmt and is_from_decorator(self):
continue
assert hasattr(node, "assign_type"), (
node,
node.scope(),
node.scope().locals,
)
assign_type = node.assign_type()
if node.has_base(self):
break
_stmts, done = assign_type._get_filtered_stmts(self, node, _stmts, mystmt)
if done:
break
optional_assign = assign_type.optional_assign
if optional_assign and assign_type.parent_of(self):
# we are inside a loop, loop var assignment is hiding previous
# assignment
_stmts = [node]
_stmt_parents = [stmt.parent]
continue
# XXX comment various branches below!!!
try:
pindex = _stmt_parents.index(stmt.parent)
except ValueError:
pass
else:
# we got a parent index, this means the currently visited node
# is at the same block level as a previously visited node
if _stmts[pindex].assign_type().parent_of(assign_type):
# both statements are not at the same block level
continue
# if currently visited node is following previously considered
# assignment and both are not exclusive, we can drop the
# previous one. For instance in the following code ::
#
# if a:
# x = 1
# else:
# x = 2
# print x
#
# we can't remove neither x = 1 nor x = 2 when looking for 'x'
# of 'print x'; while in the following ::
#
# x = 1
# x = 2
# print x
#
# we can remove x = 1 when we see x = 2
#
# moreover, on loop assignment types, assignment won't
# necessarily be done if the loop has no iteration, so we don't
# want to clear previous assignments if any (hence the test on
# optional_assign)
if not (optional_assign or are_exclusive(_stmts[pindex], node)):
if (
# In case of partial function node, if the statement is different
# from the origin function then it can be deleted otherwise it should
# remain to be able to correctly infer the call to origin function.
not node.is_function
or node.qname() != "PartialFunction"
or node.name != _stmts[pindex].name
):
del _stmt_parents[pindex]
del _stmts[pindex]
if isinstance(node, AssignName):
if not optional_assign and stmt.parent is mystmt.parent:
_stmts = []
_stmt_parents = []
elif isinstance(node, DelName):
_stmts = []
_stmt_parents = []
continue
if not are_exclusive(self, node):
_stmts.append(node)
_stmt_parents.append(stmt.parent)
return _stmts | python | def _filter_stmts(self, stmts, frame, offset):
# if offset == -1, my actual frame is not the inner frame but its parent
#
# class A(B): pass
#
# we need this to resolve B correctly
if offset == -1:
myframe = self.frame().parent.frame()
else:
myframe = self.frame()
# If the frame of this node is the same as the statement
# of this node, then the node is part of a class or
# a function definition and the frame of this node should be the
# the upper frame, not the frame of the definition.
# For more information why this is important,
# see Pylint issue #295.
# For example, for 'b', the statement is the same
# as the frame / scope:
#
# def test(b=1):
# ...
if self.statement() is myframe and myframe.parent:
myframe = myframe.parent.frame()
mystmt = self.statement()
# line filtering if we are in the same frame
#
# take care node may be missing lineno information (this is the case for
# nodes inserted for living objects)
if myframe is frame and mystmt.fromlineno is not None:
assert mystmt.fromlineno is not None, mystmt
mylineno = mystmt.fromlineno + offset
else:
# disabling lineno filtering
mylineno = 0
_stmts = []
_stmt_parents = []
statements = self._get_filtered_node_statements(stmts)
for node, stmt in statements:
# line filtering is on and we have reached our location, break
if stmt.fromlineno > mylineno > 0:
break
# Ignore decorators with the same name as the
# decorated function
# Fixes issue #375
if mystmt is stmt and is_from_decorator(self):
continue
assert hasattr(node, "assign_type"), (
node,
node.scope(),
node.scope().locals,
)
assign_type = node.assign_type()
if node.has_base(self):
break
_stmts, done = assign_type._get_filtered_stmts(self, node, _stmts, mystmt)
if done:
break
optional_assign = assign_type.optional_assign
if optional_assign and assign_type.parent_of(self):
# we are inside a loop, loop var assignment is hiding previous
# assignment
_stmts = [node]
_stmt_parents = [stmt.parent]
continue
# XXX comment various branches below!!!
try:
pindex = _stmt_parents.index(stmt.parent)
except ValueError:
pass
else:
# we got a parent index, this means the currently visited node
# is at the same block level as a previously visited node
if _stmts[pindex].assign_type().parent_of(assign_type):
# both statements are not at the same block level
continue
# if currently visited node is following previously considered
# assignment and both are not exclusive, we can drop the
# previous one. For instance in the following code ::
#
# if a:
# x = 1
# else:
# x = 2
# print x
#
# we can't remove neither x = 1 nor x = 2 when looking for 'x'
# of 'print x'; while in the following ::
#
# x = 1
# x = 2
# print x
#
# we can remove x = 1 when we see x = 2
#
# moreover, on loop assignment types, assignment won't
# necessarily be done if the loop has no iteration, so we don't
# want to clear previous assignments if any (hence the test on
# optional_assign)
if not (optional_assign or are_exclusive(_stmts[pindex], node)):
if (
# In case of partial function node, if the statement is different
# from the origin function then it can be deleted otherwise it should
# remain to be able to correctly infer the call to origin function.
not node.is_function
or node.qname() != "PartialFunction"
or node.name != _stmts[pindex].name
):
del _stmt_parents[pindex]
del _stmts[pindex]
if isinstance(node, AssignName):
if not optional_assign and stmt.parent is mystmt.parent:
_stmts = []
_stmt_parents = []
elif isinstance(node, DelName):
_stmts = []
_stmt_parents = []
continue
if not are_exclusive(self, node):
_stmts.append(node)
_stmt_parents.append(stmt.parent)
return _stmts | [
"def",
"_filter_stmts",
"(",
"self",
",",
"stmts",
",",
"frame",
",",
"offset",
")",
":",
"# if offset == -1, my actual frame is not the inner frame but its parent",
"#",
"# class A(B): pass",
"#",
"# we need this to resolve B correctly",
"if",
"offset",
"==",
"-",
"1",
"... | Filter the given list of statements to remove ignorable statements.
If self is not a frame itself and the name is found in the inner
frame locals, statements will be filtered to remove ignorable
statements according to self's location.
:param stmts: The statements to filter.
:type stmts: list(NodeNG)
:param frame: The frame that all of the given statements belong to.
:type frame: NodeNG
:param offset: The line offset to filter statements up to.
:type offset: int
:returns: The filtered statements.
:rtype: list(NodeNG) | [
"Filter",
"the",
"given",
"list",
"of",
"statements",
"to",
"remove",
"ignorable",
"statements",
"."
] | e0a298df55b15abcb77c2a93253f5ab7be52d0fb | https://github.com/PyCQA/astroid/blob/e0a298df55b15abcb77c2a93253f5ab7be52d0fb/astroid/node_classes.py#L1115-L1259 |
227,241 | PyCQA/astroid | astroid/node_classes.py | Arguments.format_args | def format_args(self):
"""Get the arguments formatted as string.
:returns: The formatted arguments.
:rtype: str
"""
result = []
if self.args:
result.append(
_format_args(
self.args, self.defaults, getattr(self, "annotations", None)
)
)
if self.vararg:
result.append("*%s" % self.vararg)
if self.kwonlyargs:
if not self.vararg:
result.append("*")
result.append(
_format_args(
self.kwonlyargs, self.kw_defaults, self.kwonlyargs_annotations
)
)
if self.kwarg:
result.append("**%s" % self.kwarg)
return ", ".join(result) | python | def format_args(self):
result = []
if self.args:
result.append(
_format_args(
self.args, self.defaults, getattr(self, "annotations", None)
)
)
if self.vararg:
result.append("*%s" % self.vararg)
if self.kwonlyargs:
if not self.vararg:
result.append("*")
result.append(
_format_args(
self.kwonlyargs, self.kw_defaults, self.kwonlyargs_annotations
)
)
if self.kwarg:
result.append("**%s" % self.kwarg)
return ", ".join(result) | [
"def",
"format_args",
"(",
"self",
")",
":",
"result",
"=",
"[",
"]",
"if",
"self",
".",
"args",
":",
"result",
".",
"append",
"(",
"_format_args",
"(",
"self",
".",
"args",
",",
"self",
".",
"defaults",
",",
"getattr",
"(",
"self",
",",
"\"annotatio... | Get the arguments formatted as string.
:returns: The formatted arguments.
:rtype: str | [
"Get",
"the",
"arguments",
"formatted",
"as",
"string",
"."
] | e0a298df55b15abcb77c2a93253f5ab7be52d0fb | https://github.com/PyCQA/astroid/blob/e0a298df55b15abcb77c2a93253f5ab7be52d0fb/astroid/node_classes.py#L1570-L1595 |
227,242 | PyCQA/astroid | astroid/node_classes.py | Arguments.default_value | def default_value(self, argname):
"""Get the default value for an argument.
:param argname: The name of the argument to get the default value for.
:type argname: str
:raises NoDefault: If there is no default value defined for the
given argument.
"""
i = _find_arg(argname, self.args)[0]
if i is not None:
idx = i - (len(self.args) - len(self.defaults))
if idx >= 0:
return self.defaults[idx]
i = _find_arg(argname, self.kwonlyargs)[0]
if i is not None and self.kw_defaults[i] is not None:
return self.kw_defaults[i]
raise exceptions.NoDefault(func=self.parent, name=argname) | python | def default_value(self, argname):
i = _find_arg(argname, self.args)[0]
if i is not None:
idx = i - (len(self.args) - len(self.defaults))
if idx >= 0:
return self.defaults[idx]
i = _find_arg(argname, self.kwonlyargs)[0]
if i is not None and self.kw_defaults[i] is not None:
return self.kw_defaults[i]
raise exceptions.NoDefault(func=self.parent, name=argname) | [
"def",
"default_value",
"(",
"self",
",",
"argname",
")",
":",
"i",
"=",
"_find_arg",
"(",
"argname",
",",
"self",
".",
"args",
")",
"[",
"0",
"]",
"if",
"i",
"is",
"not",
"None",
":",
"idx",
"=",
"i",
"-",
"(",
"len",
"(",
"self",
".",
"args",... | Get the default value for an argument.
:param argname: The name of the argument to get the default value for.
:type argname: str
:raises NoDefault: If there is no default value defined for the
given argument. | [
"Get",
"the",
"default",
"value",
"for",
"an",
"argument",
"."
] | e0a298df55b15abcb77c2a93253f5ab7be52d0fb | https://github.com/PyCQA/astroid/blob/e0a298df55b15abcb77c2a93253f5ab7be52d0fb/astroid/node_classes.py#L1597-L1614 |
227,243 | PyCQA/astroid | astroid/node_classes.py | Arguments.is_argument | def is_argument(self, name):
"""Check if the given name is defined in the arguments.
:param name: The name to check for.
:type name: str
:returns: True if the given name is defined in the arguments,
False otherwise.
:rtype: bool
"""
if name == self.vararg:
return True
if name == self.kwarg:
return True
return (
self.find_argname(name, True)[1] is not None
or self.kwonlyargs
and _find_arg(name, self.kwonlyargs, True)[1] is not None
) | python | def is_argument(self, name):
if name == self.vararg:
return True
if name == self.kwarg:
return True
return (
self.find_argname(name, True)[1] is not None
or self.kwonlyargs
and _find_arg(name, self.kwonlyargs, True)[1] is not None
) | [
"def",
"is_argument",
"(",
"self",
",",
"name",
")",
":",
"if",
"name",
"==",
"self",
".",
"vararg",
":",
"return",
"True",
"if",
"name",
"==",
"self",
".",
"kwarg",
":",
"return",
"True",
"return",
"(",
"self",
".",
"find_argname",
"(",
"name",
",",... | Check if the given name is defined in the arguments.
:param name: The name to check for.
:type name: str
:returns: True if the given name is defined in the arguments,
False otherwise.
:rtype: bool | [
"Check",
"if",
"the",
"given",
"name",
"is",
"defined",
"in",
"the",
"arguments",
"."
] | e0a298df55b15abcb77c2a93253f5ab7be52d0fb | https://github.com/PyCQA/astroid/blob/e0a298df55b15abcb77c2a93253f5ab7be52d0fb/astroid/node_classes.py#L1616-L1634 |
227,244 | PyCQA/astroid | astroid/node_classes.py | Call.starargs | def starargs(self):
"""The positional arguments that unpack something.
:type: list(Starred)
"""
args = self.args or []
return [arg for arg in args if isinstance(arg, Starred)] | python | def starargs(self):
args = self.args or []
return [arg for arg in args if isinstance(arg, Starred)] | [
"def",
"starargs",
"(",
"self",
")",
":",
"args",
"=",
"self",
".",
"args",
"or",
"[",
"]",
"return",
"[",
"arg",
"for",
"arg",
"in",
"args",
"if",
"isinstance",
"(",
"arg",
",",
"Starred",
")",
"]"
] | The positional arguments that unpack something.
:type: list(Starred) | [
"The",
"positional",
"arguments",
"that",
"unpack",
"something",
"."
] | e0a298df55b15abcb77c2a93253f5ab7be52d0fb | https://github.com/PyCQA/astroid/blob/e0a298df55b15abcb77c2a93253f5ab7be52d0fb/astroid/node_classes.py#L2245-L2251 |
227,245 | PyCQA/astroid | astroid/node_classes.py | Call.kwargs | def kwargs(self):
"""The keyword arguments that unpack something.
:type: list(Keyword)
"""
keywords = self.keywords or []
return [keyword for keyword in keywords if keyword.arg is None] | python | def kwargs(self):
keywords = self.keywords or []
return [keyword for keyword in keywords if keyword.arg is None] | [
"def",
"kwargs",
"(",
"self",
")",
":",
"keywords",
"=",
"self",
".",
"keywords",
"or",
"[",
"]",
"return",
"[",
"keyword",
"for",
"keyword",
"in",
"keywords",
"if",
"keyword",
".",
"arg",
"is",
"None",
"]"
] | The keyword arguments that unpack something.
:type: list(Keyword) | [
"The",
"keyword",
"arguments",
"that",
"unpack",
"something",
"."
] | e0a298df55b15abcb77c2a93253f5ab7be52d0fb | https://github.com/PyCQA/astroid/blob/e0a298df55b15abcb77c2a93253f5ab7be52d0fb/astroid/node_classes.py#L2254-L2260 |
227,246 | PyCQA/astroid | astroid/node_classes.py | Const.getitem | def getitem(self, index, context=None):
"""Get an item from this node if subscriptable.
:param index: The node to use as a subscript index.
:type index: Const or Slice
:raises AstroidTypeError: When the given index cannot be used as a
subscript index, or if this node is not subscriptable.
"""
if isinstance(index, Const):
index_value = index.value
elif isinstance(index, Slice):
index_value = _infer_slice(index, context=context)
else:
raise exceptions.AstroidTypeError(
"Could not use type {} as subscript index".format(type(index))
)
try:
if isinstance(self.value, (str, bytes)):
return Const(self.value[index_value])
except IndexError as exc:
raise exceptions.AstroidIndexError(
message="Index {index!r} out of range",
node=self,
index=index,
context=context,
) from exc
except TypeError as exc:
raise exceptions.AstroidTypeError(
message="Type error {error!r}", node=self, index=index, context=context
) from exc
raise exceptions.AstroidTypeError("%r (value=%s)" % (self, self.value)) | python | def getitem(self, index, context=None):
if isinstance(index, Const):
index_value = index.value
elif isinstance(index, Slice):
index_value = _infer_slice(index, context=context)
else:
raise exceptions.AstroidTypeError(
"Could not use type {} as subscript index".format(type(index))
)
try:
if isinstance(self.value, (str, bytes)):
return Const(self.value[index_value])
except IndexError as exc:
raise exceptions.AstroidIndexError(
message="Index {index!r} out of range",
node=self,
index=index,
context=context,
) from exc
except TypeError as exc:
raise exceptions.AstroidTypeError(
message="Type error {error!r}", node=self, index=index, context=context
) from exc
raise exceptions.AstroidTypeError("%r (value=%s)" % (self, self.value)) | [
"def",
"getitem",
"(",
"self",
",",
"index",
",",
"context",
"=",
"None",
")",
":",
"if",
"isinstance",
"(",
"index",
",",
"Const",
")",
":",
"index_value",
"=",
"index",
".",
"value",
"elif",
"isinstance",
"(",
"index",
",",
"Slice",
")",
":",
"inde... | Get an item from this node if subscriptable.
:param index: The node to use as a subscript index.
:type index: Const or Slice
:raises AstroidTypeError: When the given index cannot be used as a
subscript index, or if this node is not subscriptable. | [
"Get",
"an",
"item",
"from",
"this",
"node",
"if",
"subscriptable",
"."
] | e0a298df55b15abcb77c2a93253f5ab7be52d0fb | https://github.com/PyCQA/astroid/blob/e0a298df55b15abcb77c2a93253f5ab7be52d0fb/astroid/node_classes.py#L2483-L2517 |
227,247 | PyCQA/astroid | astroid/node_classes.py | ExceptHandler.blockstart_tolineno | def blockstart_tolineno(self):
"""The line on which the beginning of this block ends.
:type: int
"""
if self.name:
return self.name.tolineno
if self.type:
return self.type.tolineno
return self.lineno | python | def blockstart_tolineno(self):
if self.name:
return self.name.tolineno
if self.type:
return self.type.tolineno
return self.lineno | [
"def",
"blockstart_tolineno",
"(",
"self",
")",
":",
"if",
"self",
".",
"name",
":",
"return",
"self",
".",
"name",
".",
"tolineno",
"if",
"self",
".",
"type",
":",
"return",
"self",
".",
"type",
".",
"tolineno",
"return",
"self",
".",
"lineno"
] | The line on which the beginning of this block ends.
:type: int | [
"The",
"line",
"on",
"which",
"the",
"beginning",
"of",
"this",
"block",
"ends",
"."
] | e0a298df55b15abcb77c2a93253f5ab7be52d0fb | https://github.com/PyCQA/astroid/blob/e0a298df55b15abcb77c2a93253f5ab7be52d0fb/astroid/node_classes.py#L2955-L2964 |
227,248 | PyCQA/astroid | astroid/node_classes.py | ExceptHandler.catch | def catch(self, exceptions): # pylint: disable=redefined-outer-name
"""Check if this node handles any of the given exceptions.
If ``exceptions`` is empty, this will default to ``True``.
:param exceptions: The name of the exceptions to check for.
:type exceptions: list(str)
"""
if self.type is None or exceptions is None:
return True
for node in self.type._get_name_nodes():
if node.name in exceptions:
return True
return False | python | def catch(self, exceptions): # pylint: disable=redefined-outer-name
if self.type is None or exceptions is None:
return True
for node in self.type._get_name_nodes():
if node.name in exceptions:
return True
return False | [
"def",
"catch",
"(",
"self",
",",
"exceptions",
")",
":",
"# pylint: disable=redefined-outer-name",
"if",
"self",
".",
"type",
"is",
"None",
"or",
"exceptions",
"is",
"None",
":",
"return",
"True",
"for",
"node",
"in",
"self",
".",
"type",
".",
"_get_name_no... | Check if this node handles any of the given exceptions.
If ``exceptions`` is empty, this will default to ``True``.
:param exceptions: The name of the exceptions to check for.
:type exceptions: list(str) | [
"Check",
"if",
"this",
"node",
"handles",
"any",
"of",
"the",
"given",
"exceptions",
"."
] | e0a298df55b15abcb77c2a93253f5ab7be52d0fb | https://github.com/PyCQA/astroid/blob/e0a298df55b15abcb77c2a93253f5ab7be52d0fb/astroid/node_classes.py#L2966-L2979 |
227,249 | PyCQA/astroid | astroid/node_classes.py | Slice._wrap_attribute | def _wrap_attribute(self, attr):
"""Wrap the empty attributes of the Slice in a Const node."""
if not attr:
const = const_factory(attr)
const.parent = self
return const
return attr | python | def _wrap_attribute(self, attr):
if not attr:
const = const_factory(attr)
const.parent = self
return const
return attr | [
"def",
"_wrap_attribute",
"(",
"self",
",",
"attr",
")",
":",
"if",
"not",
"attr",
":",
"const",
"=",
"const_factory",
"(",
"attr",
")",
"const",
".",
"parent",
"=",
"self",
"return",
"const",
"return",
"attr"
] | Wrap the empty attributes of the Slice in a Const node. | [
"Wrap",
"the",
"empty",
"attributes",
"of",
"the",
"Slice",
"in",
"a",
"Const",
"node",
"."
] | e0a298df55b15abcb77c2a93253f5ab7be52d0fb | https://github.com/PyCQA/astroid/blob/e0a298df55b15abcb77c2a93253f5ab7be52d0fb/astroid/node_classes.py#L3896-L3902 |
227,250 | PyCQA/astroid | astroid/node_classes.py | Slice.igetattr | def igetattr(self, attrname, context=None):
"""Infer the possible values of the given attribute on the slice.
:param attrname: The name of the attribute to infer.
:type attrname: str
:returns: The inferred possible values.
:rtype: iterable(NodeNG)
"""
if attrname == "start":
yield self._wrap_attribute(self.lower)
elif attrname == "stop":
yield self._wrap_attribute(self.upper)
elif attrname == "step":
yield self._wrap_attribute(self.step)
else:
yield from self.getattr(attrname, context=context) | python | def igetattr(self, attrname, context=None):
if attrname == "start":
yield self._wrap_attribute(self.lower)
elif attrname == "stop":
yield self._wrap_attribute(self.upper)
elif attrname == "step":
yield self._wrap_attribute(self.step)
else:
yield from self.getattr(attrname, context=context) | [
"def",
"igetattr",
"(",
"self",
",",
"attrname",
",",
"context",
"=",
"None",
")",
":",
"if",
"attrname",
"==",
"\"start\"",
":",
"yield",
"self",
".",
"_wrap_attribute",
"(",
"self",
".",
"lower",
")",
"elif",
"attrname",
"==",
"\"stop\"",
":",
"yield",... | Infer the possible values of the given attribute on the slice.
:param attrname: The name of the attribute to infer.
:type attrname: str
:returns: The inferred possible values.
:rtype: iterable(NodeNG) | [
"Infer",
"the",
"possible",
"values",
"of",
"the",
"given",
"attribute",
"on",
"the",
"slice",
"."
] | e0a298df55b15abcb77c2a93253f5ab7be52d0fb | https://github.com/PyCQA/astroid/blob/e0a298df55b15abcb77c2a93253f5ab7be52d0fb/astroid/node_classes.py#L3917-L3933 |
227,251 | PyCQA/astroid | astroid/brain/brain_gi.py | _gi_build_stub | def _gi_build_stub(parent):
"""
Inspect the passed module recursively and build stubs for functions,
classes, etc.
"""
classes = {}
functions = {}
constants = {}
methods = {}
for name in dir(parent):
if name.startswith("__"):
continue
# Check if this is a valid name in python
if not re.match(_identifier_re, name):
continue
try:
obj = getattr(parent, name)
except:
continue
if inspect.isclass(obj):
classes[name] = obj
elif inspect.isfunction(obj) or inspect.isbuiltin(obj):
functions[name] = obj
elif inspect.ismethod(obj) or inspect.ismethoddescriptor(obj):
methods[name] = obj
elif (
str(obj).startswith("<flags")
or str(obj).startswith("<enum ")
or str(obj).startswith("<GType ")
or inspect.isdatadescriptor(obj)
):
constants[name] = 0
elif isinstance(obj, (int, str)):
constants[name] = obj
elif callable(obj):
# Fall back to a function for anything callable
functions[name] = obj
else:
# Assume everything else is some manner of constant
constants[name] = 0
ret = ""
if constants:
ret += "# %s constants\n\n" % parent.__name__
for name in sorted(constants):
if name[0].isdigit():
# GDK has some busted constant names like
# Gdk.EventType.2BUTTON_PRESS
continue
val = constants[name]
strval = str(val)
if isinstance(val, str):
strval = '"%s"' % str(val).replace("\\", "\\\\")
ret += "%s = %s\n" % (name, strval)
if ret:
ret += "\n\n"
if functions:
ret += "# %s functions\n\n" % parent.__name__
for name in sorted(functions):
ret += "def %s(*args, **kwargs):\n" % name
ret += " pass\n"
if ret:
ret += "\n\n"
if methods:
ret += "# %s methods\n\n" % parent.__name__
for name in sorted(methods):
ret += "def %s(self, *args, **kwargs):\n" % name
ret += " pass\n"
if ret:
ret += "\n\n"
if classes:
ret += "# %s classes\n\n" % parent.__name__
for name, obj in sorted(classes.items()):
base = "object"
if issubclass(obj, Exception):
base = "Exception"
ret += "class %s(%s):\n" % (name, base)
classret = _gi_build_stub(obj)
if not classret:
classret = "pass\n"
for line in classret.splitlines():
ret += " " + line + "\n"
ret += "\n"
return ret | python | def _gi_build_stub(parent):
classes = {}
functions = {}
constants = {}
methods = {}
for name in dir(parent):
if name.startswith("__"):
continue
# Check if this is a valid name in python
if not re.match(_identifier_re, name):
continue
try:
obj = getattr(parent, name)
except:
continue
if inspect.isclass(obj):
classes[name] = obj
elif inspect.isfunction(obj) or inspect.isbuiltin(obj):
functions[name] = obj
elif inspect.ismethod(obj) or inspect.ismethoddescriptor(obj):
methods[name] = obj
elif (
str(obj).startswith("<flags")
or str(obj).startswith("<enum ")
or str(obj).startswith("<GType ")
or inspect.isdatadescriptor(obj)
):
constants[name] = 0
elif isinstance(obj, (int, str)):
constants[name] = obj
elif callable(obj):
# Fall back to a function for anything callable
functions[name] = obj
else:
# Assume everything else is some manner of constant
constants[name] = 0
ret = ""
if constants:
ret += "# %s constants\n\n" % parent.__name__
for name in sorted(constants):
if name[0].isdigit():
# GDK has some busted constant names like
# Gdk.EventType.2BUTTON_PRESS
continue
val = constants[name]
strval = str(val)
if isinstance(val, str):
strval = '"%s"' % str(val).replace("\\", "\\\\")
ret += "%s = %s\n" % (name, strval)
if ret:
ret += "\n\n"
if functions:
ret += "# %s functions\n\n" % parent.__name__
for name in sorted(functions):
ret += "def %s(*args, **kwargs):\n" % name
ret += " pass\n"
if ret:
ret += "\n\n"
if methods:
ret += "# %s methods\n\n" % parent.__name__
for name in sorted(methods):
ret += "def %s(self, *args, **kwargs):\n" % name
ret += " pass\n"
if ret:
ret += "\n\n"
if classes:
ret += "# %s classes\n\n" % parent.__name__
for name, obj in sorted(classes.items()):
base = "object"
if issubclass(obj, Exception):
base = "Exception"
ret += "class %s(%s):\n" % (name, base)
classret = _gi_build_stub(obj)
if not classret:
classret = "pass\n"
for line in classret.splitlines():
ret += " " + line + "\n"
ret += "\n"
return ret | [
"def",
"_gi_build_stub",
"(",
"parent",
")",
":",
"classes",
"=",
"{",
"}",
"functions",
"=",
"{",
"}",
"constants",
"=",
"{",
"}",
"methods",
"=",
"{",
"}",
"for",
"name",
"in",
"dir",
"(",
"parent",
")",
":",
"if",
"name",
".",
"startswith",
"(",... | Inspect the passed module recursively and build stubs for functions,
classes, etc. | [
"Inspect",
"the",
"passed",
"module",
"recursively",
"and",
"build",
"stubs",
"for",
"functions",
"classes",
"etc",
"."
] | e0a298df55b15abcb77c2a93253f5ab7be52d0fb | https://github.com/PyCQA/astroid/blob/e0a298df55b15abcb77c2a93253f5ab7be52d0fb/astroid/brain/brain_gi.py#L33-L128 |
227,252 | PyCQA/astroid | astroid/helpers.py | object_type | def object_type(node, context=None):
"""Obtain the type of the given node
This is used to implement the ``type`` builtin, which means that it's
used for inferring type calls, as well as used in a couple of other places
in the inference.
The node will be inferred first, so this function can support all
sorts of objects, as long as they support inference.
"""
try:
types = set(_object_type(node, context))
except exceptions.InferenceError:
return util.Uninferable
if len(types) > 1 or not types:
return util.Uninferable
return list(types)[0] | python | def object_type(node, context=None):
try:
types = set(_object_type(node, context))
except exceptions.InferenceError:
return util.Uninferable
if len(types) > 1 or not types:
return util.Uninferable
return list(types)[0] | [
"def",
"object_type",
"(",
"node",
",",
"context",
"=",
"None",
")",
":",
"try",
":",
"types",
"=",
"set",
"(",
"_object_type",
"(",
"node",
",",
"context",
")",
")",
"except",
"exceptions",
".",
"InferenceError",
":",
"return",
"util",
".",
"Uninferable... | Obtain the type of the given node
This is used to implement the ``type`` builtin, which means that it's
used for inferring type calls, as well as used in a couple of other places
in the inference.
The node will be inferred first, so this function can support all
sorts of objects, as long as they support inference. | [
"Obtain",
"the",
"type",
"of",
"the",
"given",
"node"
] | e0a298df55b15abcb77c2a93253f5ab7be52d0fb | https://github.com/PyCQA/astroid/blob/e0a298df55b15abcb77c2a93253f5ab7be52d0fb/astroid/helpers.py#L68-L84 |
227,253 | PyCQA/astroid | astroid/helpers.py | object_isinstance | def object_isinstance(node, class_or_seq, context=None):
"""Check if a node 'isinstance' any node in class_or_seq
:param node: A given node
:param class_or_seq: Union[nodes.NodeNG, Sequence[nodes.NodeNG]]
:rtype: bool
:raises AstroidTypeError: if the given ``classes_or_seq`` are not types
"""
obj_type = object_type(node, context)
if obj_type is util.Uninferable:
return util.Uninferable
return _object_type_is_subclass(obj_type, class_or_seq, context=context) | python | def object_isinstance(node, class_or_seq, context=None):
obj_type = object_type(node, context)
if obj_type is util.Uninferable:
return util.Uninferable
return _object_type_is_subclass(obj_type, class_or_seq, context=context) | [
"def",
"object_isinstance",
"(",
"node",
",",
"class_or_seq",
",",
"context",
"=",
"None",
")",
":",
"obj_type",
"=",
"object_type",
"(",
"node",
",",
"context",
")",
"if",
"obj_type",
"is",
"util",
".",
"Uninferable",
":",
"return",
"util",
".",
"Uninfera... | Check if a node 'isinstance' any node in class_or_seq
:param node: A given node
:param class_or_seq: Union[nodes.NodeNG, Sequence[nodes.NodeNG]]
:rtype: bool
:raises AstroidTypeError: if the given ``classes_or_seq`` are not types | [
"Check",
"if",
"a",
"node",
"isinstance",
"any",
"node",
"in",
"class_or_seq"
] | e0a298df55b15abcb77c2a93253f5ab7be52d0fb | https://github.com/PyCQA/astroid/blob/e0a298df55b15abcb77c2a93253f5ab7be52d0fb/astroid/helpers.py#L114-L126 |
227,254 | PyCQA/astroid | astroid/helpers.py | object_issubclass | def object_issubclass(node, class_or_seq, context=None):
"""Check if a type is a subclass of any node in class_or_seq
:param node: A given node
:param class_or_seq: Union[Nodes.NodeNG, Sequence[nodes.NodeNG]]
:rtype: bool
:raises AstroidTypeError: if the given ``classes_or_seq`` are not types
:raises AstroidError: if the type of the given node cannot be inferred
or its type's mro doesn't work
"""
if not isinstance(node, nodes.ClassDef):
raise TypeError("{node} needs to be a ClassDef node".format(node=node))
return _object_type_is_subclass(node, class_or_seq, context=context) | python | def object_issubclass(node, class_or_seq, context=None):
if not isinstance(node, nodes.ClassDef):
raise TypeError("{node} needs to be a ClassDef node".format(node=node))
return _object_type_is_subclass(node, class_or_seq, context=context) | [
"def",
"object_issubclass",
"(",
"node",
",",
"class_or_seq",
",",
"context",
"=",
"None",
")",
":",
"if",
"not",
"isinstance",
"(",
"node",
",",
"nodes",
".",
"ClassDef",
")",
":",
"raise",
"TypeError",
"(",
"\"{node} needs to be a ClassDef node\"",
".",
"for... | Check if a type is a subclass of any node in class_or_seq
:param node: A given node
:param class_or_seq: Union[Nodes.NodeNG, Sequence[nodes.NodeNG]]
:rtype: bool
:raises AstroidTypeError: if the given ``classes_or_seq`` are not types
:raises AstroidError: if the type of the given node cannot be inferred
or its type's mro doesn't work | [
"Check",
"if",
"a",
"type",
"is",
"a",
"subclass",
"of",
"any",
"node",
"in",
"class_or_seq"
] | e0a298df55b15abcb77c2a93253f5ab7be52d0fb | https://github.com/PyCQA/astroid/blob/e0a298df55b15abcb77c2a93253f5ab7be52d0fb/astroid/helpers.py#L129-L142 |
227,255 | PyCQA/astroid | astroid/helpers.py | safe_infer | def safe_infer(node, context=None):
"""Return the inferred value for the given node.
Return None if inference failed or if there is some ambiguity (more than
one node has been inferred).
"""
try:
inferit = node.infer(context=context)
value = next(inferit)
except exceptions.InferenceError:
return None
try:
next(inferit)
return None # None if there is ambiguity on the inferred node
except exceptions.InferenceError:
return None # there is some kind of ambiguity
except StopIteration:
return value | python | def safe_infer(node, context=None):
try:
inferit = node.infer(context=context)
value = next(inferit)
except exceptions.InferenceError:
return None
try:
next(inferit)
return None # None if there is ambiguity on the inferred node
except exceptions.InferenceError:
return None # there is some kind of ambiguity
except StopIteration:
return value | [
"def",
"safe_infer",
"(",
"node",
",",
"context",
"=",
"None",
")",
":",
"try",
":",
"inferit",
"=",
"node",
".",
"infer",
"(",
"context",
"=",
"context",
")",
"value",
"=",
"next",
"(",
"inferit",
")",
"except",
"exceptions",
".",
"InferenceError",
":... | Return the inferred value for the given node.
Return None if inference failed or if there is some ambiguity (more than
one node has been inferred). | [
"Return",
"the",
"inferred",
"value",
"for",
"the",
"given",
"node",
"."
] | e0a298df55b15abcb77c2a93253f5ab7be52d0fb | https://github.com/PyCQA/astroid/blob/e0a298df55b15abcb77c2a93253f5ab7be52d0fb/astroid/helpers.py#L145-L162 |
227,256 | PyCQA/astroid | astroid/helpers.py | has_known_bases | def has_known_bases(klass, context=None):
"""Return true if all base classes of a class could be inferred."""
try:
return klass._all_bases_known
except AttributeError:
pass
for base in klass.bases:
result = safe_infer(base, context=context)
# TODO: check for A->B->A->B pattern in class structure too?
if (
not isinstance(result, scoped_nodes.ClassDef)
or result is klass
or not has_known_bases(result, context=context)
):
klass._all_bases_known = False
return False
klass._all_bases_known = True
return True | python | def has_known_bases(klass, context=None):
try:
return klass._all_bases_known
except AttributeError:
pass
for base in klass.bases:
result = safe_infer(base, context=context)
# TODO: check for A->B->A->B pattern in class structure too?
if (
not isinstance(result, scoped_nodes.ClassDef)
or result is klass
or not has_known_bases(result, context=context)
):
klass._all_bases_known = False
return False
klass._all_bases_known = True
return True | [
"def",
"has_known_bases",
"(",
"klass",
",",
"context",
"=",
"None",
")",
":",
"try",
":",
"return",
"klass",
".",
"_all_bases_known",
"except",
"AttributeError",
":",
"pass",
"for",
"base",
"in",
"klass",
".",
"bases",
":",
"result",
"=",
"safe_infer",
"(... | Return true if all base classes of a class could be inferred. | [
"Return",
"true",
"if",
"all",
"base",
"classes",
"of",
"a",
"class",
"could",
"be",
"inferred",
"."
] | e0a298df55b15abcb77c2a93253f5ab7be52d0fb | https://github.com/PyCQA/astroid/blob/e0a298df55b15abcb77c2a93253f5ab7be52d0fb/astroid/helpers.py#L165-L182 |
227,257 | PyCQA/astroid | astroid/helpers.py | class_instance_as_index | def class_instance_as_index(node):
"""Get the value as an index for the given instance.
If an instance provides an __index__ method, then it can
be used in some scenarios where an integer is expected,
for instance when multiplying or subscripting a list.
"""
context = contextmod.InferenceContext()
context.callcontext = contextmod.CallContext(args=[node])
try:
for inferred in node.igetattr("__index__", context=context):
if not isinstance(inferred, bases.BoundMethod):
continue
for result in inferred.infer_call_result(node, context=context):
if isinstance(result, nodes.Const) and isinstance(result.value, int):
return result
except exceptions.InferenceError:
pass
return None | python | def class_instance_as_index(node):
context = contextmod.InferenceContext()
context.callcontext = contextmod.CallContext(args=[node])
try:
for inferred in node.igetattr("__index__", context=context):
if not isinstance(inferred, bases.BoundMethod):
continue
for result in inferred.infer_call_result(node, context=context):
if isinstance(result, nodes.Const) and isinstance(result.value, int):
return result
except exceptions.InferenceError:
pass
return None | [
"def",
"class_instance_as_index",
"(",
"node",
")",
":",
"context",
"=",
"contextmod",
".",
"InferenceContext",
"(",
")",
"context",
".",
"callcontext",
"=",
"contextmod",
".",
"CallContext",
"(",
"args",
"=",
"[",
"node",
"]",
")",
"try",
":",
"for",
"inf... | Get the value as an index for the given instance.
If an instance provides an __index__ method, then it can
be used in some scenarios where an integer is expected,
for instance when multiplying or subscripting a list. | [
"Get",
"the",
"value",
"as",
"an",
"index",
"for",
"the",
"given",
"instance",
"."
] | e0a298df55b15abcb77c2a93253f5ab7be52d0fb | https://github.com/PyCQA/astroid/blob/e0a298df55b15abcb77c2a93253f5ab7be52d0fb/astroid/helpers.py#L208-L228 |
227,258 | PyCQA/astroid | astroid/helpers.py | object_len | def object_len(node, context=None):
"""Infer length of given node object
:param Union[nodes.ClassDef, nodes.Instance] node:
:param node: Node to infer length of
:raises AstroidTypeError: If an invalid node is returned
from __len__ method or no __len__ method exists
:raises InferenceError: If the given node cannot be inferred
or if multiple nodes are inferred
:rtype int: Integer length of node
"""
from astroid.objects import FrozenSet
inferred_node = safe_infer(node, context=context)
if inferred_node is None or inferred_node is util.Uninferable:
raise exceptions.InferenceError(node=node)
if isinstance(inferred_node, nodes.Const) and isinstance(
inferred_node.value, (bytes, str)
):
return len(inferred_node.value)
if isinstance(inferred_node, (nodes.List, nodes.Set, nodes.Tuple, FrozenSet)):
return len(inferred_node.elts)
if isinstance(inferred_node, nodes.Dict):
return len(inferred_node.items)
try:
node_type = object_type(inferred_node, context=context)
len_call = next(node_type.igetattr("__len__", context=context))
except exceptions.AttributeInferenceError:
raise exceptions.AstroidTypeError(
"object of type '{}' has no len()".format(len_call.pytype())
)
result_of_len = next(len_call.infer_call_result(node, context))
if (
isinstance(result_of_len, nodes.Const)
and result_of_len.pytype() == "builtins.int"
):
return result_of_len.value
raise exceptions.AstroidTypeError(
"'{}' object cannot be interpreted as an integer".format(result_of_len)
) | python | def object_len(node, context=None):
from astroid.objects import FrozenSet
inferred_node = safe_infer(node, context=context)
if inferred_node is None or inferred_node is util.Uninferable:
raise exceptions.InferenceError(node=node)
if isinstance(inferred_node, nodes.Const) and isinstance(
inferred_node.value, (bytes, str)
):
return len(inferred_node.value)
if isinstance(inferred_node, (nodes.List, nodes.Set, nodes.Tuple, FrozenSet)):
return len(inferred_node.elts)
if isinstance(inferred_node, nodes.Dict):
return len(inferred_node.items)
try:
node_type = object_type(inferred_node, context=context)
len_call = next(node_type.igetattr("__len__", context=context))
except exceptions.AttributeInferenceError:
raise exceptions.AstroidTypeError(
"object of type '{}' has no len()".format(len_call.pytype())
)
result_of_len = next(len_call.infer_call_result(node, context))
if (
isinstance(result_of_len, nodes.Const)
and result_of_len.pytype() == "builtins.int"
):
return result_of_len.value
raise exceptions.AstroidTypeError(
"'{}' object cannot be interpreted as an integer".format(result_of_len)
) | [
"def",
"object_len",
"(",
"node",
",",
"context",
"=",
"None",
")",
":",
"from",
"astroid",
".",
"objects",
"import",
"FrozenSet",
"inferred_node",
"=",
"safe_infer",
"(",
"node",
",",
"context",
"=",
"context",
")",
"if",
"inferred_node",
"is",
"None",
"o... | Infer length of given node object
:param Union[nodes.ClassDef, nodes.Instance] node:
:param node: Node to infer length of
:raises AstroidTypeError: If an invalid node is returned
from __len__ method or no __len__ method exists
:raises InferenceError: If the given node cannot be inferred
or if multiple nodes are inferred
:rtype int: Integer length of node | [
"Infer",
"length",
"of",
"given",
"node",
"object"
] | e0a298df55b15abcb77c2a93253f5ab7be52d0fb | https://github.com/PyCQA/astroid/blob/e0a298df55b15abcb77c2a93253f5ab7be52d0fb/astroid/helpers.py#L231-L272 |
227,259 | PyCQA/astroid | astroid/brain/brain_six.py | _indent | def _indent(text, prefix, predicate=None):
"""Adds 'prefix' to the beginning of selected lines in 'text'.
If 'predicate' is provided, 'prefix' will only be added to the lines
where 'predicate(line)' is True. If 'predicate' is not provided,
it will default to adding 'prefix' to all non-empty lines that do not
consist solely of whitespace characters.
"""
if predicate is None:
predicate = lambda line: line.strip()
def prefixed_lines():
for line in text.splitlines(True):
yield prefix + line if predicate(line) else line
return "".join(prefixed_lines()) | python | def _indent(text, prefix, predicate=None):
if predicate is None:
predicate = lambda line: line.strip()
def prefixed_lines():
for line in text.splitlines(True):
yield prefix + line if predicate(line) else line
return "".join(prefixed_lines()) | [
"def",
"_indent",
"(",
"text",
",",
"prefix",
",",
"predicate",
"=",
"None",
")",
":",
"if",
"predicate",
"is",
"None",
":",
"predicate",
"=",
"lambda",
"line",
":",
"line",
".",
"strip",
"(",
")",
"def",
"prefixed_lines",
"(",
")",
":",
"for",
"line... | Adds 'prefix' to the beginning of selected lines in 'text'.
If 'predicate' is provided, 'prefix' will only be added to the lines
where 'predicate(line)' is True. If 'predicate' is not provided,
it will default to adding 'prefix' to all non-empty lines that do not
consist solely of whitespace characters. | [
"Adds",
"prefix",
"to",
"the",
"beginning",
"of",
"selected",
"lines",
"in",
"text",
"."
] | e0a298df55b15abcb77c2a93253f5ab7be52d0fb | https://github.com/PyCQA/astroid/blob/e0a298df55b15abcb77c2a93253f5ab7be52d0fb/astroid/brain/brain_six.py#L26-L41 |
227,260 | PyCQA/astroid | astroid/brain/brain_six.py | _six_fail_hook | def _six_fail_hook(modname):
"""Fix six.moves imports due to the dynamic nature of this
class.
Construct a pseudo-module which contains all the necessary imports
for six
:param modname: Name of failed module
:type modname: str
:return: An astroid module
:rtype: nodes.Module
"""
attribute_of = modname != "six.moves" and modname.startswith("six.moves")
if modname != "six.moves" and not attribute_of:
raise AstroidBuildingError(modname=modname)
module = AstroidBuilder(MANAGER).string_build(_IMPORTS)
module.name = "six.moves"
if attribute_of:
# Facilitate import of submodules in Moves
start_index = len(module.name)
attribute = modname[start_index:].lstrip(".").replace(".", "_")
try:
import_attr = module.getattr(attribute)[0]
except AttributeInferenceError:
raise AstroidBuildingError(modname=modname)
if isinstance(import_attr, nodes.Import):
submodule = MANAGER.ast_from_module_name(import_attr.names[0][0])
return submodule
# Let dummy submodule imports pass through
# This will cause an Uninferable result, which is okay
return module | python | def _six_fail_hook(modname):
attribute_of = modname != "six.moves" and modname.startswith("six.moves")
if modname != "six.moves" and not attribute_of:
raise AstroidBuildingError(modname=modname)
module = AstroidBuilder(MANAGER).string_build(_IMPORTS)
module.name = "six.moves"
if attribute_of:
# Facilitate import of submodules in Moves
start_index = len(module.name)
attribute = modname[start_index:].lstrip(".").replace(".", "_")
try:
import_attr = module.getattr(attribute)[0]
except AttributeInferenceError:
raise AstroidBuildingError(modname=modname)
if isinstance(import_attr, nodes.Import):
submodule = MANAGER.ast_from_module_name(import_attr.names[0][0])
return submodule
# Let dummy submodule imports pass through
# This will cause an Uninferable result, which is okay
return module | [
"def",
"_six_fail_hook",
"(",
"modname",
")",
":",
"attribute_of",
"=",
"modname",
"!=",
"\"six.moves\"",
"and",
"modname",
".",
"startswith",
"(",
"\"six.moves\"",
")",
"if",
"modname",
"!=",
"\"six.moves\"",
"and",
"not",
"attribute_of",
":",
"raise",
"Astroid... | Fix six.moves imports due to the dynamic nature of this
class.
Construct a pseudo-module which contains all the necessary imports
for six
:param modname: Name of failed module
:type modname: str
:return: An astroid module
:rtype: nodes.Module | [
"Fix",
"six",
".",
"moves",
"imports",
"due",
"to",
"the",
"dynamic",
"nature",
"of",
"this",
"class",
"."
] | e0a298df55b15abcb77c2a93253f5ab7be52d0fb | https://github.com/PyCQA/astroid/blob/e0a298df55b15abcb77c2a93253f5ab7be52d0fb/astroid/brain/brain_six.py#L122-L154 |
227,261 | PyCQA/astroid | astroid/interpreter/_import/spec.py | find_spec | def find_spec(modpath, path=None):
"""Find a spec for the given module.
:type modpath: list or tuple
:param modpath:
split module's name (i.e name of a module or package split
on '.'), with leading empty strings for explicit relative import
:type path: list or None
:param path:
optional list of path where the module or package should be
searched (use sys.path if nothing or None is given)
:rtype: ModuleSpec
:return: A module spec, which describes how the module was
found and where.
"""
_path = path or sys.path
# Need a copy for not mutating the argument.
modpath = modpath[:]
submodule_path = None
module_parts = modpath[:]
processed = []
while modpath:
modname = modpath.pop(0)
finder, spec = _find_spec_with_path(
_path, modname, module_parts, processed, submodule_path or path
)
processed.append(modname)
if modpath:
submodule_path = finder.contribute_to_path(spec, processed)
if spec.type == ModuleType.PKG_DIRECTORY:
spec = spec._replace(submodule_search_locations=submodule_path)
return spec | python | def find_spec(modpath, path=None):
_path = path or sys.path
# Need a copy for not mutating the argument.
modpath = modpath[:]
submodule_path = None
module_parts = modpath[:]
processed = []
while modpath:
modname = modpath.pop(0)
finder, spec = _find_spec_with_path(
_path, modname, module_parts, processed, submodule_path or path
)
processed.append(modname)
if modpath:
submodule_path = finder.contribute_to_path(spec, processed)
if spec.type == ModuleType.PKG_DIRECTORY:
spec = spec._replace(submodule_search_locations=submodule_path)
return spec | [
"def",
"find_spec",
"(",
"modpath",
",",
"path",
"=",
"None",
")",
":",
"_path",
"=",
"path",
"or",
"sys",
".",
"path",
"# Need a copy for not mutating the argument.",
"modpath",
"=",
"modpath",
"[",
":",
"]",
"submodule_path",
"=",
"None",
"module_parts",
"="... | Find a spec for the given module.
:type modpath: list or tuple
:param modpath:
split module's name (i.e name of a module or package split
on '.'), with leading empty strings for explicit relative import
:type path: list or None
:param path:
optional list of path where the module or package should be
searched (use sys.path if nothing or None is given)
:rtype: ModuleSpec
:return: A module spec, which describes how the module was
found and where. | [
"Find",
"a",
"spec",
"for",
"the",
"given",
"module",
"."
] | e0a298df55b15abcb77c2a93253f5ab7be52d0fb | https://github.com/PyCQA/astroid/blob/e0a298df55b15abcb77c2a93253f5ab7be52d0fb/astroid/interpreter/_import/spec.py#L299-L337 |
227,262 | PyCQA/astroid | astroid/objects.py | Super.super_mro | def super_mro(self):
"""Get the MRO which will be used to lookup attributes in this super."""
if not isinstance(self.mro_pointer, scoped_nodes.ClassDef):
raise exceptions.SuperError(
"The first argument to super must be a subtype of "
"type, not {mro_pointer}.",
super_=self,
)
if isinstance(self.type, scoped_nodes.ClassDef):
# `super(type, type)`, most likely in a class method.
self._class_based = True
mro_type = self.type
else:
mro_type = getattr(self.type, "_proxied", None)
if not isinstance(mro_type, (bases.Instance, scoped_nodes.ClassDef)):
raise exceptions.SuperError(
"The second argument to super must be an "
"instance or subtype of type, not {type}.",
super_=self,
)
if not mro_type.newstyle:
raise exceptions.SuperError(
"Unable to call super on old-style classes.", super_=self
)
mro = mro_type.mro()
if self.mro_pointer not in mro:
raise exceptions.SuperError(
"The second argument to super must be an "
"instance or subtype of type, not {type}.",
super_=self,
)
index = mro.index(self.mro_pointer)
return mro[index + 1 :] | python | def super_mro(self):
if not isinstance(self.mro_pointer, scoped_nodes.ClassDef):
raise exceptions.SuperError(
"The first argument to super must be a subtype of "
"type, not {mro_pointer}.",
super_=self,
)
if isinstance(self.type, scoped_nodes.ClassDef):
# `super(type, type)`, most likely in a class method.
self._class_based = True
mro_type = self.type
else:
mro_type = getattr(self.type, "_proxied", None)
if not isinstance(mro_type, (bases.Instance, scoped_nodes.ClassDef)):
raise exceptions.SuperError(
"The second argument to super must be an "
"instance or subtype of type, not {type}.",
super_=self,
)
if not mro_type.newstyle:
raise exceptions.SuperError(
"Unable to call super on old-style classes.", super_=self
)
mro = mro_type.mro()
if self.mro_pointer not in mro:
raise exceptions.SuperError(
"The second argument to super must be an "
"instance or subtype of type, not {type}.",
super_=self,
)
index = mro.index(self.mro_pointer)
return mro[index + 1 :] | [
"def",
"super_mro",
"(",
"self",
")",
":",
"if",
"not",
"isinstance",
"(",
"self",
".",
"mro_pointer",
",",
"scoped_nodes",
".",
"ClassDef",
")",
":",
"raise",
"exceptions",
".",
"SuperError",
"(",
"\"The first argument to super must be a subtype of \"",
"\"type, no... | Get the MRO which will be used to lookup attributes in this super. | [
"Get",
"the",
"MRO",
"which",
"will",
"be",
"used",
"to",
"lookup",
"attributes",
"in",
"this",
"super",
"."
] | e0a298df55b15abcb77c2a93253f5ab7be52d0fb | https://github.com/PyCQA/astroid/blob/e0a298df55b15abcb77c2a93253f5ab7be52d0fb/astroid/objects.py#L77-L113 |
227,263 | PyCQA/astroid | astroid/objects.py | Super.igetattr | def igetattr(self, name, context=None):
"""Retrieve the inferred values of the given attribute name."""
if name in self.special_attributes:
yield self.special_attributes.lookup(name)
return
try:
mro = self.super_mro()
# Don't let invalid MROs or invalid super calls
# leak out as is from this function.
except exceptions.SuperError as exc:
raise exceptions.AttributeInferenceError(
(
"Lookup for {name} on {target!r} because super call {super!r} "
"is invalid."
),
target=self,
attribute=name,
context=context,
super_=exc.super_,
) from exc
except exceptions.MroError as exc:
raise exceptions.AttributeInferenceError(
(
"Lookup for {name} on {target!r} failed because {cls!r} has an "
"invalid MRO."
),
target=self,
attribute=name,
context=context,
mros=exc.mros,
cls=exc.cls,
) from exc
found = False
for cls in mro:
if name not in cls.locals:
continue
found = True
for inferred in bases._infer_stmts([cls[name]], context, frame=self):
if not isinstance(inferred, scoped_nodes.FunctionDef):
yield inferred
continue
# We can obtain different descriptors from a super depending
# on what we are accessing and where the super call is.
if inferred.type == "classmethod":
yield bases.BoundMethod(inferred, cls)
elif self._scope.type == "classmethod" and inferred.type == "method":
yield inferred
elif self._class_based or inferred.type == "staticmethod":
yield inferred
elif bases._is_property(inferred):
# TODO: support other descriptors as well.
try:
yield from inferred.infer_call_result(self, context)
except exceptions.InferenceError:
yield util.Uninferable
else:
yield bases.BoundMethod(inferred, cls)
if not found:
raise exceptions.AttributeInferenceError(
target=self, attribute=name, context=context
) | python | def igetattr(self, name, context=None):
if name in self.special_attributes:
yield self.special_attributes.lookup(name)
return
try:
mro = self.super_mro()
# Don't let invalid MROs or invalid super calls
# leak out as is from this function.
except exceptions.SuperError as exc:
raise exceptions.AttributeInferenceError(
(
"Lookup for {name} on {target!r} because super call {super!r} "
"is invalid."
),
target=self,
attribute=name,
context=context,
super_=exc.super_,
) from exc
except exceptions.MroError as exc:
raise exceptions.AttributeInferenceError(
(
"Lookup for {name} on {target!r} failed because {cls!r} has an "
"invalid MRO."
),
target=self,
attribute=name,
context=context,
mros=exc.mros,
cls=exc.cls,
) from exc
found = False
for cls in mro:
if name not in cls.locals:
continue
found = True
for inferred in bases._infer_stmts([cls[name]], context, frame=self):
if not isinstance(inferred, scoped_nodes.FunctionDef):
yield inferred
continue
# We can obtain different descriptors from a super depending
# on what we are accessing and where the super call is.
if inferred.type == "classmethod":
yield bases.BoundMethod(inferred, cls)
elif self._scope.type == "classmethod" and inferred.type == "method":
yield inferred
elif self._class_based or inferred.type == "staticmethod":
yield inferred
elif bases._is_property(inferred):
# TODO: support other descriptors as well.
try:
yield from inferred.infer_call_result(self, context)
except exceptions.InferenceError:
yield util.Uninferable
else:
yield bases.BoundMethod(inferred, cls)
if not found:
raise exceptions.AttributeInferenceError(
target=self, attribute=name, context=context
) | [
"def",
"igetattr",
"(",
"self",
",",
"name",
",",
"context",
"=",
"None",
")",
":",
"if",
"name",
"in",
"self",
".",
"special_attributes",
":",
"yield",
"self",
".",
"special_attributes",
".",
"lookup",
"(",
"name",
")",
"return",
"try",
":",
"mro",
"=... | Retrieve the inferred values of the given attribute name. | [
"Retrieve",
"the",
"inferred",
"values",
"of",
"the",
"given",
"attribute",
"name",
"."
] | e0a298df55b15abcb77c2a93253f5ab7be52d0fb | https://github.com/PyCQA/astroid/blob/e0a298df55b15abcb77c2a93253f5ab7be52d0fb/astroid/objects.py#L134-L199 |
227,264 | PyCQA/astroid | astroid/transforms.py | TransformVisitor._transform | def _transform(self, node):
"""Call matching transforms for the given node if any and return the
transformed node.
"""
cls = node.__class__
if cls not in self.transforms:
# no transform registered for this class of node
return node
transforms = self.transforms[cls]
for transform_func, predicate in transforms:
if predicate is None or predicate(node):
ret = transform_func(node)
# if the transformation function returns something, it's
# expected to be a replacement for the node
if ret is not None:
node = ret
if ret.__class__ != cls:
# Can no longer apply the rest of the transforms.
break
return node | python | def _transform(self, node):
cls = node.__class__
if cls not in self.transforms:
# no transform registered for this class of node
return node
transforms = self.transforms[cls]
for transform_func, predicate in transforms:
if predicate is None or predicate(node):
ret = transform_func(node)
# if the transformation function returns something, it's
# expected to be a replacement for the node
if ret is not None:
node = ret
if ret.__class__ != cls:
# Can no longer apply the rest of the transforms.
break
return node | [
"def",
"_transform",
"(",
"self",
",",
"node",
")",
":",
"cls",
"=",
"node",
".",
"__class__",
"if",
"cls",
"not",
"in",
"self",
".",
"transforms",
":",
"# no transform registered for this class of node",
"return",
"node",
"transforms",
"=",
"self",
".",
"tran... | Call matching transforms for the given node if any and return the
transformed node. | [
"Call",
"matching",
"transforms",
"for",
"the",
"given",
"node",
"if",
"any",
"and",
"return",
"the",
"transformed",
"node",
"."
] | e0a298df55b15abcb77c2a93253f5ab7be52d0fb | https://github.com/PyCQA/astroid/blob/e0a298df55b15abcb77c2a93253f5ab7be52d0fb/astroid/transforms.py#L28-L48 |
227,265 | PyCQA/astroid | astroid/transforms.py | TransformVisitor.unregister_transform | def unregister_transform(self, node_class, transform, predicate=None):
"""Unregister the given transform."""
self.transforms[node_class].remove((transform, predicate)) | python | def unregister_transform(self, node_class, transform, predicate=None):
self.transforms[node_class].remove((transform, predicate)) | [
"def",
"unregister_transform",
"(",
"self",
",",
"node_class",
",",
"transform",
",",
"predicate",
"=",
"None",
")",
":",
"self",
".",
"transforms",
"[",
"node_class",
"]",
".",
"remove",
"(",
"(",
"transform",
",",
"predicate",
")",
")"
] | Unregister the given transform. | [
"Unregister",
"the",
"given",
"transform",
"."
] | e0a298df55b15abcb77c2a93253f5ab7be52d0fb | https://github.com/PyCQA/astroid/blob/e0a298df55b15abcb77c2a93253f5ab7be52d0fb/astroid/transforms.py#L79-L81 |
227,266 | PyCQA/astroid | astroid/brain/brain_functools.py | _looks_like_lru_cache | def _looks_like_lru_cache(node):
"""Check if the given function node is decorated with lru_cache."""
if not node.decorators:
return False
for decorator in node.decorators.nodes:
if not isinstance(decorator, astroid.Call):
continue
if _looks_like_functools_member(decorator, "lru_cache"):
return True
return False | python | def _looks_like_lru_cache(node):
if not node.decorators:
return False
for decorator in node.decorators.nodes:
if not isinstance(decorator, astroid.Call):
continue
if _looks_like_functools_member(decorator, "lru_cache"):
return True
return False | [
"def",
"_looks_like_lru_cache",
"(",
"node",
")",
":",
"if",
"not",
"node",
".",
"decorators",
":",
"return",
"False",
"for",
"decorator",
"in",
"node",
".",
"decorators",
".",
"nodes",
":",
"if",
"not",
"isinstance",
"(",
"decorator",
",",
"astroid",
".",... | Check if the given function node is decorated with lru_cache. | [
"Check",
"if",
"the",
"given",
"function",
"node",
"is",
"decorated",
"with",
"lru_cache",
"."
] | e0a298df55b15abcb77c2a93253f5ab7be52d0fb | https://github.com/PyCQA/astroid/blob/e0a298df55b15abcb77c2a93253f5ab7be52d0fb/astroid/brain/brain_functools.py#L121-L130 |
227,267 | PyCQA/astroid | astroid/brain/brain_functools.py | _looks_like_functools_member | def _looks_like_functools_member(node, member):
"""Check if the given Call node is a functools.partial call"""
if isinstance(node.func, astroid.Name):
return node.func.name == member
elif isinstance(node.func, astroid.Attribute):
return (
node.func.attrname == member
and isinstance(node.func.expr, astroid.Name)
and node.func.expr.name == "functools"
) | python | def _looks_like_functools_member(node, member):
if isinstance(node.func, astroid.Name):
return node.func.name == member
elif isinstance(node.func, astroid.Attribute):
return (
node.func.attrname == member
and isinstance(node.func.expr, astroid.Name)
and node.func.expr.name == "functools"
) | [
"def",
"_looks_like_functools_member",
"(",
"node",
",",
"member",
")",
":",
"if",
"isinstance",
"(",
"node",
".",
"func",
",",
"astroid",
".",
"Name",
")",
":",
"return",
"node",
".",
"func",
".",
"name",
"==",
"member",
"elif",
"isinstance",
"(",
"node... | Check if the given Call node is a functools.partial call | [
"Check",
"if",
"the",
"given",
"Call",
"node",
"is",
"a",
"functools",
".",
"partial",
"call"
] | e0a298df55b15abcb77c2a93253f5ab7be52d0fb | https://github.com/PyCQA/astroid/blob/e0a298df55b15abcb77c2a93253f5ab7be52d0fb/astroid/brain/brain_functools.py#L133-L142 |
227,268 | PyCQA/astroid | astroid/mixins.py | FilterStmtsMixin._get_filtered_stmts | def _get_filtered_stmts(self, _, node, _stmts, mystmt):
"""method used in _filter_stmts to get statements and trigger break"""
if self.statement() is mystmt:
# original node's statement is the assignment, only keep
# current node (gen exp, list comp)
return [node], True
return _stmts, False | python | def _get_filtered_stmts(self, _, node, _stmts, mystmt):
if self.statement() is mystmt:
# original node's statement is the assignment, only keep
# current node (gen exp, list comp)
return [node], True
return _stmts, False | [
"def",
"_get_filtered_stmts",
"(",
"self",
",",
"_",
",",
"node",
",",
"_stmts",
",",
"mystmt",
")",
":",
"if",
"self",
".",
"statement",
"(",
")",
"is",
"mystmt",
":",
"# original node's statement is the assignment, only keep",
"# current node (gen exp, list comp)",
... | method used in _filter_stmts to get statements and trigger break | [
"method",
"used",
"in",
"_filter_stmts",
"to",
"get",
"statements",
"and",
"trigger",
"break"
] | e0a298df55b15abcb77c2a93253f5ab7be52d0fb | https://github.com/PyCQA/astroid/blob/e0a298df55b15abcb77c2a93253f5ab7be52d0fb/astroid/mixins.py#L44-L50 |
227,269 | PyCQA/astroid | astroid/mixins.py | ImportFromMixin.real_name | def real_name(self, asname):
"""get name from 'as' name"""
for name, _asname in self.names:
if name == "*":
return asname
if not _asname:
name = name.split(".", 1)[0]
_asname = name
if asname == _asname:
return name
raise exceptions.AttributeInferenceError(
"Could not find original name for {attribute} in {target!r}",
target=self,
attribute=asname,
) | python | def real_name(self, asname):
for name, _asname in self.names:
if name == "*":
return asname
if not _asname:
name = name.split(".", 1)[0]
_asname = name
if asname == _asname:
return name
raise exceptions.AttributeInferenceError(
"Could not find original name for {attribute} in {target!r}",
target=self,
attribute=asname,
) | [
"def",
"real_name",
"(",
"self",
",",
"asname",
")",
":",
"for",
"name",
",",
"_asname",
"in",
"self",
".",
"names",
":",
"if",
"name",
"==",
"\"*\"",
":",
"return",
"asname",
"if",
"not",
"_asname",
":",
"name",
"=",
"name",
".",
"split",
"(",
"\"... | get name from 'as' name | [
"get",
"name",
"from",
"as",
"name"
] | e0a298df55b15abcb77c2a93253f5ab7be52d0fb | https://github.com/PyCQA/astroid/blob/e0a298df55b15abcb77c2a93253f5ab7be52d0fb/astroid/mixins.py#L103-L117 |
227,270 | PyCQA/astroid | astroid/_ast.py | parse_function_type_comment | def parse_function_type_comment(type_comment: str) -> Optional[FunctionType]:
"""Given a correct type comment, obtain a FunctionType object"""
if _ast_py3 is None:
return None
func_type = _ast_py3.parse(type_comment, "<type_comment>", "func_type")
return FunctionType(argtypes=func_type.argtypes, returns=func_type.returns) | python | def parse_function_type_comment(type_comment: str) -> Optional[FunctionType]:
if _ast_py3 is None:
return None
func_type = _ast_py3.parse(type_comment, "<type_comment>", "func_type")
return FunctionType(argtypes=func_type.argtypes, returns=func_type.returns) | [
"def",
"parse_function_type_comment",
"(",
"type_comment",
":",
"str",
")",
"->",
"Optional",
"[",
"FunctionType",
"]",
":",
"if",
"_ast_py3",
"is",
"None",
":",
"return",
"None",
"func_type",
"=",
"_ast_py3",
".",
"parse",
"(",
"type_comment",
",",
"\"<type_c... | Given a correct type comment, obtain a FunctionType object | [
"Given",
"a",
"correct",
"type",
"comment",
"obtain",
"a",
"FunctionType",
"object"
] | e0a298df55b15abcb77c2a93253f5ab7be52d0fb | https://github.com/PyCQA/astroid/blob/e0a298df55b15abcb77c2a93253f5ab7be52d0fb/astroid/_ast.py#L34-L40 |
227,271 | PyCQA/astroid | astroid/brain/brain_attrs.py | is_decorated_with_attrs | def is_decorated_with_attrs(node, decorator_names=ATTRS_NAMES):
"""Return True if a decorated node has
an attr decorator applied."""
if not node.decorators:
return False
for decorator_attribute in node.decorators.nodes:
if isinstance(decorator_attribute, astroid.Call): # decorator with arguments
decorator_attribute = decorator_attribute.func
if decorator_attribute.as_string() in decorator_names:
return True
return False | python | def is_decorated_with_attrs(node, decorator_names=ATTRS_NAMES):
if not node.decorators:
return False
for decorator_attribute in node.decorators.nodes:
if isinstance(decorator_attribute, astroid.Call): # decorator with arguments
decorator_attribute = decorator_attribute.func
if decorator_attribute.as_string() in decorator_names:
return True
return False | [
"def",
"is_decorated_with_attrs",
"(",
"node",
",",
"decorator_names",
"=",
"ATTRS_NAMES",
")",
":",
"if",
"not",
"node",
".",
"decorators",
":",
"return",
"False",
"for",
"decorator_attribute",
"in",
"node",
".",
"decorators",
".",
"nodes",
":",
"if",
"isinst... | Return True if a decorated node has
an attr decorator applied. | [
"Return",
"True",
"if",
"a",
"decorated",
"node",
"has",
"an",
"attr",
"decorator",
"applied",
"."
] | e0a298df55b15abcb77c2a93253f5ab7be52d0fb | https://github.com/PyCQA/astroid/blob/e0a298df55b15abcb77c2a93253f5ab7be52d0fb/astroid/brain/brain_attrs.py#L18-L28 |
227,272 | PyCQA/astroid | astroid/brain/brain_attrs.py | attr_attributes_transform | def attr_attributes_transform(node):
"""Given that the ClassNode has an attr decorator,
rewrite class attributes as instance attributes
"""
# Astroid can't infer this attribute properly
# Prevents https://github.com/PyCQA/pylint/issues/1884
node.locals["__attrs_attrs__"] = [astroid.Unknown(parent=node)]
for cdefbodynode in node.body:
if not isinstance(cdefbodynode, astroid.Assign):
continue
if isinstance(cdefbodynode.value, astroid.Call):
if cdefbodynode.value.func.as_string() not in ATTRIB_NAMES:
continue
else:
continue
for target in cdefbodynode.targets:
rhs_node = astroid.Unknown(
lineno=cdefbodynode.lineno,
col_offset=cdefbodynode.col_offset,
parent=cdefbodynode,
)
node.locals[target.name] = [rhs_node] | python | def attr_attributes_transform(node):
# Astroid can't infer this attribute properly
# Prevents https://github.com/PyCQA/pylint/issues/1884
node.locals["__attrs_attrs__"] = [astroid.Unknown(parent=node)]
for cdefbodynode in node.body:
if not isinstance(cdefbodynode, astroid.Assign):
continue
if isinstance(cdefbodynode.value, astroid.Call):
if cdefbodynode.value.func.as_string() not in ATTRIB_NAMES:
continue
else:
continue
for target in cdefbodynode.targets:
rhs_node = astroid.Unknown(
lineno=cdefbodynode.lineno,
col_offset=cdefbodynode.col_offset,
parent=cdefbodynode,
)
node.locals[target.name] = [rhs_node] | [
"def",
"attr_attributes_transform",
"(",
"node",
")",
":",
"# Astroid can't infer this attribute properly",
"# Prevents https://github.com/PyCQA/pylint/issues/1884",
"node",
".",
"locals",
"[",
"\"__attrs_attrs__\"",
"]",
"=",
"[",
"astroid",
".",
"Unknown",
"(",
"parent",
... | Given that the ClassNode has an attr decorator,
rewrite class attributes as instance attributes | [
"Given",
"that",
"the",
"ClassNode",
"has",
"an",
"attr",
"decorator",
"rewrite",
"class",
"attributes",
"as",
"instance",
"attributes"
] | e0a298df55b15abcb77c2a93253f5ab7be52d0fb | https://github.com/PyCQA/astroid/blob/e0a298df55b15abcb77c2a93253f5ab7be52d0fb/astroid/brain/brain_attrs.py#L31-L54 |
227,273 | PyCQA/astroid | astroid/util.py | proxy_alias | def proxy_alias(alias_name, node_type):
"""Get a Proxy from the given name to the given node type."""
proxy = type(
alias_name,
(lazy_object_proxy.Proxy,),
{
"__class__": object.__dict__["__class__"],
"__instancecheck__": _instancecheck,
},
)
return proxy(lambda: node_type) | python | def proxy_alias(alias_name, node_type):
proxy = type(
alias_name,
(lazy_object_proxy.Proxy,),
{
"__class__": object.__dict__["__class__"],
"__instancecheck__": _instancecheck,
},
)
return proxy(lambda: node_type) | [
"def",
"proxy_alias",
"(",
"alias_name",
",",
"node_type",
")",
":",
"proxy",
"=",
"type",
"(",
"alias_name",
",",
"(",
"lazy_object_proxy",
".",
"Proxy",
",",
")",
",",
"{",
"\"__class__\"",
":",
"object",
".",
"__dict__",
"[",
"\"__class__\"",
"]",
",",
... | Get a Proxy from the given name to the given node type. | [
"Get",
"a",
"Proxy",
"from",
"the",
"given",
"name",
"to",
"the",
"given",
"node",
"type",
"."
] | e0a298df55b15abcb77c2a93253f5ab7be52d0fb | https://github.com/PyCQA/astroid/blob/e0a298df55b15abcb77c2a93253f5ab7be52d0fb/astroid/util.py#L131-L141 |
227,274 | PyCQA/astroid | astroid/util.py | limit_inference | def limit_inference(iterator, size):
"""Limit inference amount.
Limit inference amount to help with performance issues with
exponentially exploding possible results.
:param iterator: Inference generator to limit
:type iterator: Iterator(NodeNG)
:param size: Maximum mount of nodes yielded plus an
Uninferable at the end if limit reached
:type size: int
:yields: A possibly modified generator
:rtype param: Iterable
"""
yield from islice(iterator, size)
has_more = next(iterator, False)
if has_more is not False:
yield Uninferable
return | python | def limit_inference(iterator, size):
yield from islice(iterator, size)
has_more = next(iterator, False)
if has_more is not False:
yield Uninferable
return | [
"def",
"limit_inference",
"(",
"iterator",
",",
"size",
")",
":",
"yield",
"from",
"islice",
"(",
"iterator",
",",
"size",
")",
"has_more",
"=",
"next",
"(",
"iterator",
",",
"False",
")",
"if",
"has_more",
"is",
"not",
"False",
":",
"yield",
"Uninferabl... | Limit inference amount.
Limit inference amount to help with performance issues with
exponentially exploding possible results.
:param iterator: Inference generator to limit
:type iterator: Iterator(NodeNG)
:param size: Maximum mount of nodes yielded plus an
Uninferable at the end if limit reached
:type size: int
:yields: A possibly modified generator
:rtype param: Iterable | [
"Limit",
"inference",
"amount",
"."
] | e0a298df55b15abcb77c2a93253f5ab7be52d0fb | https://github.com/PyCQA/astroid/blob/e0a298df55b15abcb77c2a93253f5ab7be52d0fb/astroid/util.py#L144-L164 |
227,275 | PyCQA/astroid | astroid/scoped_nodes.py | builtin_lookup | def builtin_lookup(name):
"""lookup a name into the builtin module
return the list of matching statements and the astroid for the builtin
module
"""
builtin_astroid = MANAGER.ast_from_module(builtins)
if name == "__dict__":
return builtin_astroid, ()
try:
stmts = builtin_astroid.locals[name]
except KeyError:
stmts = ()
return builtin_astroid, stmts | python | def builtin_lookup(name):
builtin_astroid = MANAGER.ast_from_module(builtins)
if name == "__dict__":
return builtin_astroid, ()
try:
stmts = builtin_astroid.locals[name]
except KeyError:
stmts = ()
return builtin_astroid, stmts | [
"def",
"builtin_lookup",
"(",
"name",
")",
":",
"builtin_astroid",
"=",
"MANAGER",
".",
"ast_from_module",
"(",
"builtins",
")",
"if",
"name",
"==",
"\"__dict__\"",
":",
"return",
"builtin_astroid",
",",
"(",
")",
"try",
":",
"stmts",
"=",
"builtin_astroid",
... | lookup a name into the builtin module
return the list of matching statements and the astroid for the builtin
module | [
"lookup",
"a",
"name",
"into",
"the",
"builtin",
"module",
"return",
"the",
"list",
"of",
"matching",
"statements",
"and",
"the",
"astroid",
"for",
"the",
"builtin",
"module"
] | e0a298df55b15abcb77c2a93253f5ab7be52d0fb | https://github.com/PyCQA/astroid/blob/e0a298df55b15abcb77c2a93253f5ab7be52d0fb/astroid/scoped_nodes.py#L115-L127 |
227,276 | PyCQA/astroid | astroid/scoped_nodes.py | _infer_decorator_callchain | def _infer_decorator_callchain(node):
"""Detect decorator call chaining and see if the end result is a
static or a classmethod.
"""
if not isinstance(node, FunctionDef):
return None
if not node.parent:
return None
try:
result = next(node.infer_call_result(node.parent))
except exceptions.InferenceError:
return None
if isinstance(result, bases.Instance):
result = result._proxied
if isinstance(result, ClassDef):
if result.is_subtype_of("%s.classmethod" % BUILTINS):
return "classmethod"
if result.is_subtype_of("%s.staticmethod" % BUILTINS):
return "staticmethod"
return None | python | def _infer_decorator_callchain(node):
if not isinstance(node, FunctionDef):
return None
if not node.parent:
return None
try:
result = next(node.infer_call_result(node.parent))
except exceptions.InferenceError:
return None
if isinstance(result, bases.Instance):
result = result._proxied
if isinstance(result, ClassDef):
if result.is_subtype_of("%s.classmethod" % BUILTINS):
return "classmethod"
if result.is_subtype_of("%s.staticmethod" % BUILTINS):
return "staticmethod"
return None | [
"def",
"_infer_decorator_callchain",
"(",
"node",
")",
":",
"if",
"not",
"isinstance",
"(",
"node",
",",
"FunctionDef",
")",
":",
"return",
"None",
"if",
"not",
"node",
".",
"parent",
":",
"return",
"None",
"try",
":",
"result",
"=",
"next",
"(",
"node",... | Detect decorator call chaining and see if the end result is a
static or a classmethod. | [
"Detect",
"decorator",
"call",
"chaining",
"and",
"see",
"if",
"the",
"end",
"result",
"is",
"a",
"static",
"or",
"a",
"classmethod",
"."
] | e0a298df55b15abcb77c2a93253f5ab7be52d0fb | https://github.com/PyCQA/astroid/blob/e0a298df55b15abcb77c2a93253f5ab7be52d0fb/astroid/scoped_nodes.py#L1045-L1064 |
227,277 | PyCQA/astroid | astroid/scoped_nodes.py | _rec_get_names | def _rec_get_names(args, names=None):
"""return a list of all argument names"""
if names is None:
names = []
for arg in args:
if isinstance(arg, node_classes.Tuple):
_rec_get_names(arg.elts, names)
else:
names.append(arg.name)
return names | python | def _rec_get_names(args, names=None):
if names is None:
names = []
for arg in args:
if isinstance(arg, node_classes.Tuple):
_rec_get_names(arg.elts, names)
else:
names.append(arg.name)
return names | [
"def",
"_rec_get_names",
"(",
"args",
",",
"names",
"=",
"None",
")",
":",
"if",
"names",
"is",
"None",
":",
"names",
"=",
"[",
"]",
"for",
"arg",
"in",
"args",
":",
"if",
"isinstance",
"(",
"arg",
",",
"node_classes",
".",
"Tuple",
")",
":",
"_rec... | return a list of all argument names | [
"return",
"a",
"list",
"of",
"all",
"argument",
"names"
] | e0a298df55b15abcb77c2a93253f5ab7be52d0fb | https://github.com/PyCQA/astroid/blob/e0a298df55b15abcb77c2a93253f5ab7be52d0fb/astroid/scoped_nodes.py#L1707-L1716 |
227,278 | PyCQA/astroid | astroid/scoped_nodes.py | _is_metaclass | def _is_metaclass(klass, seen=None):
""" Return if the given class can be
used as a metaclass.
"""
if klass.name == "type":
return True
if seen is None:
seen = set()
for base in klass.bases:
try:
for baseobj in base.infer():
baseobj_name = baseobj.qname()
if baseobj_name in seen:
continue
else:
seen.add(baseobj_name)
if isinstance(baseobj, bases.Instance):
# not abstract
return False
if baseobj is util.Uninferable:
continue
if baseobj is klass:
continue
if not isinstance(baseobj, ClassDef):
continue
if baseobj._type == "metaclass":
return True
if _is_metaclass(baseobj, seen):
return True
except exceptions.InferenceError:
continue
return False | python | def _is_metaclass(klass, seen=None):
if klass.name == "type":
return True
if seen is None:
seen = set()
for base in klass.bases:
try:
for baseobj in base.infer():
baseobj_name = baseobj.qname()
if baseobj_name in seen:
continue
else:
seen.add(baseobj_name)
if isinstance(baseobj, bases.Instance):
# not abstract
return False
if baseobj is util.Uninferable:
continue
if baseobj is klass:
continue
if not isinstance(baseobj, ClassDef):
continue
if baseobj._type == "metaclass":
return True
if _is_metaclass(baseobj, seen):
return True
except exceptions.InferenceError:
continue
return False | [
"def",
"_is_metaclass",
"(",
"klass",
",",
"seen",
"=",
"None",
")",
":",
"if",
"klass",
".",
"name",
"==",
"\"type\"",
":",
"return",
"True",
"if",
"seen",
"is",
"None",
":",
"seen",
"=",
"set",
"(",
")",
"for",
"base",
"in",
"klass",
".",
"bases"... | Return if the given class can be
used as a metaclass. | [
"Return",
"if",
"the",
"given",
"class",
"can",
"be",
"used",
"as",
"a",
"metaclass",
"."
] | e0a298df55b15abcb77c2a93253f5ab7be52d0fb | https://github.com/PyCQA/astroid/blob/e0a298df55b15abcb77c2a93253f5ab7be52d0fb/astroid/scoped_nodes.py#L1719-L1750 |
227,279 | PyCQA/astroid | astroid/scoped_nodes.py | _class_type | def _class_type(klass, ancestors=None):
"""return a ClassDef node type to differ metaclass and exception
from 'regular' classes
"""
# XXX we have to store ancestors in case we have an ancestor loop
if klass._type is not None:
return klass._type
if _is_metaclass(klass):
klass._type = "metaclass"
elif klass.name.endswith("Exception"):
klass._type = "exception"
else:
if ancestors is None:
ancestors = set()
klass_name = klass.qname()
if klass_name in ancestors:
# XXX we are in loop ancestors, and have found no type
klass._type = "class"
return "class"
ancestors.add(klass_name)
for base in klass.ancestors(recurs=False):
name = _class_type(base, ancestors)
if name != "class":
if name == "metaclass" and not _is_metaclass(klass):
# don't propagate it if the current class
# can't be a metaclass
continue
klass._type = base.type
break
if klass._type is None:
klass._type = "class"
return klass._type | python | def _class_type(klass, ancestors=None):
# XXX we have to store ancestors in case we have an ancestor loop
if klass._type is not None:
return klass._type
if _is_metaclass(klass):
klass._type = "metaclass"
elif klass.name.endswith("Exception"):
klass._type = "exception"
else:
if ancestors is None:
ancestors = set()
klass_name = klass.qname()
if klass_name in ancestors:
# XXX we are in loop ancestors, and have found no type
klass._type = "class"
return "class"
ancestors.add(klass_name)
for base in klass.ancestors(recurs=False):
name = _class_type(base, ancestors)
if name != "class":
if name == "metaclass" and not _is_metaclass(klass):
# don't propagate it if the current class
# can't be a metaclass
continue
klass._type = base.type
break
if klass._type is None:
klass._type = "class"
return klass._type | [
"def",
"_class_type",
"(",
"klass",
",",
"ancestors",
"=",
"None",
")",
":",
"# XXX we have to store ancestors in case we have an ancestor loop",
"if",
"klass",
".",
"_type",
"is",
"not",
"None",
":",
"return",
"klass",
".",
"_type",
"if",
"_is_metaclass",
"(",
"k... | return a ClassDef node type to differ metaclass and exception
from 'regular' classes | [
"return",
"a",
"ClassDef",
"node",
"type",
"to",
"differ",
"metaclass",
"and",
"exception",
"from",
"regular",
"classes"
] | e0a298df55b15abcb77c2a93253f5ab7be52d0fb | https://github.com/PyCQA/astroid/blob/e0a298df55b15abcb77c2a93253f5ab7be52d0fb/astroid/scoped_nodes.py#L1753-L1784 |
227,280 | PyCQA/astroid | astroid/scoped_nodes.py | get_wrapping_class | def get_wrapping_class(node):
"""Get the class that wraps the given node.
We consider that a class wraps a node if the class
is a parent for the said node.
:returns: The class that wraps the given node
:rtype: ClassDef or None
"""
klass = node.frame()
while klass is not None and not isinstance(klass, ClassDef):
if klass.parent is None:
klass = None
else:
klass = klass.parent.frame()
return klass | python | def get_wrapping_class(node):
klass = node.frame()
while klass is not None and not isinstance(klass, ClassDef):
if klass.parent is None:
klass = None
else:
klass = klass.parent.frame()
return klass | [
"def",
"get_wrapping_class",
"(",
"node",
")",
":",
"klass",
"=",
"node",
".",
"frame",
"(",
")",
"while",
"klass",
"is",
"not",
"None",
"and",
"not",
"isinstance",
"(",
"klass",
",",
"ClassDef",
")",
":",
"if",
"klass",
".",
"parent",
"is",
"None",
... | Get the class that wraps the given node.
We consider that a class wraps a node if the class
is a parent for the said node.
:returns: The class that wraps the given node
:rtype: ClassDef or None | [
"Get",
"the",
"class",
"that",
"wraps",
"the",
"given",
"node",
"."
] | e0a298df55b15abcb77c2a93253f5ab7be52d0fb | https://github.com/PyCQA/astroid/blob/e0a298df55b15abcb77c2a93253f5ab7be52d0fb/astroid/scoped_nodes.py#L1787-L1803 |
227,281 | PyCQA/astroid | astroid/scoped_nodes.py | LocalsDictNodeNG.qname | def qname(self):
"""Get the 'qualified' name of the node.
For example: module.name, module.class.name ...
:returns: The qualified name.
:rtype: str
"""
# pylint: disable=no-member; github.com/pycqa/astroid/issues/278
if self.parent is None:
return self.name
return "%s.%s" % (self.parent.frame().qname(), self.name) | python | def qname(self):
# pylint: disable=no-member; github.com/pycqa/astroid/issues/278
if self.parent is None:
return self.name
return "%s.%s" % (self.parent.frame().qname(), self.name) | [
"def",
"qname",
"(",
"self",
")",
":",
"# pylint: disable=no-member; github.com/pycqa/astroid/issues/278",
"if",
"self",
".",
"parent",
"is",
"None",
":",
"return",
"self",
".",
"name",
"return",
"\"%s.%s\"",
"%",
"(",
"self",
".",
"parent",
".",
"frame",
"(",
... | Get the 'qualified' name of the node.
For example: module.name, module.class.name ...
:returns: The qualified name.
:rtype: str | [
"Get",
"the",
"qualified",
"name",
"of",
"the",
"node",
"."
] | e0a298df55b15abcb77c2a93253f5ab7be52d0fb | https://github.com/PyCQA/astroid/blob/e0a298df55b15abcb77c2a93253f5ab7be52d0fb/astroid/scoped_nodes.py#L145-L156 |
227,282 | PyCQA/astroid | astroid/scoped_nodes.py | LocalsDictNodeNG._scope_lookup | def _scope_lookup(self, node, name, offset=0):
"""XXX method for interfacing the scope lookup"""
try:
stmts = node._filter_stmts(self.locals[name], self, offset)
except KeyError:
stmts = ()
if stmts:
return self, stmts
if self.parent: # i.e. not Module
# nested scope: if parent scope is a function, that's fine
# else jump to the module
pscope = self.parent.scope()
if not pscope.is_function:
pscope = pscope.root()
return pscope.scope_lookup(node, name)
return builtin_lookup(name) | python | def _scope_lookup(self, node, name, offset=0):
try:
stmts = node._filter_stmts(self.locals[name], self, offset)
except KeyError:
stmts = ()
if stmts:
return self, stmts
if self.parent: # i.e. not Module
# nested scope: if parent scope is a function, that's fine
# else jump to the module
pscope = self.parent.scope()
if not pscope.is_function:
pscope = pscope.root()
return pscope.scope_lookup(node, name)
return builtin_lookup(name) | [
"def",
"_scope_lookup",
"(",
"self",
",",
"node",
",",
"name",
",",
"offset",
"=",
"0",
")",
":",
"try",
":",
"stmts",
"=",
"node",
".",
"_filter_stmts",
"(",
"self",
".",
"locals",
"[",
"name",
"]",
",",
"self",
",",
"offset",
")",
"except",
"KeyE... | XXX method for interfacing the scope lookup | [
"XXX",
"method",
"for",
"interfacing",
"the",
"scope",
"lookup"
] | e0a298df55b15abcb77c2a93253f5ab7be52d0fb | https://github.com/PyCQA/astroid/blob/e0a298df55b15abcb77c2a93253f5ab7be52d0fb/astroid/scoped_nodes.py#L177-L192 |
227,283 | PyCQA/astroid | astroid/scoped_nodes.py | LocalsDictNodeNG.set_local | def set_local(self, name, stmt):
"""Define that the given name is declared in the given statement node.
.. seealso:: :meth:`scope`
:param name: The name that is being defined.
:type name: str
:param stmt: The statement that defines the given name.
:type stmt: NodeNG
"""
# assert not stmt in self.locals.get(name, ()), (self, stmt)
self.locals.setdefault(name, []).append(stmt) | python | def set_local(self, name, stmt):
# assert not stmt in self.locals.get(name, ()), (self, stmt)
self.locals.setdefault(name, []).append(stmt) | [
"def",
"set_local",
"(",
"self",
",",
"name",
",",
"stmt",
")",
":",
"# assert not stmt in self.locals.get(name, ()), (self, stmt)",
"self",
".",
"locals",
".",
"setdefault",
"(",
"name",
",",
"[",
"]",
")",
".",
"append",
"(",
"stmt",
")"
] | Define that the given name is declared in the given statement node.
.. seealso:: :meth:`scope`
:param name: The name that is being defined.
:type name: str
:param stmt: The statement that defines the given name.
:type stmt: NodeNG | [
"Define",
"that",
"the",
"given",
"name",
"is",
"declared",
"in",
"the",
"given",
"statement",
"node",
"."
] | e0a298df55b15abcb77c2a93253f5ab7be52d0fb | https://github.com/PyCQA/astroid/blob/e0a298df55b15abcb77c2a93253f5ab7be52d0fb/astroid/scoped_nodes.py#L194-L206 |
227,284 | PyCQA/astroid | astroid/scoped_nodes.py | LocalsDictNodeNG._append_node | def _append_node(self, child):
"""append a child, linking it in the tree"""
# pylint: disable=no-member; depending by the class
# which uses the current class as a mixin or base class.
# It's rewritten in 2.0, so it makes no sense for now
# to spend development time on it.
self.body.append(child)
child.parent = self | python | def _append_node(self, child):
# pylint: disable=no-member; depending by the class
# which uses the current class as a mixin or base class.
# It's rewritten in 2.0, so it makes no sense for now
# to spend development time on it.
self.body.append(child)
child.parent = self | [
"def",
"_append_node",
"(",
"self",
",",
"child",
")",
":",
"# pylint: disable=no-member; depending by the class",
"# which uses the current class as a mixin or base class.",
"# It's rewritten in 2.0, so it makes no sense for now",
"# to spend development time on it.",
"self",
".",
"body... | append a child, linking it in the tree | [
"append",
"a",
"child",
"linking",
"it",
"in",
"the",
"tree"
] | e0a298df55b15abcb77c2a93253f5ab7be52d0fb | https://github.com/PyCQA/astroid/blob/e0a298df55b15abcb77c2a93253f5ab7be52d0fb/astroid/scoped_nodes.py#L210-L217 |
227,285 | PyCQA/astroid | astroid/scoped_nodes.py | LocalsDictNodeNG.add_local_node | def add_local_node(self, child_node, name=None):
"""Append a child that should alter the locals of this scope node.
:param child_node: The child node that will alter locals.
:type child_node: NodeNG
:param name: The name of the local that will be altered by
the given child node.
:type name: str or None
"""
if name != "__class__":
# add __class__ node as a child will cause infinite recursion later!
self._append_node(child_node)
self.set_local(name or child_node.name, child_node) | python | def add_local_node(self, child_node, name=None):
if name != "__class__":
# add __class__ node as a child will cause infinite recursion later!
self._append_node(child_node)
self.set_local(name or child_node.name, child_node) | [
"def",
"add_local_node",
"(",
"self",
",",
"child_node",
",",
"name",
"=",
"None",
")",
":",
"if",
"name",
"!=",
"\"__class__\"",
":",
"# add __class__ node as a child will cause infinite recursion later!",
"self",
".",
"_append_node",
"(",
"child_node",
")",
"self",
... | Append a child that should alter the locals of this scope node.
:param child_node: The child node that will alter locals.
:type child_node: NodeNG
:param name: The name of the local that will be altered by
the given child node.
:type name: str or None | [
"Append",
"a",
"child",
"that",
"should",
"alter",
"the",
"locals",
"of",
"this",
"scope",
"node",
"."
] | e0a298df55b15abcb77c2a93253f5ab7be52d0fb | https://github.com/PyCQA/astroid/blob/e0a298df55b15abcb77c2a93253f5ab7be52d0fb/astroid/scoped_nodes.py#L219-L232 |
227,286 | PyCQA/astroid | astroid/scoped_nodes.py | Module.scope_lookup | def scope_lookup(self, node, name, offset=0):
"""Lookup where the given variable is assigned.
:param node: The node to look for assignments up to.
Any assignments after the given node are ignored.
:type node: NodeNG
:param name: The name of the variable to find assignments for.
:type name: str
:param offset: The line offset to filter statements up to.
:type offset: int
:returns: This scope node and the list of assignments associated to the
given name according to the scope where it has been found (locals,
globals or builtin).
:rtype: tuple(str, list(NodeNG))
"""
if name in self.scope_attrs and name not in self.locals:
try:
return self, self.getattr(name)
except exceptions.AttributeInferenceError:
return self, ()
return self._scope_lookup(node, name, offset) | python | def scope_lookup(self, node, name, offset=0):
if name in self.scope_attrs and name not in self.locals:
try:
return self, self.getattr(name)
except exceptions.AttributeInferenceError:
return self, ()
return self._scope_lookup(node, name, offset) | [
"def",
"scope_lookup",
"(",
"self",
",",
"node",
",",
"name",
",",
"offset",
"=",
"0",
")",
":",
"if",
"name",
"in",
"self",
".",
"scope_attrs",
"and",
"name",
"not",
"in",
"self",
".",
"locals",
":",
"try",
":",
"return",
"self",
",",
"self",
".",... | Lookup where the given variable is assigned.
:param node: The node to look for assignments up to.
Any assignments after the given node are ignored.
:type node: NodeNG
:param name: The name of the variable to find assignments for.
:type name: str
:param offset: The line offset to filter statements up to.
:type offset: int
:returns: This scope node and the list of assignments associated to the
given name according to the scope where it has been found (locals,
globals or builtin).
:rtype: tuple(str, list(NodeNG)) | [
"Lookup",
"where",
"the",
"given",
"variable",
"is",
"assigned",
"."
] | e0a298df55b15abcb77c2a93253f5ab7be52d0fb | https://github.com/PyCQA/astroid/blob/e0a298df55b15abcb77c2a93253f5ab7be52d0fb/astroid/scoped_nodes.py#L473-L496 |
227,287 | PyCQA/astroid | astroid/scoped_nodes.py | Module.import_module | def import_module(self, modname, relative_only=False, level=None):
"""Get the ast for a given module as if imported from this module.
:param modname: The name of the module to "import".
:type modname: str
:param relative_only: Whether to only consider relative imports.
:type relative_only: bool
:param level: The level of relative import.
:type level: int or None
:returns: The imported module ast.
:rtype: NodeNG
"""
if relative_only and level is None:
level = 0
absmodname = self.relative_to_absolute_name(modname, level)
try:
return MANAGER.ast_from_module_name(absmodname)
except exceptions.AstroidBuildingError:
# we only want to import a sub module or package of this module,
# skip here
if relative_only:
raise
return MANAGER.ast_from_module_name(modname) | python | def import_module(self, modname, relative_only=False, level=None):
if relative_only and level is None:
level = 0
absmodname = self.relative_to_absolute_name(modname, level)
try:
return MANAGER.ast_from_module_name(absmodname)
except exceptions.AstroidBuildingError:
# we only want to import a sub module or package of this module,
# skip here
if relative_only:
raise
return MANAGER.ast_from_module_name(modname) | [
"def",
"import_module",
"(",
"self",
",",
"modname",
",",
"relative_only",
"=",
"False",
",",
"level",
"=",
"None",
")",
":",
"if",
"relative_only",
"and",
"level",
"is",
"None",
":",
"level",
"=",
"0",
"absmodname",
"=",
"self",
".",
"relative_to_absolute... | Get the ast for a given module as if imported from this module.
:param modname: The name of the module to "import".
:type modname: str
:param relative_only: Whether to only consider relative imports.
:type relative_only: bool
:param level: The level of relative import.
:type level: int or None
:returns: The imported module ast.
:rtype: NodeNG | [
"Get",
"the",
"ast",
"for",
"a",
"given",
"module",
"as",
"if",
"imported",
"from",
"this",
"module",
"."
] | e0a298df55b15abcb77c2a93253f5ab7be52d0fb | https://github.com/PyCQA/astroid/blob/e0a298df55b15abcb77c2a93253f5ab7be52d0fb/astroid/scoped_nodes.py#L599-L625 |
227,288 | PyCQA/astroid | astroid/scoped_nodes.py | Module.relative_to_absolute_name | def relative_to_absolute_name(self, modname, level):
"""Get the absolute module name for a relative import.
The relative import can be implicit or explicit.
:param modname: The module name to convert.
:type modname: str
:param level: The level of relative import.
:type level: int
:returns: The absolute module name.
:rtype: str
:raises TooManyLevelsError: When the relative import refers to a
module too far above this one.
"""
# XXX this returns non sens when called on an absolute import
# like 'pylint.checkers.astroid.utils'
# XXX doesn't return absolute name if self.name isn't absolute name
if self.absolute_import_activated() and level is None:
return modname
if level:
if self.package:
level = level - 1
if level and self.name.count(".") < level:
raise exceptions.TooManyLevelsError(level=level, name=self.name)
package_name = self.name.rsplit(".", level)[0]
elif self.package:
package_name = self.name
else:
package_name = self.name.rsplit(".", 1)[0]
if package_name:
if not modname:
return package_name
return "%s.%s" % (package_name, modname)
return modname | python | def relative_to_absolute_name(self, modname, level):
# XXX this returns non sens when called on an absolute import
# like 'pylint.checkers.astroid.utils'
# XXX doesn't return absolute name if self.name isn't absolute name
if self.absolute_import_activated() and level is None:
return modname
if level:
if self.package:
level = level - 1
if level and self.name.count(".") < level:
raise exceptions.TooManyLevelsError(level=level, name=self.name)
package_name = self.name.rsplit(".", level)[0]
elif self.package:
package_name = self.name
else:
package_name = self.name.rsplit(".", 1)[0]
if package_name:
if not modname:
return package_name
return "%s.%s" % (package_name, modname)
return modname | [
"def",
"relative_to_absolute_name",
"(",
"self",
",",
"modname",
",",
"level",
")",
":",
"# XXX this returns non sens when called on an absolute import",
"# like 'pylint.checkers.astroid.utils'",
"# XXX doesn't return absolute name if self.name isn't absolute name",
"if",
"self",
".",
... | Get the absolute module name for a relative import.
The relative import can be implicit or explicit.
:param modname: The module name to convert.
:type modname: str
:param level: The level of relative import.
:type level: int
:returns: The absolute module name.
:rtype: str
:raises TooManyLevelsError: When the relative import refers to a
module too far above this one. | [
"Get",
"the",
"absolute",
"module",
"name",
"for",
"a",
"relative",
"import",
"."
] | e0a298df55b15abcb77c2a93253f5ab7be52d0fb | https://github.com/PyCQA/astroid/blob/e0a298df55b15abcb77c2a93253f5ab7be52d0fb/astroid/scoped_nodes.py#L627-L665 |
227,289 | PyCQA/astroid | astroid/scoped_nodes.py | Module.wildcard_import_names | def wildcard_import_names(self):
"""The list of imported names when this module is 'wildcard imported'.
It doesn't include the '__builtins__' name which is added by the
current CPython implementation of wildcard imports.
:returns: The list of imported names.
:rtype: list(str)
"""
# We separate the different steps of lookup in try/excepts
# to avoid catching too many Exceptions
default = [name for name in self.keys() if not name.startswith("_")]
try:
all_values = self["__all__"]
except KeyError:
return default
try:
explicit = next(all_values.assigned_stmts())
except exceptions.InferenceError:
return default
except AttributeError:
# not an assignment node
# XXX infer?
return default
# Try our best to detect the exported name.
inferred = []
try:
explicit = next(explicit.infer())
except exceptions.InferenceError:
return default
if not isinstance(explicit, (node_classes.Tuple, node_classes.List)):
return default
str_const = lambda node: (
isinstance(node, node_classes.Const) and isinstance(node.value, str)
)
for node in explicit.elts:
if str_const(node):
inferred.append(node.value)
else:
try:
inferred_node = next(node.infer())
except exceptions.InferenceError:
continue
if str_const(inferred_node):
inferred.append(inferred_node.value)
return inferred | python | def wildcard_import_names(self):
# We separate the different steps of lookup in try/excepts
# to avoid catching too many Exceptions
default = [name for name in self.keys() if not name.startswith("_")]
try:
all_values = self["__all__"]
except KeyError:
return default
try:
explicit = next(all_values.assigned_stmts())
except exceptions.InferenceError:
return default
except AttributeError:
# not an assignment node
# XXX infer?
return default
# Try our best to detect the exported name.
inferred = []
try:
explicit = next(explicit.infer())
except exceptions.InferenceError:
return default
if not isinstance(explicit, (node_classes.Tuple, node_classes.List)):
return default
str_const = lambda node: (
isinstance(node, node_classes.Const) and isinstance(node.value, str)
)
for node in explicit.elts:
if str_const(node):
inferred.append(node.value)
else:
try:
inferred_node = next(node.infer())
except exceptions.InferenceError:
continue
if str_const(inferred_node):
inferred.append(inferred_node.value)
return inferred | [
"def",
"wildcard_import_names",
"(",
"self",
")",
":",
"# We separate the different steps of lookup in try/excepts",
"# to avoid catching too many Exceptions",
"default",
"=",
"[",
"name",
"for",
"name",
"in",
"self",
".",
"keys",
"(",
")",
"if",
"not",
"name",
".",
"... | The list of imported names when this module is 'wildcard imported'.
It doesn't include the '__builtins__' name which is added by the
current CPython implementation of wildcard imports.
:returns: The list of imported names.
:rtype: list(str) | [
"The",
"list",
"of",
"imported",
"names",
"when",
"this",
"module",
"is",
"wildcard",
"imported",
"."
] | e0a298df55b15abcb77c2a93253f5ab7be52d0fb | https://github.com/PyCQA/astroid/blob/e0a298df55b15abcb77c2a93253f5ab7be52d0fb/astroid/scoped_nodes.py#L667-L715 |
227,290 | PyCQA/astroid | astroid/scoped_nodes.py | Lambda.type | def type(self):
"""Whether this is a method or function.
:returns: 'method' if this is a method, 'function' otherwise.
:rtype: str
"""
# pylint: disable=no-member
if self.args.args and self.args.args[0].name == "self":
if isinstance(self.parent.scope(), ClassDef):
return "method"
return "function" | python | def type(self):
# pylint: disable=no-member
if self.args.args and self.args.args[0].name == "self":
if isinstance(self.parent.scope(), ClassDef):
return "method"
return "function" | [
"def",
"type",
"(",
"self",
")",
":",
"# pylint: disable=no-member",
"if",
"self",
".",
"args",
".",
"args",
"and",
"self",
".",
"args",
".",
"args",
"[",
"0",
"]",
".",
"name",
"==",
"\"self\"",
":",
"if",
"isinstance",
"(",
"self",
".",
"parent",
"... | Whether this is a method or function.
:returns: 'method' if this is a method, 'function' otherwise.
:rtype: str | [
"Whether",
"this",
"is",
"a",
"method",
"or",
"function",
"."
] | e0a298df55b15abcb77c2a93253f5ab7be52d0fb | https://github.com/PyCQA/astroid/blob/e0a298df55b15abcb77c2a93253f5ab7be52d0fb/astroid/scoped_nodes.py#L1085-L1095 |
227,291 | PyCQA/astroid | astroid/scoped_nodes.py | Lambda.argnames | def argnames(self):
"""Get the names of each of the arguments.
:returns: The names of the arguments.
:rtype: list(str)
"""
# pylint: disable=no-member; github.com/pycqa/astroid/issues/291
# args is in fact redefined later on by postinit. Can't be changed
# to None due to a strong interaction between Lambda and FunctionDef.
if self.args.args: # maybe None with builtin functions
names = _rec_get_names(self.args.args)
else:
names = []
if self.args.vararg:
names.append(self.args.vararg)
if self.args.kwarg:
names.append(self.args.kwarg)
return names | python | def argnames(self):
# pylint: disable=no-member; github.com/pycqa/astroid/issues/291
# args is in fact redefined later on by postinit. Can't be changed
# to None due to a strong interaction between Lambda and FunctionDef.
if self.args.args: # maybe None with builtin functions
names = _rec_get_names(self.args.args)
else:
names = []
if self.args.vararg:
names.append(self.args.vararg)
if self.args.kwarg:
names.append(self.args.kwarg)
return names | [
"def",
"argnames",
"(",
"self",
")",
":",
"# pylint: disable=no-member; github.com/pycqa/astroid/issues/291",
"# args is in fact redefined later on by postinit. Can't be changed",
"# to None due to a strong interaction between Lambda and FunctionDef.",
"if",
"self",
".",
"args",
".",
"ar... | Get the names of each of the arguments.
:returns: The names of the arguments.
:rtype: list(str) | [
"Get",
"the",
"names",
"of",
"each",
"of",
"the",
"arguments",
"."
] | e0a298df55b15abcb77c2a93253f5ab7be52d0fb | https://github.com/PyCQA/astroid/blob/e0a298df55b15abcb77c2a93253f5ab7be52d0fb/astroid/scoped_nodes.py#L1171-L1189 |
227,292 | PyCQA/astroid | astroid/scoped_nodes.py | Lambda.scope_lookup | def scope_lookup(self, node, name, offset=0):
"""Lookup where the given names is assigned.
:param node: The node to look for assignments up to.
Any assignments after the given node are ignored.
:type node: NodeNG
:param name: The name to find assignments for.
:type name: str
:param offset: The line offset to filter statements up to.
:type offset: int
:returns: This scope node and the list of assignments associated to the
given name according to the scope where it has been found (locals,
globals or builtin).
:rtype: tuple(str, list(NodeNG))
"""
# pylint: disable=no-member; github.com/pycqa/astroid/issues/291
# args is in fact redefined later on by postinit. Can't be changed
# to None due to a strong interaction between Lambda and FunctionDef.
if node in self.args.defaults or node in self.args.kw_defaults:
frame = self.parent.frame()
# line offset to avoid that def func(f=func) resolve the default
# value to the defined function
offset = -1
else:
# check this is not used in function decorators
frame = self
return frame._scope_lookup(node, name, offset) | python | def scope_lookup(self, node, name, offset=0):
# pylint: disable=no-member; github.com/pycqa/astroid/issues/291
# args is in fact redefined later on by postinit. Can't be changed
# to None due to a strong interaction between Lambda and FunctionDef.
if node in self.args.defaults or node in self.args.kw_defaults:
frame = self.parent.frame()
# line offset to avoid that def func(f=func) resolve the default
# value to the defined function
offset = -1
else:
# check this is not used in function decorators
frame = self
return frame._scope_lookup(node, name, offset) | [
"def",
"scope_lookup",
"(",
"self",
",",
"node",
",",
"name",
",",
"offset",
"=",
"0",
")",
":",
"# pylint: disable=no-member; github.com/pycqa/astroid/issues/291",
"# args is in fact redefined later on by postinit. Can't be changed",
"# to None due to a strong interaction between La... | Lookup where the given names is assigned.
:param node: The node to look for assignments up to.
Any assignments after the given node are ignored.
:type node: NodeNG
:param name: The name to find assignments for.
:type name: str
:param offset: The line offset to filter statements up to.
:type offset: int
:returns: This scope node and the list of assignments associated to the
given name according to the scope where it has been found (locals,
globals or builtin).
:rtype: tuple(str, list(NodeNG)) | [
"Lookup",
"where",
"the",
"given",
"names",
"is",
"assigned",
"."
] | e0a298df55b15abcb77c2a93253f5ab7be52d0fb | https://github.com/PyCQA/astroid/blob/e0a298df55b15abcb77c2a93253f5ab7be52d0fb/astroid/scoped_nodes.py#L1202-L1232 |
227,293 | PyCQA/astroid | astroid/scoped_nodes.py | FunctionDef.extra_decorators | def extra_decorators(self):
"""The extra decorators that this function can have.
Additional decorators are considered when they are used as
assignments, as in ``method = staticmethod(method)``.
The property will return all the callables that are used for
decoration.
:type: list(NodeNG)
"""
frame = self.parent.frame()
if not isinstance(frame, ClassDef):
return []
decorators = []
for assign in frame._get_assign_nodes():
if isinstance(assign.value, node_classes.Call) and isinstance(
assign.value.func, node_classes.Name
):
for assign_node in assign.targets:
if not isinstance(assign_node, node_classes.AssignName):
# Support only `name = callable(name)`
continue
if assign_node.name != self.name:
# Interested only in the assignment nodes that
# decorates the current method.
continue
try:
meth = frame[self.name]
except KeyError:
continue
else:
# Must be a function and in the same frame as the
# original method.
if (
isinstance(meth, FunctionDef)
and assign_node.frame() == frame
):
decorators.append(assign.value)
return decorators | python | def extra_decorators(self):
frame = self.parent.frame()
if not isinstance(frame, ClassDef):
return []
decorators = []
for assign in frame._get_assign_nodes():
if isinstance(assign.value, node_classes.Call) and isinstance(
assign.value.func, node_classes.Name
):
for assign_node in assign.targets:
if not isinstance(assign_node, node_classes.AssignName):
# Support only `name = callable(name)`
continue
if assign_node.name != self.name:
# Interested only in the assignment nodes that
# decorates the current method.
continue
try:
meth = frame[self.name]
except KeyError:
continue
else:
# Must be a function and in the same frame as the
# original method.
if (
isinstance(meth, FunctionDef)
and assign_node.frame() == frame
):
decorators.append(assign.value)
return decorators | [
"def",
"extra_decorators",
"(",
"self",
")",
":",
"frame",
"=",
"self",
".",
"parent",
".",
"frame",
"(",
")",
"if",
"not",
"isinstance",
"(",
"frame",
",",
"ClassDef",
")",
":",
"return",
"[",
"]",
"decorators",
"=",
"[",
"]",
"for",
"assign",
"in",... | The extra decorators that this function can have.
Additional decorators are considered when they are used as
assignments, as in ``method = staticmethod(method)``.
The property will return all the callables that are used for
decoration.
:type: list(NodeNG) | [
"The",
"extra",
"decorators",
"that",
"this",
"function",
"can",
"have",
"."
] | e0a298df55b15abcb77c2a93253f5ab7be52d0fb | https://github.com/PyCQA/astroid/blob/e0a298df55b15abcb77c2a93253f5ab7be52d0fb/astroid/scoped_nodes.py#L1374-L1414 |
227,294 | PyCQA/astroid | astroid/scoped_nodes.py | FunctionDef.type | def type(self):
"""The function type for this node.
Possible values are: method, function, staticmethod, classmethod.
:type: str
"""
builtin_descriptors = {"classmethod", "staticmethod"}
for decorator in self.extra_decorators:
if decorator.func.name in builtin_descriptors:
return decorator.func.name
frame = self.parent.frame()
type_name = "function"
if isinstance(frame, ClassDef):
if self.name == "__new__":
return "classmethod"
if sys.version_info >= (3, 6) and self.name == "__init_subclass__":
return "classmethod"
type_name = "method"
if not self.decorators:
return type_name
for node in self.decorators.nodes:
if isinstance(node, node_classes.Name):
if node.name in builtin_descriptors:
return node.name
if isinstance(node, node_classes.Call):
# Handle the following case:
# @some_decorator(arg1, arg2)
# def func(...)
#
try:
current = next(node.func.infer())
except exceptions.InferenceError:
continue
_type = _infer_decorator_callchain(current)
if _type is not None:
return _type
try:
for inferred in node.infer():
# Check to see if this returns a static or a class method.
_type = _infer_decorator_callchain(inferred)
if _type is not None:
return _type
if not isinstance(inferred, ClassDef):
continue
for ancestor in inferred.ancestors():
if not isinstance(ancestor, ClassDef):
continue
if ancestor.is_subtype_of("%s.classmethod" % BUILTINS):
return "classmethod"
if ancestor.is_subtype_of("%s.staticmethod" % BUILTINS):
return "staticmethod"
except exceptions.InferenceError:
pass
return type_name | python | def type(self):
builtin_descriptors = {"classmethod", "staticmethod"}
for decorator in self.extra_decorators:
if decorator.func.name in builtin_descriptors:
return decorator.func.name
frame = self.parent.frame()
type_name = "function"
if isinstance(frame, ClassDef):
if self.name == "__new__":
return "classmethod"
if sys.version_info >= (3, 6) and self.name == "__init_subclass__":
return "classmethod"
type_name = "method"
if not self.decorators:
return type_name
for node in self.decorators.nodes:
if isinstance(node, node_classes.Name):
if node.name in builtin_descriptors:
return node.name
if isinstance(node, node_classes.Call):
# Handle the following case:
# @some_decorator(arg1, arg2)
# def func(...)
#
try:
current = next(node.func.infer())
except exceptions.InferenceError:
continue
_type = _infer_decorator_callchain(current)
if _type is not None:
return _type
try:
for inferred in node.infer():
# Check to see if this returns a static or a class method.
_type = _infer_decorator_callchain(inferred)
if _type is not None:
return _type
if not isinstance(inferred, ClassDef):
continue
for ancestor in inferred.ancestors():
if not isinstance(ancestor, ClassDef):
continue
if ancestor.is_subtype_of("%s.classmethod" % BUILTINS):
return "classmethod"
if ancestor.is_subtype_of("%s.staticmethod" % BUILTINS):
return "staticmethod"
except exceptions.InferenceError:
pass
return type_name | [
"def",
"type",
"(",
"self",
")",
":",
"builtin_descriptors",
"=",
"{",
"\"classmethod\"",
",",
"\"staticmethod\"",
"}",
"for",
"decorator",
"in",
"self",
".",
"extra_decorators",
":",
"if",
"decorator",
".",
"func",
".",
"name",
"in",
"builtin_descriptors",
":... | The function type for this node.
Possible values are: method, function, staticmethod, classmethod.
:type: str | [
"The",
"function",
"type",
"for",
"this",
"node",
"."
] | e0a298df55b15abcb77c2a93253f5ab7be52d0fb | https://github.com/PyCQA/astroid/blob/e0a298df55b15abcb77c2a93253f5ab7be52d0fb/astroid/scoped_nodes.py#L1417-L1479 |
227,295 | PyCQA/astroid | astroid/scoped_nodes.py | FunctionDef.getattr | def getattr(self, name, context=None):
"""this method doesn't look in the instance_attrs dictionary since it's
done by an Instance proxy at inference time.
"""
if name in self.instance_attrs:
return self.instance_attrs[name]
if name in self.special_attributes:
return [self.special_attributes.lookup(name)]
raise exceptions.AttributeInferenceError(target=self, attribute=name) | python | def getattr(self, name, context=None):
if name in self.instance_attrs:
return self.instance_attrs[name]
if name in self.special_attributes:
return [self.special_attributes.lookup(name)]
raise exceptions.AttributeInferenceError(target=self, attribute=name) | [
"def",
"getattr",
"(",
"self",
",",
"name",
",",
"context",
"=",
"None",
")",
":",
"if",
"name",
"in",
"self",
".",
"instance_attrs",
":",
"return",
"self",
".",
"instance_attrs",
"[",
"name",
"]",
"if",
"name",
"in",
"self",
".",
"special_attributes",
... | this method doesn't look in the instance_attrs dictionary since it's
done by an Instance proxy at inference time. | [
"this",
"method",
"doesn",
"t",
"look",
"in",
"the",
"instance_attrs",
"dictionary",
"since",
"it",
"s",
"done",
"by",
"an",
"Instance",
"proxy",
"at",
"inference",
"time",
"."
] | e0a298df55b15abcb77c2a93253f5ab7be52d0fb | https://github.com/PyCQA/astroid/blob/e0a298df55b15abcb77c2a93253f5ab7be52d0fb/astroid/scoped_nodes.py#L1516-L1524 |
227,296 | PyCQA/astroid | astroid/scoped_nodes.py | FunctionDef.igetattr | def igetattr(self, name, context=None):
"""Inferred getattr, which returns an iterator of inferred statements."""
try:
return bases._infer_stmts(self.getattr(name, context), context, frame=self)
except exceptions.AttributeInferenceError as error:
raise exceptions.InferenceError(
error.message, target=self, attribute=name, context=context
) from error | python | def igetattr(self, name, context=None):
try:
return bases._infer_stmts(self.getattr(name, context), context, frame=self)
except exceptions.AttributeInferenceError as error:
raise exceptions.InferenceError(
error.message, target=self, attribute=name, context=context
) from error | [
"def",
"igetattr",
"(",
"self",
",",
"name",
",",
"context",
"=",
"None",
")",
":",
"try",
":",
"return",
"bases",
".",
"_infer_stmts",
"(",
"self",
".",
"getattr",
"(",
"name",
",",
"context",
")",
",",
"context",
",",
"frame",
"=",
"self",
")",
"... | Inferred getattr, which returns an iterator of inferred statements. | [
"Inferred",
"getattr",
"which",
"returns",
"an",
"iterator",
"of",
"inferred",
"statements",
"."
] | e0a298df55b15abcb77c2a93253f5ab7be52d0fb | https://github.com/PyCQA/astroid/blob/e0a298df55b15abcb77c2a93253f5ab7be52d0fb/astroid/scoped_nodes.py#L1526-L1533 |
227,297 | PyCQA/astroid | astroid/scoped_nodes.py | FunctionDef.decoratornames | def decoratornames(self):
"""Get the qualified names of each of the decorators on this function.
:returns: The names of the decorators.
:rtype: set(str)
"""
result = set()
decoratornodes = []
if self.decorators is not None:
decoratornodes += self.decorators.nodes
decoratornodes += self.extra_decorators
for decnode in decoratornodes:
try:
for infnode in decnode.infer():
result.add(infnode.qname())
except exceptions.InferenceError:
continue
return result | python | def decoratornames(self):
result = set()
decoratornodes = []
if self.decorators is not None:
decoratornodes += self.decorators.nodes
decoratornodes += self.extra_decorators
for decnode in decoratornodes:
try:
for infnode in decnode.infer():
result.add(infnode.qname())
except exceptions.InferenceError:
continue
return result | [
"def",
"decoratornames",
"(",
"self",
")",
":",
"result",
"=",
"set",
"(",
")",
"decoratornodes",
"=",
"[",
"]",
"if",
"self",
".",
"decorators",
"is",
"not",
"None",
":",
"decoratornodes",
"+=",
"self",
".",
"decorators",
".",
"nodes",
"decoratornodes",
... | Get the qualified names of each of the decorators on this function.
:returns: The names of the decorators.
:rtype: set(str) | [
"Get",
"the",
"qualified",
"names",
"of",
"each",
"of",
"the",
"decorators",
"on",
"this",
"function",
"."
] | e0a298df55b15abcb77c2a93253f5ab7be52d0fb | https://github.com/PyCQA/astroid/blob/e0a298df55b15abcb77c2a93253f5ab7be52d0fb/astroid/scoped_nodes.py#L1546-L1563 |
227,298 | PyCQA/astroid | astroid/scoped_nodes.py | FunctionDef.is_abstract | def is_abstract(self, pass_is_abstract=True):
"""Check if the method is abstract.
A method is considered abstract if any of the following is true:
* The only statement is 'raise NotImplementedError'
* The only statement is 'pass' and pass_is_abstract is True
* The method is annotated with abc.astractproperty/abc.abstractmethod
:returns: True if the method is abstract, False otherwise.
:rtype: bool
"""
if self.decorators:
for node in self.decorators.nodes:
try:
inferred = next(node.infer())
except exceptions.InferenceError:
continue
if inferred and inferred.qname() in (
"abc.abstractproperty",
"abc.abstractmethod",
):
return True
for child_node in self.body:
if isinstance(child_node, node_classes.Raise):
if child_node.raises_not_implemented():
return True
return pass_is_abstract and isinstance(child_node, node_classes.Pass)
# empty function is the same as function with a single "pass" statement
if pass_is_abstract:
return True | python | def is_abstract(self, pass_is_abstract=True):
if self.decorators:
for node in self.decorators.nodes:
try:
inferred = next(node.infer())
except exceptions.InferenceError:
continue
if inferred and inferred.qname() in (
"abc.abstractproperty",
"abc.abstractmethod",
):
return True
for child_node in self.body:
if isinstance(child_node, node_classes.Raise):
if child_node.raises_not_implemented():
return True
return pass_is_abstract and isinstance(child_node, node_classes.Pass)
# empty function is the same as function with a single "pass" statement
if pass_is_abstract:
return True | [
"def",
"is_abstract",
"(",
"self",
",",
"pass_is_abstract",
"=",
"True",
")",
":",
"if",
"self",
".",
"decorators",
":",
"for",
"node",
"in",
"self",
".",
"decorators",
".",
"nodes",
":",
"try",
":",
"inferred",
"=",
"next",
"(",
"node",
".",
"infer",
... | Check if the method is abstract.
A method is considered abstract if any of the following is true:
* The only statement is 'raise NotImplementedError'
* The only statement is 'pass' and pass_is_abstract is True
* The method is annotated with abc.astractproperty/abc.abstractmethod
:returns: True if the method is abstract, False otherwise.
:rtype: bool | [
"Check",
"if",
"the",
"method",
"is",
"abstract",
"."
] | e0a298df55b15abcb77c2a93253f5ab7be52d0fb | https://github.com/PyCQA/astroid/blob/e0a298df55b15abcb77c2a93253f5ab7be52d0fb/astroid/scoped_nodes.py#L1574-L1604 |
227,299 | PyCQA/astroid | astroid/scoped_nodes.py | FunctionDef.infer_call_result | def infer_call_result(self, caller=None, context=None):
"""Infer what the function returns when called.
:returns: What the function returns.
:rtype: iterable(NodeNG or Uninferable) or None
"""
if self.is_generator():
if isinstance(self, AsyncFunctionDef):
generator_cls = bases.AsyncGenerator
else:
generator_cls = bases.Generator
result = generator_cls(self)
yield result
return
# This is really a gigantic hack to work around metaclass generators
# that return transient class-generating functions. Pylint's AST structure
# cannot handle a base class object that is only used for calling __new__,
# but does not contribute to the inheritance structure itself. We inject
# a fake class into the hierarchy here for several well-known metaclass
# generators, and filter it out later.
if (
self.name == "with_metaclass"
and len(self.args.args) == 1
and self.args.vararg is not None
):
metaclass = next(caller.args[0].infer(context))
if isinstance(metaclass, ClassDef):
class_bases = [next(arg.infer(context)) for arg in caller.args[1:]]
new_class = ClassDef(name="temporary_class")
new_class.hide = True
new_class.parent = self
new_class.postinit(
bases=[base for base in class_bases if base != util.Uninferable],
body=[],
decorators=[],
metaclass=metaclass,
)
yield new_class
return
returns = self._get_return_nodes_skip_functions()
first_return = next(returns, None)
if not first_return:
raise exceptions.InferenceError("Empty return iterator")
for returnnode in itertools.chain((first_return,), returns):
if returnnode.value is None:
yield node_classes.Const(None)
else:
try:
yield from returnnode.value.infer(context)
except exceptions.InferenceError:
yield util.Uninferable | python | def infer_call_result(self, caller=None, context=None):
if self.is_generator():
if isinstance(self, AsyncFunctionDef):
generator_cls = bases.AsyncGenerator
else:
generator_cls = bases.Generator
result = generator_cls(self)
yield result
return
# This is really a gigantic hack to work around metaclass generators
# that return transient class-generating functions. Pylint's AST structure
# cannot handle a base class object that is only used for calling __new__,
# but does not contribute to the inheritance structure itself. We inject
# a fake class into the hierarchy here for several well-known metaclass
# generators, and filter it out later.
if (
self.name == "with_metaclass"
and len(self.args.args) == 1
and self.args.vararg is not None
):
metaclass = next(caller.args[0].infer(context))
if isinstance(metaclass, ClassDef):
class_bases = [next(arg.infer(context)) for arg in caller.args[1:]]
new_class = ClassDef(name="temporary_class")
new_class.hide = True
new_class.parent = self
new_class.postinit(
bases=[base for base in class_bases if base != util.Uninferable],
body=[],
decorators=[],
metaclass=metaclass,
)
yield new_class
return
returns = self._get_return_nodes_skip_functions()
first_return = next(returns, None)
if not first_return:
raise exceptions.InferenceError("Empty return iterator")
for returnnode in itertools.chain((first_return,), returns):
if returnnode.value is None:
yield node_classes.Const(None)
else:
try:
yield from returnnode.value.infer(context)
except exceptions.InferenceError:
yield util.Uninferable | [
"def",
"infer_call_result",
"(",
"self",
",",
"caller",
"=",
"None",
",",
"context",
"=",
"None",
")",
":",
"if",
"self",
".",
"is_generator",
"(",
")",
":",
"if",
"isinstance",
"(",
"self",
",",
"AsyncFunctionDef",
")",
":",
"generator_cls",
"=",
"bases... | Infer what the function returns when called.
:returns: What the function returns.
:rtype: iterable(NodeNG or Uninferable) or None | [
"Infer",
"what",
"the",
"function",
"returns",
"when",
"called",
"."
] | e0a298df55b15abcb77c2a93253f5ab7be52d0fb | https://github.com/PyCQA/astroid/blob/e0a298df55b15abcb77c2a93253f5ab7be52d0fb/astroid/scoped_nodes.py#L1614-L1666 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.