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,300 | PyCQA/astroid | astroid/scoped_nodes.py | ClassDef.implicit_locals | def implicit_locals(self):
"""Get implicitly defined class definition locals.
:returns: the the name and Const pair for each local
:rtype: tuple(tuple(str, node_classes.Const), ...)
"""
locals_ = (("__module__", self.special_attributes.attr___module__),)
if sys.version_info >= (3, 3):
# __qualname__ is defined in PEP3155
locals_ += (("__qualname__", self.special_attributes.attr___qualname__),)
return locals_ | python | def implicit_locals(self):
locals_ = (("__module__", self.special_attributes.attr___module__),)
if sys.version_info >= (3, 3):
# __qualname__ is defined in PEP3155
locals_ += (("__qualname__", self.special_attributes.attr___qualname__),)
return locals_ | [
"def",
"implicit_locals",
"(",
"self",
")",
":",
"locals_",
"=",
"(",
"(",
"\"__module__\"",
",",
"self",
".",
"special_attributes",
".",
"attr___module__",
")",
",",
")",
"if",
"sys",
".",
"version_info",
">=",
"(",
"3",
",",
"3",
")",
":",
"# __qualnam... | Get implicitly defined class definition locals.
:returns: the the name and Const pair for each local
:rtype: tuple(tuple(str, node_classes.Const), ...) | [
"Get",
"implicitly",
"defined",
"class",
"definition",
"locals",
"."
] | e0a298df55b15abcb77c2a93253f5ab7be52d0fb | https://github.com/PyCQA/astroid/blob/e0a298df55b15abcb77c2a93253f5ab7be52d0fb/astroid/scoped_nodes.py#L1917-L1927 |
227,301 | PyCQA/astroid | astroid/scoped_nodes.py | ClassDef.is_subtype_of | def is_subtype_of(self, type_name, context=None):
"""Whether this class is a subtype of the given type.
:param type_name: The name of the type of check against.
:type type_name: str
:returns: True if this class is a subtype of the given type,
False otherwise.
:rtype: bool
"""
if self.qname() == type_name:
return True
for anc in self.ancestors(context=context):
if anc.qname() == type_name:
return True
return False | python | def is_subtype_of(self, type_name, context=None):
if self.qname() == type_name:
return True
for anc in self.ancestors(context=context):
if anc.qname() == type_name:
return True
return False | [
"def",
"is_subtype_of",
"(",
"self",
",",
"type_name",
",",
"context",
"=",
"None",
")",
":",
"if",
"self",
".",
"qname",
"(",
")",
"==",
"type_name",
":",
"return",
"True",
"for",
"anc",
"in",
"self",
".",
"ancestors",
"(",
"context",
"=",
"context",
... | Whether this class is a subtype of the given type.
:param type_name: The name of the type of check against.
:type type_name: str
:returns: True if this class is a subtype of the given type,
False otherwise.
:rtype: bool | [
"Whether",
"this",
"class",
"is",
"a",
"subtype",
"of",
"the",
"given",
"type",
"."
] | e0a298df55b15abcb77c2a93253f5ab7be52d0fb | https://github.com/PyCQA/astroid/blob/e0a298df55b15abcb77c2a93253f5ab7be52d0fb/astroid/scoped_nodes.py#L2036-L2051 |
227,302 | PyCQA/astroid | astroid/scoped_nodes.py | ClassDef.infer_call_result | def infer_call_result(self, caller, context=None):
"""infer what a class is returning when called"""
if (
self.is_subtype_of("%s.type" % (BUILTINS,), context)
and len(caller.args) == 3
):
result = self._infer_type_call(caller, context)
yield result
return
dunder_call = None
try:
metaclass = self.metaclass(context=context)
if metaclass is not None:
dunder_call = next(metaclass.igetattr("__call__", context))
except exceptions.AttributeInferenceError:
pass
if dunder_call and dunder_call.qname() != "builtins.type.__call__":
context = contextmod.bind_context_to_node(context, self)
yield from dunder_call.infer_call_result(caller, context)
else:
# Call type.__call__ if not set metaclass
# (since type is the default metaclass)
yield bases.Instance(self) | python | def infer_call_result(self, caller, context=None):
if (
self.is_subtype_of("%s.type" % (BUILTINS,), context)
and len(caller.args) == 3
):
result = self._infer_type_call(caller, context)
yield result
return
dunder_call = None
try:
metaclass = self.metaclass(context=context)
if metaclass is not None:
dunder_call = next(metaclass.igetattr("__call__", context))
except exceptions.AttributeInferenceError:
pass
if dunder_call and dunder_call.qname() != "builtins.type.__call__":
context = contextmod.bind_context_to_node(context, self)
yield from dunder_call.infer_call_result(caller, context)
else:
# Call type.__call__ if not set metaclass
# (since type is the default metaclass)
yield bases.Instance(self) | [
"def",
"infer_call_result",
"(",
"self",
",",
"caller",
",",
"context",
"=",
"None",
")",
":",
"if",
"(",
"self",
".",
"is_subtype_of",
"(",
"\"%s.type\"",
"%",
"(",
"BUILTINS",
",",
")",
",",
"context",
")",
"and",
"len",
"(",
"caller",
".",
"args",
... | infer what a class is returning when called | [
"infer",
"what",
"a",
"class",
"is",
"returning",
"when",
"called"
] | e0a298df55b15abcb77c2a93253f5ab7be52d0fb | https://github.com/PyCQA/astroid/blob/e0a298df55b15abcb77c2a93253f5ab7be52d0fb/astroid/scoped_nodes.py#L2088-L2111 |
227,303 | PyCQA/astroid | astroid/scoped_nodes.py | ClassDef.scope_lookup | def scope_lookup(self, node, name, offset=0):
"""Lookup where the given name 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))
"""
# If the name looks like a builtin name, just try to look
# into the upper scope of this class. We might have a
# decorator that it's poorly named after a builtin object
# inside this class.
lookup_upper_frame = (
isinstance(node.parent, node_classes.Decorators)
and name in MANAGER.builtins_module
)
if (
any(node == base or base.parent_of(node) for base in self.bases)
or lookup_upper_frame
):
# Handle the case where we have either a name
# in the bases of a class, which exists before
# the actual definition or the case where we have
# a Getattr node, with that name.
#
# name = ...
# class A(name):
# def name(self): ...
#
# import name
# class A(name.Name):
# def name(self): ...
frame = self.parent.frame()
# line offset to avoid that class A(A) resolve the ancestor to
# the defined class
offset = -1
else:
frame = self
return frame._scope_lookup(node, name, offset) | python | def scope_lookup(self, node, name, offset=0):
# If the name looks like a builtin name, just try to look
# into the upper scope of this class. We might have a
# decorator that it's poorly named after a builtin object
# inside this class.
lookup_upper_frame = (
isinstance(node.parent, node_classes.Decorators)
and name in MANAGER.builtins_module
)
if (
any(node == base or base.parent_of(node) for base in self.bases)
or lookup_upper_frame
):
# Handle the case where we have either a name
# in the bases of a class, which exists before
# the actual definition or the case where we have
# a Getattr node, with that name.
#
# name = ...
# class A(name):
# def name(self): ...
#
# import name
# class A(name.Name):
# def name(self): ...
frame = self.parent.frame()
# line offset to avoid that class A(A) resolve the ancestor to
# the defined class
offset = -1
else:
frame = self
return frame._scope_lookup(node, name, offset) | [
"def",
"scope_lookup",
"(",
"self",
",",
"node",
",",
"name",
",",
"offset",
"=",
"0",
")",
":",
"# If the name looks like a builtin name, just try to look",
"# into the upper scope of this class. We might have a",
"# decorator that it's poorly named after a builtin object",
"# ins... | Lookup where the given name 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",
"name",
"is",
"assigned",
"."
] | e0a298df55b15abcb77c2a93253f5ab7be52d0fb | https://github.com/PyCQA/astroid/blob/e0a298df55b15abcb77c2a93253f5ab7be52d0fb/astroid/scoped_nodes.py#L2113-L2162 |
227,304 | PyCQA/astroid | astroid/scoped_nodes.py | ClassDef.ancestors | def ancestors(self, recurs=True, context=None):
"""Iterate over the base classes in prefixed depth first order.
:param recurs: Whether to recurse or return direct ancestors only.
:type recurs: bool
:returns: The base classes
:rtype: iterable(NodeNG)
"""
# FIXME: should be possible to choose the resolution order
# FIXME: inference make infinite loops possible here
yielded = {self}
if context is None:
context = contextmod.InferenceContext()
if not self.bases and self.qname() != "builtins.object":
yield builtin_lookup("object")[1][0]
return
for stmt in self.bases:
with context.restore_path():
try:
for baseobj in stmt.infer(context):
if not isinstance(baseobj, ClassDef):
if isinstance(baseobj, bases.Instance):
baseobj = baseobj._proxied
else:
continue
if not baseobj.hide:
if baseobj in yielded:
continue
yielded.add(baseobj)
yield baseobj
if not recurs:
continue
for grandpa in baseobj.ancestors(recurs=True, context=context):
if grandpa is self:
# This class is the ancestor of itself.
break
if grandpa in yielded:
continue
yielded.add(grandpa)
yield grandpa
except exceptions.InferenceError:
continue | python | def ancestors(self, recurs=True, context=None):
# FIXME: should be possible to choose the resolution order
# FIXME: inference make infinite loops possible here
yielded = {self}
if context is None:
context = contextmod.InferenceContext()
if not self.bases and self.qname() != "builtins.object":
yield builtin_lookup("object")[1][0]
return
for stmt in self.bases:
with context.restore_path():
try:
for baseobj in stmt.infer(context):
if not isinstance(baseobj, ClassDef):
if isinstance(baseobj, bases.Instance):
baseobj = baseobj._proxied
else:
continue
if not baseobj.hide:
if baseobj in yielded:
continue
yielded.add(baseobj)
yield baseobj
if not recurs:
continue
for grandpa in baseobj.ancestors(recurs=True, context=context):
if grandpa is self:
# This class is the ancestor of itself.
break
if grandpa in yielded:
continue
yielded.add(grandpa)
yield grandpa
except exceptions.InferenceError:
continue | [
"def",
"ancestors",
"(",
"self",
",",
"recurs",
"=",
"True",
",",
"context",
"=",
"None",
")",
":",
"# FIXME: should be possible to choose the resolution order",
"# FIXME: inference make infinite loops possible here",
"yielded",
"=",
"{",
"self",
"}",
"if",
"context",
"... | Iterate over the base classes in prefixed depth first order.
:param recurs: Whether to recurse or return direct ancestors only.
:type recurs: bool
:returns: The base classes
:rtype: iterable(NodeNG) | [
"Iterate",
"over",
"the",
"base",
"classes",
"in",
"prefixed",
"depth",
"first",
"order",
"."
] | e0a298df55b15abcb77c2a93253f5ab7be52d0fb | https://github.com/PyCQA/astroid/blob/e0a298df55b15abcb77c2a93253f5ab7be52d0fb/astroid/scoped_nodes.py#L2174-L2217 |
227,305 | PyCQA/astroid | astroid/scoped_nodes.py | ClassDef.local_attr_ancestors | def local_attr_ancestors(self, name, context=None):
"""Iterate over the parents that define the given name.
:param name: The name to find definitions for.
:type name: str
:returns: The parents that define the given name.
:rtype: iterable(NodeNG)
"""
# Look up in the mro if we can. This will result in the
# attribute being looked up just as Python does it.
try:
ancestors = self.mro(context)[1:]
except exceptions.MroError:
# Fallback to use ancestors, we can't determine
# a sane MRO.
ancestors = self.ancestors(context=context)
for astroid in ancestors:
if name in astroid:
yield astroid | python | def local_attr_ancestors(self, name, context=None):
# Look up in the mro if we can. This will result in the
# attribute being looked up just as Python does it.
try:
ancestors = self.mro(context)[1:]
except exceptions.MroError:
# Fallback to use ancestors, we can't determine
# a sane MRO.
ancestors = self.ancestors(context=context)
for astroid in ancestors:
if name in astroid:
yield astroid | [
"def",
"local_attr_ancestors",
"(",
"self",
",",
"name",
",",
"context",
"=",
"None",
")",
":",
"# Look up in the mro if we can. This will result in the",
"# attribute being looked up just as Python does it.",
"try",
":",
"ancestors",
"=",
"self",
".",
"mro",
"(",
"contex... | Iterate over the parents that define the given name.
:param name: The name to find definitions for.
:type name: str
:returns: The parents that define the given name.
:rtype: iterable(NodeNG) | [
"Iterate",
"over",
"the",
"parents",
"that",
"define",
"the",
"given",
"name",
"."
] | e0a298df55b15abcb77c2a93253f5ab7be52d0fb | https://github.com/PyCQA/astroid/blob/e0a298df55b15abcb77c2a93253f5ab7be52d0fb/astroid/scoped_nodes.py#L2219-L2238 |
227,306 | PyCQA/astroid | astroid/scoped_nodes.py | ClassDef.instance_attr_ancestors | def instance_attr_ancestors(self, name, context=None):
"""Iterate over the parents that define the given name as an attribute.
:param name: The name to find definitions for.
:type name: str
:returns: The parents that define the given name as
an instance attribute.
:rtype: iterable(NodeNG)
"""
for astroid in self.ancestors(context=context):
if name in astroid.instance_attrs:
yield astroid | python | def instance_attr_ancestors(self, name, context=None):
for astroid in self.ancestors(context=context):
if name in astroid.instance_attrs:
yield astroid | [
"def",
"instance_attr_ancestors",
"(",
"self",
",",
"name",
",",
"context",
"=",
"None",
")",
":",
"for",
"astroid",
"in",
"self",
".",
"ancestors",
"(",
"context",
"=",
"context",
")",
":",
"if",
"name",
"in",
"astroid",
".",
"instance_attrs",
":",
"yie... | Iterate over the parents that define the given name as an attribute.
:param name: The name to find definitions for.
:type name: str
:returns: The parents that define the given name as
an instance attribute.
:rtype: iterable(NodeNG) | [
"Iterate",
"over",
"the",
"parents",
"that",
"define",
"the",
"given",
"name",
"as",
"an",
"attribute",
"."
] | e0a298df55b15abcb77c2a93253f5ab7be52d0fb | https://github.com/PyCQA/astroid/blob/e0a298df55b15abcb77c2a93253f5ab7be52d0fb/astroid/scoped_nodes.py#L2240-L2252 |
227,307 | PyCQA/astroid | astroid/scoped_nodes.py | ClassDef.local_attr | def local_attr(self, name, context=None):
"""Get the list of assign nodes associated to the given name.
Assignments are looked for in both this class and in parents.
:returns: The list of assignments to the given name.
:rtype: list(NodeNG)
:raises AttributeInferenceError: If no attribute with this name
can be found in this class or parent classes.
"""
result = []
if name in self.locals:
result = self.locals[name]
else:
class_node = next(self.local_attr_ancestors(name, context), None)
if class_node:
result = class_node.locals[name]
result = [n for n in result if not isinstance(n, node_classes.DelAttr)]
if result:
return result
raise exceptions.AttributeInferenceError(
target=self, attribute=name, context=context
) | python | def local_attr(self, name, context=None):
result = []
if name in self.locals:
result = self.locals[name]
else:
class_node = next(self.local_attr_ancestors(name, context), None)
if class_node:
result = class_node.locals[name]
result = [n for n in result if not isinstance(n, node_classes.DelAttr)]
if result:
return result
raise exceptions.AttributeInferenceError(
target=self, attribute=name, context=context
) | [
"def",
"local_attr",
"(",
"self",
",",
"name",
",",
"context",
"=",
"None",
")",
":",
"result",
"=",
"[",
"]",
"if",
"name",
"in",
"self",
".",
"locals",
":",
"result",
"=",
"self",
".",
"locals",
"[",
"name",
"]",
"else",
":",
"class_node",
"=",
... | Get the list of assign nodes associated to the given name.
Assignments are looked for in both this class and in parents.
:returns: The list of assignments to the given name.
:rtype: list(NodeNG)
:raises AttributeInferenceError: If no attribute with this name
can be found in this class or parent classes. | [
"Get",
"the",
"list",
"of",
"assign",
"nodes",
"associated",
"to",
"the",
"given",
"name",
"."
] | e0a298df55b15abcb77c2a93253f5ab7be52d0fb | https://github.com/PyCQA/astroid/blob/e0a298df55b15abcb77c2a93253f5ab7be52d0fb/astroid/scoped_nodes.py#L2265-L2288 |
227,308 | PyCQA/astroid | astroid/scoped_nodes.py | ClassDef.instance_attr | def instance_attr(self, name, context=None):
"""Get the list of nodes associated to the given attribute name.
Assignments are looked for in both this class and in parents.
:returns: The list of assignments to the given name.
:rtype: list(NodeNG)
:raises AttributeInferenceError: If no attribute with this name
can be found in this class or parent classes.
"""
# Return a copy, so we don't modify self.instance_attrs,
# which could lead to infinite loop.
values = list(self.instance_attrs.get(name, []))
# get all values from parents
for class_node in self.instance_attr_ancestors(name, context):
values += class_node.instance_attrs[name]
values = [n for n in values if not isinstance(n, node_classes.DelAttr)]
if values:
return values
raise exceptions.AttributeInferenceError(
target=self, attribute=name, context=context
) | python | def instance_attr(self, name, context=None):
# Return a copy, so we don't modify self.instance_attrs,
# which could lead to infinite loop.
values = list(self.instance_attrs.get(name, []))
# get all values from parents
for class_node in self.instance_attr_ancestors(name, context):
values += class_node.instance_attrs[name]
values = [n for n in values if not isinstance(n, node_classes.DelAttr)]
if values:
return values
raise exceptions.AttributeInferenceError(
target=self, attribute=name, context=context
) | [
"def",
"instance_attr",
"(",
"self",
",",
"name",
",",
"context",
"=",
"None",
")",
":",
"# Return a copy, so we don't modify self.instance_attrs,",
"# which could lead to infinite loop.",
"values",
"=",
"list",
"(",
"self",
".",
"instance_attrs",
".",
"get",
"(",
"na... | Get the list of nodes associated to the given attribute name.
Assignments are looked for in both this class and in parents.
:returns: The list of assignments to the given name.
:rtype: list(NodeNG)
:raises AttributeInferenceError: If no attribute with this name
can be found in this class or parent classes. | [
"Get",
"the",
"list",
"of",
"nodes",
"associated",
"to",
"the",
"given",
"attribute",
"name",
"."
] | e0a298df55b15abcb77c2a93253f5ab7be52d0fb | https://github.com/PyCQA/astroid/blob/e0a298df55b15abcb77c2a93253f5ab7be52d0fb/astroid/scoped_nodes.py#L2290-L2312 |
227,309 | PyCQA/astroid | astroid/scoped_nodes.py | ClassDef.getattr | def getattr(self, name, context=None, class_context=True):
"""Get an attribute from this class, using Python's attribute semantic.
This method doesn't look in the :attr:`instance_attrs` dictionary
since it is done by an :class:`Instance` proxy at inference time.
It may return an :class:`Uninferable` object if
the attribute has not been
found, but a ``__getattr__`` or ``__getattribute__`` method is defined.
If ``class_context`` is given, then it is considered that the
attribute is accessed from a class context,
e.g. ClassDef.attribute, otherwise it might have been accessed
from an instance as well. If ``class_context`` is used in that
case, then a lookup in the implicit metaclass and the explicit
metaclass will be done.
:param name: The attribute to look for.
:type name: str
:param class_context: Whether the attribute can be accessed statically.
:type class_context: bool
:returns: The attribute.
:rtype: list(NodeNG)
:raises AttributeInferenceError: If the attribute cannot be inferred.
"""
values = self.locals.get(name, [])
if name in self.special_attributes and class_context and not values:
result = [self.special_attributes.lookup(name)]
if name == "__bases__":
# Need special treatment, since they are mutable
# and we need to return all the values.
result += values
return result
# don't modify the list in self.locals!
values = list(values)
for classnode in self.ancestors(recurs=True, context=context):
values += classnode.locals.get(name, [])
if class_context:
values += self._metaclass_lookup_attribute(name, context)
if not values:
raise exceptions.AttributeInferenceError(
target=self, attribute=name, context=context
)
# Look for AnnAssigns, which are not attributes in the purest sense.
for value in values:
if isinstance(value, node_classes.AssignName):
stmt = value.statement()
if isinstance(stmt, node_classes.AnnAssign) and stmt.value is None:
raise exceptions.AttributeInferenceError(
target=self, attribute=name, context=context
)
return values | python | def getattr(self, name, context=None, class_context=True):
values = self.locals.get(name, [])
if name in self.special_attributes and class_context and not values:
result = [self.special_attributes.lookup(name)]
if name == "__bases__":
# Need special treatment, since they are mutable
# and we need to return all the values.
result += values
return result
# don't modify the list in self.locals!
values = list(values)
for classnode in self.ancestors(recurs=True, context=context):
values += classnode.locals.get(name, [])
if class_context:
values += self._metaclass_lookup_attribute(name, context)
if not values:
raise exceptions.AttributeInferenceError(
target=self, attribute=name, context=context
)
# Look for AnnAssigns, which are not attributes in the purest sense.
for value in values:
if isinstance(value, node_classes.AssignName):
stmt = value.statement()
if isinstance(stmt, node_classes.AnnAssign) and stmt.value is None:
raise exceptions.AttributeInferenceError(
target=self, attribute=name, context=context
)
return values | [
"def",
"getattr",
"(",
"self",
",",
"name",
",",
"context",
"=",
"None",
",",
"class_context",
"=",
"True",
")",
":",
"values",
"=",
"self",
".",
"locals",
".",
"get",
"(",
"name",
",",
"[",
"]",
")",
"if",
"name",
"in",
"self",
".",
"special_attri... | Get an attribute from this class, using Python's attribute semantic.
This method doesn't look in the :attr:`instance_attrs` dictionary
since it is done by an :class:`Instance` proxy at inference time.
It may return an :class:`Uninferable` object if
the attribute has not been
found, but a ``__getattr__`` or ``__getattribute__`` method is defined.
If ``class_context`` is given, then it is considered that the
attribute is accessed from a class context,
e.g. ClassDef.attribute, otherwise it might have been accessed
from an instance as well. If ``class_context`` is used in that
case, then a lookup in the implicit metaclass and the explicit
metaclass will be done.
:param name: The attribute to look for.
:type name: str
:param class_context: Whether the attribute can be accessed statically.
:type class_context: bool
:returns: The attribute.
:rtype: list(NodeNG)
:raises AttributeInferenceError: If the attribute cannot be inferred. | [
"Get",
"an",
"attribute",
"from",
"this",
"class",
"using",
"Python",
"s",
"attribute",
"semantic",
"."
] | e0a298df55b15abcb77c2a93253f5ab7be52d0fb | https://github.com/PyCQA/astroid/blob/e0a298df55b15abcb77c2a93253f5ab7be52d0fb/astroid/scoped_nodes.py#L2323-L2379 |
227,310 | PyCQA/astroid | astroid/scoped_nodes.py | ClassDef._metaclass_lookup_attribute | def _metaclass_lookup_attribute(self, name, context):
"""Search the given name in the implicit and the explicit metaclass."""
attrs = set()
implicit_meta = self.implicit_metaclass()
metaclass = self.metaclass()
for cls in {implicit_meta, metaclass}:
if cls and cls != self and isinstance(cls, ClassDef):
cls_attributes = self._get_attribute_from_metaclass(cls, name, context)
attrs.update(set(cls_attributes))
return attrs | python | def _metaclass_lookup_attribute(self, name, context):
attrs = set()
implicit_meta = self.implicit_metaclass()
metaclass = self.metaclass()
for cls in {implicit_meta, metaclass}:
if cls and cls != self and isinstance(cls, ClassDef):
cls_attributes = self._get_attribute_from_metaclass(cls, name, context)
attrs.update(set(cls_attributes))
return attrs | [
"def",
"_metaclass_lookup_attribute",
"(",
"self",
",",
"name",
",",
"context",
")",
":",
"attrs",
"=",
"set",
"(",
")",
"implicit_meta",
"=",
"self",
".",
"implicit_metaclass",
"(",
")",
"metaclass",
"=",
"self",
".",
"metaclass",
"(",
")",
"for",
"cls",
... | Search the given name in the implicit and the explicit metaclass. | [
"Search",
"the",
"given",
"name",
"in",
"the",
"implicit",
"and",
"the",
"explicit",
"metaclass",
"."
] | e0a298df55b15abcb77c2a93253f5ab7be52d0fb | https://github.com/PyCQA/astroid/blob/e0a298df55b15abcb77c2a93253f5ab7be52d0fb/astroid/scoped_nodes.py#L2381-L2390 |
227,311 | PyCQA/astroid | astroid/scoped_nodes.py | ClassDef.igetattr | def igetattr(self, name, context=None, class_context=True):
"""Infer the possible values of the given variable.
:param name: The name of the variable to infer.
:type name: str
:returns: The inferred possible values.
:rtype: iterable(NodeNG or Uninferable)
"""
# set lookup name since this is necessary to infer on import nodes for
# instance
context = contextmod.copy_context(context)
context.lookupname = name
try:
attr = self.getattr(name, context, class_context=class_context)[0]
for inferred in bases._infer_stmts([attr], context, frame=self):
# yield Uninferable object instead of descriptors when necessary
if not isinstance(inferred, node_classes.Const) and isinstance(
inferred, bases.Instance
):
try:
inferred._proxied.getattr("__get__", context)
except exceptions.AttributeInferenceError:
yield inferred
else:
yield util.Uninferable
else:
yield function_to_method(inferred, self)
except exceptions.AttributeInferenceError as error:
if not name.startswith("__") and self.has_dynamic_getattr(context):
# class handle some dynamic attributes, return a Uninferable object
yield util.Uninferable
else:
raise exceptions.InferenceError(
error.message, target=self, attribute=name, context=context
) | python | def igetattr(self, name, context=None, class_context=True):
# set lookup name since this is necessary to infer on import nodes for
# instance
context = contextmod.copy_context(context)
context.lookupname = name
try:
attr = self.getattr(name, context, class_context=class_context)[0]
for inferred in bases._infer_stmts([attr], context, frame=self):
# yield Uninferable object instead of descriptors when necessary
if not isinstance(inferred, node_classes.Const) and isinstance(
inferred, bases.Instance
):
try:
inferred._proxied.getattr("__get__", context)
except exceptions.AttributeInferenceError:
yield inferred
else:
yield util.Uninferable
else:
yield function_to_method(inferred, self)
except exceptions.AttributeInferenceError as error:
if not name.startswith("__") and self.has_dynamic_getattr(context):
# class handle some dynamic attributes, return a Uninferable object
yield util.Uninferable
else:
raise exceptions.InferenceError(
error.message, target=self, attribute=name, context=context
) | [
"def",
"igetattr",
"(",
"self",
",",
"name",
",",
"context",
"=",
"None",
",",
"class_context",
"=",
"True",
")",
":",
"# set lookup name since this is necessary to infer on import nodes for",
"# instance",
"context",
"=",
"contextmod",
".",
"copy_context",
"(",
"cont... | Infer the possible values of the given variable.
:param name: The name of the variable to infer.
:type name: str
:returns: The inferred possible values.
:rtype: iterable(NodeNG or Uninferable) | [
"Infer",
"the",
"possible",
"values",
"of",
"the",
"given",
"variable",
"."
] | e0a298df55b15abcb77c2a93253f5ab7be52d0fb | https://github.com/PyCQA/astroid/blob/e0a298df55b15abcb77c2a93253f5ab7be52d0fb/astroid/scoped_nodes.py#L2419-L2454 |
227,312 | PyCQA/astroid | astroid/scoped_nodes.py | ClassDef.getitem | def getitem(self, index, context=None):
"""Return the inference of a subscript.
This is basically looking up the method in the metaclass and calling it.
:returns: The inferred value of a subscript to this class.
:rtype: NodeNG
:raises AstroidTypeError: If this class does not define a
``__getitem__`` method.
"""
try:
methods = dunder_lookup.lookup(self, "__getitem__")
except exceptions.AttributeInferenceError as exc:
raise exceptions.AstroidTypeError(node=self, context=context) from exc
method = methods[0]
# Create a new callcontext for providing index as an argument.
new_context = contextmod.bind_context_to_node(context, self)
new_context.callcontext = contextmod.CallContext(args=[index])
try:
return next(method.infer_call_result(self, new_context))
except exceptions.InferenceError:
return util.Uninferable | python | def getitem(self, index, context=None):
try:
methods = dunder_lookup.lookup(self, "__getitem__")
except exceptions.AttributeInferenceError as exc:
raise exceptions.AstroidTypeError(node=self, context=context) from exc
method = methods[0]
# Create a new callcontext for providing index as an argument.
new_context = contextmod.bind_context_to_node(context, self)
new_context.callcontext = contextmod.CallContext(args=[index])
try:
return next(method.infer_call_result(self, new_context))
except exceptions.InferenceError:
return util.Uninferable | [
"def",
"getitem",
"(",
"self",
",",
"index",
",",
"context",
"=",
"None",
")",
":",
"try",
":",
"methods",
"=",
"dunder_lookup",
".",
"lookup",
"(",
"self",
",",
"\"__getitem__\"",
")",
"except",
"exceptions",
".",
"AttributeInferenceError",
"as",
"exc",
"... | Return the inference of a subscript.
This is basically looking up the method in the metaclass and calling it.
:returns: The inferred value of a subscript to this class.
:rtype: NodeNG
:raises AstroidTypeError: If this class does not define a
``__getitem__`` method. | [
"Return",
"the",
"inference",
"of",
"a",
"subscript",
"."
] | e0a298df55b15abcb77c2a93253f5ab7be52d0fb | https://github.com/PyCQA/astroid/blob/e0a298df55b15abcb77c2a93253f5ab7be52d0fb/astroid/scoped_nodes.py#L2483-L2508 |
227,313 | PyCQA/astroid | astroid/scoped_nodes.py | ClassDef.methods | def methods(self):
"""Iterate over all of the method defined in this class and its parents.
:returns: The methods defined on the class.
:rtype: iterable(FunctionDef)
"""
done = {}
for astroid in itertools.chain(iter((self,)), self.ancestors()):
for meth in astroid.mymethods():
if meth.name in done:
continue
done[meth.name] = None
yield meth | python | def methods(self):
done = {}
for astroid in itertools.chain(iter((self,)), self.ancestors()):
for meth in astroid.mymethods():
if meth.name in done:
continue
done[meth.name] = None
yield meth | [
"def",
"methods",
"(",
"self",
")",
":",
"done",
"=",
"{",
"}",
"for",
"astroid",
"in",
"itertools",
".",
"chain",
"(",
"iter",
"(",
"(",
"self",
",",
")",
")",
",",
"self",
".",
"ancestors",
"(",
")",
")",
":",
"for",
"meth",
"in",
"astroid",
... | Iterate over all of the method defined in this class and its parents.
:returns: The methods defined on the class.
:rtype: iterable(FunctionDef) | [
"Iterate",
"over",
"all",
"of",
"the",
"method",
"defined",
"in",
"this",
"class",
"and",
"its",
"parents",
"."
] | e0a298df55b15abcb77c2a93253f5ab7be52d0fb | https://github.com/PyCQA/astroid/blob/e0a298df55b15abcb77c2a93253f5ab7be52d0fb/astroid/scoped_nodes.py#L2510-L2522 |
227,314 | PyCQA/astroid | astroid/scoped_nodes.py | ClassDef.declared_metaclass | def declared_metaclass(self, context=None):
"""Return the explicit declared metaclass for the current class.
An explicit declared metaclass is defined
either by passing the ``metaclass`` keyword argument
in the class definition line (Python 3) or (Python 2) by
having a ``__metaclass__`` class attribute, or if there are
no explicit bases but there is a global ``__metaclass__`` variable.
:returns: The metaclass of this class,
or None if one could not be found.
:rtype: NodeNG or None
"""
for base in self.bases:
try:
for baseobj in base.infer(context=context):
if isinstance(baseobj, ClassDef) and baseobj.hide:
self._metaclass = baseobj._metaclass
self._metaclass_hack = True
break
except exceptions.InferenceError:
pass
if self._metaclass:
# Expects this from Py3k TreeRebuilder
try:
return next(
node
for node in self._metaclass.infer(context=context)
if node is not util.Uninferable
)
except (exceptions.InferenceError, StopIteration):
return None
return None | python | def declared_metaclass(self, context=None):
for base in self.bases:
try:
for baseobj in base.infer(context=context):
if isinstance(baseobj, ClassDef) and baseobj.hide:
self._metaclass = baseobj._metaclass
self._metaclass_hack = True
break
except exceptions.InferenceError:
pass
if self._metaclass:
# Expects this from Py3k TreeRebuilder
try:
return next(
node
for node in self._metaclass.infer(context=context)
if node is not util.Uninferable
)
except (exceptions.InferenceError, StopIteration):
return None
return None | [
"def",
"declared_metaclass",
"(",
"self",
",",
"context",
"=",
"None",
")",
":",
"for",
"base",
"in",
"self",
".",
"bases",
":",
"try",
":",
"for",
"baseobj",
"in",
"base",
".",
"infer",
"(",
"context",
"=",
"context",
")",
":",
"if",
"isinstance",
"... | Return the explicit declared metaclass for the current class.
An explicit declared metaclass is defined
either by passing the ``metaclass`` keyword argument
in the class definition line (Python 3) or (Python 2) by
having a ``__metaclass__`` class attribute, or if there are
no explicit bases but there is a global ``__metaclass__`` variable.
:returns: The metaclass of this class,
or None if one could not be found.
:rtype: NodeNG or None | [
"Return",
"the",
"explicit",
"declared",
"metaclass",
"for",
"the",
"current",
"class",
"."
] | e0a298df55b15abcb77c2a93253f5ab7be52d0fb | https://github.com/PyCQA/astroid/blob/e0a298df55b15abcb77c2a93253f5ab7be52d0fb/astroid/scoped_nodes.py#L2550-L2584 |
227,315 | PyCQA/astroid | astroid/scoped_nodes.py | ClassDef._islots | def _islots(self):
""" Return an iterator with the inferred slots. """
if "__slots__" not in self.locals:
return None
for slots in self.igetattr("__slots__"):
# check if __slots__ is a valid type
for meth in ITER_METHODS:
try:
slots.getattr(meth)
break
except exceptions.AttributeInferenceError:
continue
else:
continue
if isinstance(slots, node_classes.Const):
# a string. Ignore the following checks,
# but yield the node, only if it has a value
if slots.value:
yield slots
continue
if not hasattr(slots, "itered"):
# we can't obtain the values, maybe a .deque?
continue
if isinstance(slots, node_classes.Dict):
values = [item[0] for item in slots.items]
else:
values = slots.itered()
if values is util.Uninferable:
continue
if not values:
# Stop the iteration, because the class
# has an empty list of slots.
return values
for elt in values:
try:
for inferred in elt.infer():
if inferred is util.Uninferable:
continue
if not isinstance(
inferred, node_classes.Const
) or not isinstance(inferred.value, str):
continue
if not inferred.value:
continue
yield inferred
except exceptions.InferenceError:
continue
return None | python | def _islots(self):
if "__slots__" not in self.locals:
return None
for slots in self.igetattr("__slots__"):
# check if __slots__ is a valid type
for meth in ITER_METHODS:
try:
slots.getattr(meth)
break
except exceptions.AttributeInferenceError:
continue
else:
continue
if isinstance(slots, node_classes.Const):
# a string. Ignore the following checks,
# but yield the node, only if it has a value
if slots.value:
yield slots
continue
if not hasattr(slots, "itered"):
# we can't obtain the values, maybe a .deque?
continue
if isinstance(slots, node_classes.Dict):
values = [item[0] for item in slots.items]
else:
values = slots.itered()
if values is util.Uninferable:
continue
if not values:
# Stop the iteration, because the class
# has an empty list of slots.
return values
for elt in values:
try:
for inferred in elt.infer():
if inferred is util.Uninferable:
continue
if not isinstance(
inferred, node_classes.Const
) or not isinstance(inferred.value, str):
continue
if not inferred.value:
continue
yield inferred
except exceptions.InferenceError:
continue
return None | [
"def",
"_islots",
"(",
"self",
")",
":",
"if",
"\"__slots__\"",
"not",
"in",
"self",
".",
"locals",
":",
"return",
"None",
"for",
"slots",
"in",
"self",
".",
"igetattr",
"(",
"\"__slots__\"",
")",
":",
"# check if __slots__ is a valid type",
"for",
"meth",
"... | Return an iterator with the inferred slots. | [
"Return",
"an",
"iterator",
"with",
"the",
"inferred",
"slots",
"."
] | e0a298df55b15abcb77c2a93253f5ab7be52d0fb | https://github.com/PyCQA/astroid/blob/e0a298df55b15abcb77c2a93253f5ab7be52d0fb/astroid/scoped_nodes.py#L2615-L2666 |
227,316 | PyCQA/astroid | astroid/scoped_nodes.py | ClassDef.slots | def slots(self):
"""Get all the slots for this node.
:returns: The names of slots for this class.
If the class doesn't define any slot, through the ``__slots__``
variable, then this function will return a None.
Also, it will return None in the case the slots were not inferred.
:rtype: list(str) or None
"""
def grouped_slots():
# Not interested in object, since it can't have slots.
for cls in self.mro()[:-1]:
try:
cls_slots = cls._slots()
except NotImplementedError:
continue
if cls_slots is not None:
yield from cls_slots
else:
yield None
if not self.newstyle:
raise NotImplementedError(
"The concept of slots is undefined for old-style classes."
)
slots = list(grouped_slots())
if not all(slot is not None for slot in slots):
return None
return sorted(slots, key=lambda item: item.value) | python | def slots(self):
def grouped_slots():
# Not interested in object, since it can't have slots.
for cls in self.mro()[:-1]:
try:
cls_slots = cls._slots()
except NotImplementedError:
continue
if cls_slots is not None:
yield from cls_slots
else:
yield None
if not self.newstyle:
raise NotImplementedError(
"The concept of slots is undefined for old-style classes."
)
slots = list(grouped_slots())
if not all(slot is not None for slot in slots):
return None
return sorted(slots, key=lambda item: item.value) | [
"def",
"slots",
"(",
"self",
")",
":",
"def",
"grouped_slots",
"(",
")",
":",
"# Not interested in object, since it can't have slots.",
"for",
"cls",
"in",
"self",
".",
"mro",
"(",
")",
"[",
":",
"-",
"1",
"]",
":",
"try",
":",
"cls_slots",
"=",
"cls",
"... | Get all the slots for this node.
:returns: The names of slots for this class.
If the class doesn't define any slot, through the ``__slots__``
variable, then this function will return a None.
Also, it will return None in the case the slots were not inferred.
:rtype: list(str) or None | [
"Get",
"all",
"the",
"slots",
"for",
"this",
"node",
"."
] | e0a298df55b15abcb77c2a93253f5ab7be52d0fb | https://github.com/PyCQA/astroid/blob/e0a298df55b15abcb77c2a93253f5ab7be52d0fb/astroid/scoped_nodes.py#L2686-L2717 |
227,317 | PyCQA/astroid | astroid/brain/brain_builtin_inference.py | infer_dict | def infer_dict(node, context=None):
"""Try to infer a dict call to a Dict node.
The function treats the following cases:
* dict()
* dict(mapping)
* dict(iterable)
* dict(iterable, **kwargs)
* dict(mapping, **kwargs)
* dict(**kwargs)
If a case can't be inferred, we'll fallback to default inference.
"""
call = arguments.CallSite.from_call(node)
if call.has_invalid_arguments() or call.has_invalid_keywords():
raise UseInferenceDefault
args = call.positional_arguments
kwargs = list(call.keyword_arguments.items())
if not args and not kwargs:
# dict()
return nodes.Dict()
elif kwargs and not args:
# dict(a=1, b=2, c=4)
items = [(nodes.Const(key), value) for key, value in kwargs]
elif len(args) == 1 and kwargs:
# dict(some_iterable, b=2, c=4)
elts = _get_elts(args[0], context)
keys = [(nodes.Const(key), value) for key, value in kwargs]
items = elts + keys
elif len(args) == 1:
items = _get_elts(args[0], context)
else:
raise UseInferenceDefault()
value = nodes.Dict(
col_offset=node.col_offset, lineno=node.lineno, parent=node.parent
)
value.postinit(items)
return value | python | def infer_dict(node, context=None):
call = arguments.CallSite.from_call(node)
if call.has_invalid_arguments() or call.has_invalid_keywords():
raise UseInferenceDefault
args = call.positional_arguments
kwargs = list(call.keyword_arguments.items())
if not args and not kwargs:
# dict()
return nodes.Dict()
elif kwargs and not args:
# dict(a=1, b=2, c=4)
items = [(nodes.Const(key), value) for key, value in kwargs]
elif len(args) == 1 and kwargs:
# dict(some_iterable, b=2, c=4)
elts = _get_elts(args[0], context)
keys = [(nodes.Const(key), value) for key, value in kwargs]
items = elts + keys
elif len(args) == 1:
items = _get_elts(args[0], context)
else:
raise UseInferenceDefault()
value = nodes.Dict(
col_offset=node.col_offset, lineno=node.lineno, parent=node.parent
)
value.postinit(items)
return value | [
"def",
"infer_dict",
"(",
"node",
",",
"context",
"=",
"None",
")",
":",
"call",
"=",
"arguments",
".",
"CallSite",
".",
"from_call",
"(",
"node",
")",
"if",
"call",
".",
"has_invalid_arguments",
"(",
")",
"or",
"call",
".",
"has_invalid_keywords",
"(",
... | Try to infer a dict call to a Dict node.
The function treats the following cases:
* dict()
* dict(mapping)
* dict(iterable)
* dict(iterable, **kwargs)
* dict(mapping, **kwargs)
* dict(**kwargs)
If a case can't be inferred, we'll fallback to default inference. | [
"Try",
"to",
"infer",
"a",
"dict",
"call",
"to",
"a",
"Dict",
"node",
"."
] | e0a298df55b15abcb77c2a93253f5ab7be52d0fb | https://github.com/PyCQA/astroid/blob/e0a298df55b15abcb77c2a93253f5ab7be52d0fb/astroid/brain/brain_builtin_inference.py#L279-L320 |
227,318 | PyCQA/astroid | astroid/brain/brain_builtin_inference.py | infer_super | def infer_super(node, context=None):
"""Understand super calls.
There are some restrictions for what can be understood:
* unbounded super (one argument form) is not understood.
* if the super call is not inside a function (classmethod or method),
then the default inference will be used.
* if the super arguments can't be inferred, the default inference
will be used.
"""
if len(node.args) == 1:
# Ignore unbounded super.
raise UseInferenceDefault
scope = node.scope()
if not isinstance(scope, nodes.FunctionDef):
# Ignore non-method uses of super.
raise UseInferenceDefault
if scope.type not in ("classmethod", "method"):
# Not interested in staticmethods.
raise UseInferenceDefault
cls = scoped_nodes.get_wrapping_class(scope)
if not len(node.args):
mro_pointer = cls
# In we are in a classmethod, the interpreter will fill
# automatically the class as the second argument, not an instance.
if scope.type == "classmethod":
mro_type = cls
else:
mro_type = cls.instantiate_class()
else:
try:
mro_pointer = next(node.args[0].infer(context=context))
except InferenceError:
raise UseInferenceDefault
try:
mro_type = next(node.args[1].infer(context=context))
except InferenceError:
raise UseInferenceDefault
if mro_pointer is util.Uninferable or mro_type is util.Uninferable:
# No way we could understand this.
raise UseInferenceDefault
super_obj = objects.Super(
mro_pointer=mro_pointer, mro_type=mro_type, self_class=cls, scope=scope
)
super_obj.parent = node
return super_obj | python | def infer_super(node, context=None):
if len(node.args) == 1:
# Ignore unbounded super.
raise UseInferenceDefault
scope = node.scope()
if not isinstance(scope, nodes.FunctionDef):
# Ignore non-method uses of super.
raise UseInferenceDefault
if scope.type not in ("classmethod", "method"):
# Not interested in staticmethods.
raise UseInferenceDefault
cls = scoped_nodes.get_wrapping_class(scope)
if not len(node.args):
mro_pointer = cls
# In we are in a classmethod, the interpreter will fill
# automatically the class as the second argument, not an instance.
if scope.type == "classmethod":
mro_type = cls
else:
mro_type = cls.instantiate_class()
else:
try:
mro_pointer = next(node.args[0].infer(context=context))
except InferenceError:
raise UseInferenceDefault
try:
mro_type = next(node.args[1].infer(context=context))
except InferenceError:
raise UseInferenceDefault
if mro_pointer is util.Uninferable or mro_type is util.Uninferable:
# No way we could understand this.
raise UseInferenceDefault
super_obj = objects.Super(
mro_pointer=mro_pointer, mro_type=mro_type, self_class=cls, scope=scope
)
super_obj.parent = node
return super_obj | [
"def",
"infer_super",
"(",
"node",
",",
"context",
"=",
"None",
")",
":",
"if",
"len",
"(",
"node",
".",
"args",
")",
"==",
"1",
":",
"# Ignore unbounded super.",
"raise",
"UseInferenceDefault",
"scope",
"=",
"node",
".",
"scope",
"(",
")",
"if",
"not",
... | Understand super calls.
There are some restrictions for what can be understood:
* unbounded super (one argument form) is not understood.
* if the super call is not inside a function (classmethod or method),
then the default inference will be used.
* if the super arguments can't be inferred, the default inference
will be used. | [
"Understand",
"super",
"calls",
"."
] | e0a298df55b15abcb77c2a93253f5ab7be52d0fb | https://github.com/PyCQA/astroid/blob/e0a298df55b15abcb77c2a93253f5ab7be52d0fb/astroid/brain/brain_builtin_inference.py#L323-L375 |
227,319 | PyCQA/astroid | astroid/brain/brain_builtin_inference.py | infer_getattr | def infer_getattr(node, context=None):
"""Understand getattr calls
If one of the arguments is an Uninferable object, then the
result will be an Uninferable object. Otherwise, the normal attribute
lookup will be done.
"""
obj, attr = _infer_getattr_args(node, context)
if (
obj is util.Uninferable
or attr is util.Uninferable
or not hasattr(obj, "igetattr")
):
return util.Uninferable
try:
return next(obj.igetattr(attr, context=context))
except (StopIteration, InferenceError, AttributeInferenceError):
if len(node.args) == 3:
# Try to infer the default and return it instead.
try:
return next(node.args[2].infer(context=context))
except InferenceError:
raise UseInferenceDefault
raise UseInferenceDefault | python | def infer_getattr(node, context=None):
obj, attr = _infer_getattr_args(node, context)
if (
obj is util.Uninferable
or attr is util.Uninferable
or not hasattr(obj, "igetattr")
):
return util.Uninferable
try:
return next(obj.igetattr(attr, context=context))
except (StopIteration, InferenceError, AttributeInferenceError):
if len(node.args) == 3:
# Try to infer the default and return it instead.
try:
return next(node.args[2].infer(context=context))
except InferenceError:
raise UseInferenceDefault
raise UseInferenceDefault | [
"def",
"infer_getattr",
"(",
"node",
",",
"context",
"=",
"None",
")",
":",
"obj",
",",
"attr",
"=",
"_infer_getattr_args",
"(",
"node",
",",
"context",
")",
"if",
"(",
"obj",
"is",
"util",
".",
"Uninferable",
"or",
"attr",
"is",
"util",
".",
"Uninfera... | Understand getattr calls
If one of the arguments is an Uninferable object, then the
result will be an Uninferable object. Otherwise, the normal attribute
lookup will be done. | [
"Understand",
"getattr",
"calls"
] | e0a298df55b15abcb77c2a93253f5ab7be52d0fb | https://github.com/PyCQA/astroid/blob/e0a298df55b15abcb77c2a93253f5ab7be52d0fb/astroid/brain/brain_builtin_inference.py#L404-L429 |
227,320 | PyCQA/astroid | astroid/brain/brain_builtin_inference.py | infer_hasattr | def infer_hasattr(node, context=None):
"""Understand hasattr calls
This always guarantees three possible outcomes for calling
hasattr: Const(False) when we are sure that the object
doesn't have the intended attribute, Const(True) when
we know that the object has the attribute and Uninferable
when we are unsure of the outcome of the function call.
"""
try:
obj, attr = _infer_getattr_args(node, context)
if (
obj is util.Uninferable
or attr is util.Uninferable
or not hasattr(obj, "getattr")
):
return util.Uninferable
obj.getattr(attr, context=context)
except UseInferenceDefault:
# Can't infer something from this function call.
return util.Uninferable
except AttributeInferenceError:
# Doesn't have it.
return nodes.Const(False)
return nodes.Const(True) | python | def infer_hasattr(node, context=None):
try:
obj, attr = _infer_getattr_args(node, context)
if (
obj is util.Uninferable
or attr is util.Uninferable
or not hasattr(obj, "getattr")
):
return util.Uninferable
obj.getattr(attr, context=context)
except UseInferenceDefault:
# Can't infer something from this function call.
return util.Uninferable
except AttributeInferenceError:
# Doesn't have it.
return nodes.Const(False)
return nodes.Const(True) | [
"def",
"infer_hasattr",
"(",
"node",
",",
"context",
"=",
"None",
")",
":",
"try",
":",
"obj",
",",
"attr",
"=",
"_infer_getattr_args",
"(",
"node",
",",
"context",
")",
"if",
"(",
"obj",
"is",
"util",
".",
"Uninferable",
"or",
"attr",
"is",
"util",
... | Understand hasattr calls
This always guarantees three possible outcomes for calling
hasattr: Const(False) when we are sure that the object
doesn't have the intended attribute, Const(True) when
we know that the object has the attribute and Uninferable
when we are unsure of the outcome of the function call. | [
"Understand",
"hasattr",
"calls"
] | e0a298df55b15abcb77c2a93253f5ab7be52d0fb | https://github.com/PyCQA/astroid/blob/e0a298df55b15abcb77c2a93253f5ab7be52d0fb/astroid/brain/brain_builtin_inference.py#L432-L456 |
227,321 | PyCQA/astroid | astroid/brain/brain_builtin_inference.py | infer_callable | def infer_callable(node, context=None):
"""Understand callable calls
This follows Python's semantics, where an object
is callable if it provides an attribute __call__,
even though that attribute is something which can't be
called.
"""
if len(node.args) != 1:
# Invalid callable call.
raise UseInferenceDefault
argument = node.args[0]
try:
inferred = next(argument.infer(context=context))
except InferenceError:
return util.Uninferable
if inferred is util.Uninferable:
return util.Uninferable
return nodes.Const(inferred.callable()) | python | def infer_callable(node, context=None):
if len(node.args) != 1:
# Invalid callable call.
raise UseInferenceDefault
argument = node.args[0]
try:
inferred = next(argument.infer(context=context))
except InferenceError:
return util.Uninferable
if inferred is util.Uninferable:
return util.Uninferable
return nodes.Const(inferred.callable()) | [
"def",
"infer_callable",
"(",
"node",
",",
"context",
"=",
"None",
")",
":",
"if",
"len",
"(",
"node",
".",
"args",
")",
"!=",
"1",
":",
"# Invalid callable call.",
"raise",
"UseInferenceDefault",
"argument",
"=",
"node",
".",
"args",
"[",
"0",
"]",
"try... | Understand callable calls
This follows Python's semantics, where an object
is callable if it provides an attribute __call__,
even though that attribute is something which can't be
called. | [
"Understand",
"callable",
"calls"
] | e0a298df55b15abcb77c2a93253f5ab7be52d0fb | https://github.com/PyCQA/astroid/blob/e0a298df55b15abcb77c2a93253f5ab7be52d0fb/astroid/brain/brain_builtin_inference.py#L459-L478 |
227,322 | PyCQA/astroid | astroid/brain/brain_builtin_inference.py | infer_bool | def infer_bool(node, context=None):
"""Understand bool calls."""
if len(node.args) > 1:
# Invalid bool call.
raise UseInferenceDefault
if not node.args:
return nodes.Const(False)
argument = node.args[0]
try:
inferred = next(argument.infer(context=context))
except InferenceError:
return util.Uninferable
if inferred is util.Uninferable:
return util.Uninferable
bool_value = inferred.bool_value()
if bool_value is util.Uninferable:
return util.Uninferable
return nodes.Const(bool_value) | python | def infer_bool(node, context=None):
if len(node.args) > 1:
# Invalid bool call.
raise UseInferenceDefault
if not node.args:
return nodes.Const(False)
argument = node.args[0]
try:
inferred = next(argument.infer(context=context))
except InferenceError:
return util.Uninferable
if inferred is util.Uninferable:
return util.Uninferable
bool_value = inferred.bool_value()
if bool_value is util.Uninferable:
return util.Uninferable
return nodes.Const(bool_value) | [
"def",
"infer_bool",
"(",
"node",
",",
"context",
"=",
"None",
")",
":",
"if",
"len",
"(",
"node",
".",
"args",
")",
">",
"1",
":",
"# Invalid bool call.",
"raise",
"UseInferenceDefault",
"if",
"not",
"node",
".",
"args",
":",
"return",
"nodes",
".",
"... | Understand bool calls. | [
"Understand",
"bool",
"calls",
"."
] | e0a298df55b15abcb77c2a93253f5ab7be52d0fb | https://github.com/PyCQA/astroid/blob/e0a298df55b15abcb77c2a93253f5ab7be52d0fb/astroid/brain/brain_builtin_inference.py#L481-L501 |
227,323 | PyCQA/astroid | astroid/brain/brain_builtin_inference.py | infer_slice | def infer_slice(node, context=None):
"""Understand `slice` calls."""
args = node.args
if not 0 < len(args) <= 3:
raise UseInferenceDefault
infer_func = partial(helpers.safe_infer, context=context)
args = [infer_func(arg) for arg in args]
for arg in args:
if not arg or arg is util.Uninferable:
raise UseInferenceDefault
if not isinstance(arg, nodes.Const):
raise UseInferenceDefault
if not isinstance(arg.value, (type(None), int)):
raise UseInferenceDefault
if len(args) < 3:
# Make sure we have 3 arguments.
args.extend([None] * (3 - len(args)))
slice_node = nodes.Slice(
lineno=node.lineno, col_offset=node.col_offset, parent=node.parent
)
slice_node.postinit(*args)
return slice_node | python | def infer_slice(node, context=None):
args = node.args
if not 0 < len(args) <= 3:
raise UseInferenceDefault
infer_func = partial(helpers.safe_infer, context=context)
args = [infer_func(arg) for arg in args]
for arg in args:
if not arg or arg is util.Uninferable:
raise UseInferenceDefault
if not isinstance(arg, nodes.Const):
raise UseInferenceDefault
if not isinstance(arg.value, (type(None), int)):
raise UseInferenceDefault
if len(args) < 3:
# Make sure we have 3 arguments.
args.extend([None] * (3 - len(args)))
slice_node = nodes.Slice(
lineno=node.lineno, col_offset=node.col_offset, parent=node.parent
)
slice_node.postinit(*args)
return slice_node | [
"def",
"infer_slice",
"(",
"node",
",",
"context",
"=",
"None",
")",
":",
"args",
"=",
"node",
".",
"args",
"if",
"not",
"0",
"<",
"len",
"(",
"args",
")",
"<=",
"3",
":",
"raise",
"UseInferenceDefault",
"infer_func",
"=",
"partial",
"(",
"helpers",
... | Understand `slice` calls. | [
"Understand",
"slice",
"calls",
"."
] | e0a298df55b15abcb77c2a93253f5ab7be52d0fb | https://github.com/PyCQA/astroid/blob/e0a298df55b15abcb77c2a93253f5ab7be52d0fb/astroid/brain/brain_builtin_inference.py#L512-L536 |
227,324 | PyCQA/astroid | astroid/brain/brain_builtin_inference.py | infer_isinstance | def infer_isinstance(callnode, context=None):
"""Infer isinstance calls
:param nodes.Call callnode: an isinstance call
:param InferenceContext: context for call
(currently unused but is a common interface for inference)
:rtype nodes.Const: Boolean Const value of isinstance call
:raises UseInferenceDefault: If the node cannot be inferred
"""
call = arguments.CallSite.from_call(callnode)
if call.keyword_arguments:
# isinstance doesn't support keyword arguments
raise UseInferenceDefault("TypeError: isinstance() takes no keyword arguments")
if len(call.positional_arguments) != 2:
raise UseInferenceDefault(
"Expected two arguments, got {count}".format(
count=len(call.positional_arguments)
)
)
# The left hand argument is the obj to be checked
obj_node, class_or_tuple_node = call.positional_arguments
# The right hand argument is the class(es) that the given
# obj is to be check is an instance of
try:
class_container = _class_or_tuple_to_container(
class_or_tuple_node, context=context
)
except InferenceError:
raise UseInferenceDefault
try:
isinstance_bool = helpers.object_isinstance(obj_node, class_container, context)
except AstroidTypeError as exc:
raise UseInferenceDefault("TypeError: " + str(exc))
except MroError as exc:
raise UseInferenceDefault from exc
if isinstance_bool is util.Uninferable:
raise UseInferenceDefault
return nodes.Const(isinstance_bool) | python | def infer_isinstance(callnode, context=None):
call = arguments.CallSite.from_call(callnode)
if call.keyword_arguments:
# isinstance doesn't support keyword arguments
raise UseInferenceDefault("TypeError: isinstance() takes no keyword arguments")
if len(call.positional_arguments) != 2:
raise UseInferenceDefault(
"Expected two arguments, got {count}".format(
count=len(call.positional_arguments)
)
)
# The left hand argument is the obj to be checked
obj_node, class_or_tuple_node = call.positional_arguments
# The right hand argument is the class(es) that the given
# obj is to be check is an instance of
try:
class_container = _class_or_tuple_to_container(
class_or_tuple_node, context=context
)
except InferenceError:
raise UseInferenceDefault
try:
isinstance_bool = helpers.object_isinstance(obj_node, class_container, context)
except AstroidTypeError as exc:
raise UseInferenceDefault("TypeError: " + str(exc))
except MroError as exc:
raise UseInferenceDefault from exc
if isinstance_bool is util.Uninferable:
raise UseInferenceDefault
return nodes.Const(isinstance_bool) | [
"def",
"infer_isinstance",
"(",
"callnode",
",",
"context",
"=",
"None",
")",
":",
"call",
"=",
"arguments",
".",
"CallSite",
".",
"from_call",
"(",
"callnode",
")",
"if",
"call",
".",
"keyword_arguments",
":",
"# isinstance doesn't support keyword arguments",
"ra... | Infer isinstance calls
:param nodes.Call callnode: an isinstance call
:param InferenceContext: context for call
(currently unused but is a common interface for inference)
:rtype nodes.Const: Boolean Const value of isinstance call
:raises UseInferenceDefault: If the node cannot be inferred | [
"Infer",
"isinstance",
"calls"
] | e0a298df55b15abcb77c2a93253f5ab7be52d0fb | https://github.com/PyCQA/astroid/blob/e0a298df55b15abcb77c2a93253f5ab7be52d0fb/astroid/brain/brain_builtin_inference.py#L605-L643 |
227,325 | PyCQA/astroid | astroid/brain/brain_builtin_inference.py | infer_len | def infer_len(node, context=None):
"""Infer length calls
:param nodes.Call node: len call to infer
:param context.InferenceContext: node context
:rtype nodes.Const: a Const node with the inferred length, if possible
"""
call = arguments.CallSite.from_call(node)
if call.keyword_arguments:
raise UseInferenceDefault("TypeError: len() must take no keyword arguments")
if len(call.positional_arguments) != 1:
raise UseInferenceDefault(
"TypeError: len() must take exactly one argument "
"({len}) given".format(len=len(call.positional_arguments))
)
[argument_node] = call.positional_arguments
try:
return nodes.Const(helpers.object_len(argument_node, context=context))
except (AstroidTypeError, InferenceError) as exc:
raise UseInferenceDefault(str(exc)) from exc | python | def infer_len(node, context=None):
call = arguments.CallSite.from_call(node)
if call.keyword_arguments:
raise UseInferenceDefault("TypeError: len() must take no keyword arguments")
if len(call.positional_arguments) != 1:
raise UseInferenceDefault(
"TypeError: len() must take exactly one argument "
"({len}) given".format(len=len(call.positional_arguments))
)
[argument_node] = call.positional_arguments
try:
return nodes.Const(helpers.object_len(argument_node, context=context))
except (AstroidTypeError, InferenceError) as exc:
raise UseInferenceDefault(str(exc)) from exc | [
"def",
"infer_len",
"(",
"node",
",",
"context",
"=",
"None",
")",
":",
"call",
"=",
"arguments",
".",
"CallSite",
".",
"from_call",
"(",
"node",
")",
"if",
"call",
".",
"keyword_arguments",
":",
"raise",
"UseInferenceDefault",
"(",
"\"TypeError: len() must ta... | Infer length calls
:param nodes.Call node: len call to infer
:param context.InferenceContext: node context
:rtype nodes.Const: a Const node with the inferred length, if possible | [
"Infer",
"length",
"calls"
] | e0a298df55b15abcb77c2a93253f5ab7be52d0fb | https://github.com/PyCQA/astroid/blob/e0a298df55b15abcb77c2a93253f5ab7be52d0fb/astroid/brain/brain_builtin_inference.py#L665-L684 |
227,326 | PyCQA/astroid | astroid/brain/brain_builtin_inference.py | infer_dict_fromkeys | def infer_dict_fromkeys(node, context=None):
"""Infer dict.fromkeys
:param nodes.Call node: dict.fromkeys() call to infer
:param context.InferenceContext: node context
:rtype nodes.Dict:
a Dictionary containing the values that astroid was able to infer.
In case the inference failed for any reason, an empty dictionary
will be inferred instead.
"""
def _build_dict_with_elements(elements):
new_node = nodes.Dict(
col_offset=node.col_offset, lineno=node.lineno, parent=node.parent
)
new_node.postinit(elements)
return new_node
call = arguments.CallSite.from_call(node)
if call.keyword_arguments:
raise UseInferenceDefault("TypeError: int() must take no keyword arguments")
if len(call.positional_arguments) not in {1, 2}:
raise UseInferenceDefault(
"TypeError: Needs between 1 and 2 positional arguments"
)
default = nodes.Const(None)
values = call.positional_arguments[0]
try:
inferred_values = next(values.infer(context=context))
except InferenceError:
return _build_dict_with_elements([])
if inferred_values is util.Uninferable:
return _build_dict_with_elements([])
# Limit to a couple of potential values, as this can become pretty complicated
accepted_iterable_elements = (nodes.Const,)
if isinstance(inferred_values, (nodes.List, nodes.Set, nodes.Tuple)):
elements = inferred_values.elts
for element in elements:
if not isinstance(element, accepted_iterable_elements):
# Fallback to an empty dict
return _build_dict_with_elements([])
elements_with_value = [(element, default) for element in elements]
return _build_dict_with_elements(elements_with_value)
elif isinstance(inferred_values, nodes.Const) and isinstance(
inferred_values.value, (str, bytes)
):
elements = [
(nodes.Const(element), default) for element in inferred_values.value
]
return _build_dict_with_elements(elements)
elif isinstance(inferred_values, nodes.Dict):
keys = inferred_values.itered()
for key in keys:
if not isinstance(key, accepted_iterable_elements):
# Fallback to an empty dict
return _build_dict_with_elements([])
elements_with_value = [(element, default) for element in keys]
return _build_dict_with_elements(elements_with_value)
# Fallback to an empty dictionary
return _build_dict_with_elements([]) | python | def infer_dict_fromkeys(node, context=None):
def _build_dict_with_elements(elements):
new_node = nodes.Dict(
col_offset=node.col_offset, lineno=node.lineno, parent=node.parent
)
new_node.postinit(elements)
return new_node
call = arguments.CallSite.from_call(node)
if call.keyword_arguments:
raise UseInferenceDefault("TypeError: int() must take no keyword arguments")
if len(call.positional_arguments) not in {1, 2}:
raise UseInferenceDefault(
"TypeError: Needs between 1 and 2 positional arguments"
)
default = nodes.Const(None)
values = call.positional_arguments[0]
try:
inferred_values = next(values.infer(context=context))
except InferenceError:
return _build_dict_with_elements([])
if inferred_values is util.Uninferable:
return _build_dict_with_elements([])
# Limit to a couple of potential values, as this can become pretty complicated
accepted_iterable_elements = (nodes.Const,)
if isinstance(inferred_values, (nodes.List, nodes.Set, nodes.Tuple)):
elements = inferred_values.elts
for element in elements:
if not isinstance(element, accepted_iterable_elements):
# Fallback to an empty dict
return _build_dict_with_elements([])
elements_with_value = [(element, default) for element in elements]
return _build_dict_with_elements(elements_with_value)
elif isinstance(inferred_values, nodes.Const) and isinstance(
inferred_values.value, (str, bytes)
):
elements = [
(nodes.Const(element), default) for element in inferred_values.value
]
return _build_dict_with_elements(elements)
elif isinstance(inferred_values, nodes.Dict):
keys = inferred_values.itered()
for key in keys:
if not isinstance(key, accepted_iterable_elements):
# Fallback to an empty dict
return _build_dict_with_elements([])
elements_with_value = [(element, default) for element in keys]
return _build_dict_with_elements(elements_with_value)
# Fallback to an empty dictionary
return _build_dict_with_elements([]) | [
"def",
"infer_dict_fromkeys",
"(",
"node",
",",
"context",
"=",
"None",
")",
":",
"def",
"_build_dict_with_elements",
"(",
"elements",
")",
":",
"new_node",
"=",
"nodes",
".",
"Dict",
"(",
"col_offset",
"=",
"node",
".",
"col_offset",
",",
"lineno",
"=",
"... | Infer dict.fromkeys
:param nodes.Call node: dict.fromkeys() call to infer
:param context.InferenceContext: node context
:rtype nodes.Dict:
a Dictionary containing the values that astroid was able to infer.
In case the inference failed for any reason, an empty dictionary
will be inferred instead. | [
"Infer",
"dict",
".",
"fromkeys"
] | e0a298df55b15abcb77c2a93253f5ab7be52d0fb | https://github.com/PyCQA/astroid/blob/e0a298df55b15abcb77c2a93253f5ab7be52d0fb/astroid/brain/brain_builtin_inference.py#L735-L800 |
227,327 | PyCQA/astroid | astroid/as_string.py | AsStringVisitor._stmt_list | def _stmt_list(self, stmts, indent=True):
"""return a list of nodes to string"""
stmts = "\n".join(nstr for nstr in [n.accept(self) for n in stmts] if nstr)
if indent:
return self.indent + stmts.replace("\n", "\n" + self.indent)
return stmts | python | def _stmt_list(self, stmts, indent=True):
stmts = "\n".join(nstr for nstr in [n.accept(self) for n in stmts] if nstr)
if indent:
return self.indent + stmts.replace("\n", "\n" + self.indent)
return stmts | [
"def",
"_stmt_list",
"(",
"self",
",",
"stmts",
",",
"indent",
"=",
"True",
")",
":",
"stmts",
"=",
"\"\\n\"",
".",
"join",
"(",
"nstr",
"for",
"nstr",
"in",
"[",
"n",
".",
"accept",
"(",
"self",
")",
"for",
"n",
"in",
"stmts",
"]",
"if",
"nstr",... | return a list of nodes to string | [
"return",
"a",
"list",
"of",
"nodes",
"to",
"string"
] | e0a298df55b15abcb77c2a93253f5ab7be52d0fb | https://github.com/PyCQA/astroid/blob/e0a298df55b15abcb77c2a93253f5ab7be52d0fb/astroid/as_string.py#L46-L52 |
227,328 | PyCQA/astroid | astroid/as_string.py | AsStringVisitor._precedence_parens | def _precedence_parens(self, node, child, is_left=True):
"""Wrap child in parens only if required to keep same semantics"""
if self._should_wrap(node, child, is_left):
return "(%s)" % child.accept(self)
return child.accept(self) | python | def _precedence_parens(self, node, child, is_left=True):
if self._should_wrap(node, child, is_left):
return "(%s)" % child.accept(self)
return child.accept(self) | [
"def",
"_precedence_parens",
"(",
"self",
",",
"node",
",",
"child",
",",
"is_left",
"=",
"True",
")",
":",
"if",
"self",
".",
"_should_wrap",
"(",
"node",
",",
"child",
",",
"is_left",
")",
":",
"return",
"\"(%s)\"",
"%",
"child",
".",
"accept",
"(",
... | Wrap child in parens only if required to keep same semantics | [
"Wrap",
"child",
"in",
"parens",
"only",
"if",
"required",
"to",
"keep",
"same",
"semantics"
] | e0a298df55b15abcb77c2a93253f5ab7be52d0fb | https://github.com/PyCQA/astroid/blob/e0a298df55b15abcb77c2a93253f5ab7be52d0fb/astroid/as_string.py#L54-L59 |
227,329 | PyCQA/astroid | astroid/as_string.py | AsStringVisitor.visit_assert | def visit_assert(self, node):
"""return an astroid.Assert node as string"""
if node.fail:
return "assert %s, %s" % (node.test.accept(self), node.fail.accept(self))
return "assert %s" % node.test.accept(self) | python | def visit_assert(self, node):
if node.fail:
return "assert %s, %s" % (node.test.accept(self), node.fail.accept(self))
return "assert %s" % node.test.accept(self) | [
"def",
"visit_assert",
"(",
"self",
",",
"node",
")",
":",
"if",
"node",
".",
"fail",
":",
"return",
"\"assert %s, %s\"",
"%",
"(",
"node",
".",
"test",
".",
"accept",
"(",
"self",
")",
",",
"node",
".",
"fail",
".",
"accept",
"(",
"self",
")",
")"... | return an astroid.Assert node as string | [
"return",
"an",
"astroid",
".",
"Assert",
"node",
"as",
"string"
] | e0a298df55b15abcb77c2a93253f5ab7be52d0fb | https://github.com/PyCQA/astroid/blob/e0a298df55b15abcb77c2a93253f5ab7be52d0fb/astroid/as_string.py#L93-L97 |
227,330 | PyCQA/astroid | astroid/as_string.py | AsStringVisitor.visit_assign | def visit_assign(self, node):
"""return an astroid.Assign node as string"""
lhs = " = ".join(n.accept(self) for n in node.targets)
return "%s = %s" % (lhs, node.value.accept(self)) | python | def visit_assign(self, node):
lhs = " = ".join(n.accept(self) for n in node.targets)
return "%s = %s" % (lhs, node.value.accept(self)) | [
"def",
"visit_assign",
"(",
"self",
",",
"node",
")",
":",
"lhs",
"=",
"\" = \"",
".",
"join",
"(",
"n",
".",
"accept",
"(",
"self",
")",
"for",
"n",
"in",
"node",
".",
"targets",
")",
"return",
"\"%s = %s\"",
"%",
"(",
"lhs",
",",
"node",
".",
"... | return an astroid.Assign node as string | [
"return",
"an",
"astroid",
".",
"Assign",
"node",
"as",
"string"
] | e0a298df55b15abcb77c2a93253f5ab7be52d0fb | https://github.com/PyCQA/astroid/blob/e0a298df55b15abcb77c2a93253f5ab7be52d0fb/astroid/as_string.py#L103-L106 |
227,331 | PyCQA/astroid | astroid/as_string.py | AsStringVisitor.visit_augassign | def visit_augassign(self, node):
"""return an astroid.AugAssign node as string"""
return "%s %s %s" % (node.target.accept(self), node.op, node.value.accept(self)) | python | def visit_augassign(self, node):
return "%s %s %s" % (node.target.accept(self), node.op, node.value.accept(self)) | [
"def",
"visit_augassign",
"(",
"self",
",",
"node",
")",
":",
"return",
"\"%s %s %s\"",
"%",
"(",
"node",
".",
"target",
".",
"accept",
"(",
"self",
")",
",",
"node",
".",
"op",
",",
"node",
".",
"value",
".",
"accept",
"(",
"self",
")",
")"
] | return an astroid.AugAssign node as string | [
"return",
"an",
"astroid",
".",
"AugAssign",
"node",
"as",
"string"
] | e0a298df55b15abcb77c2a93253f5ab7be52d0fb | https://github.com/PyCQA/astroid/blob/e0a298df55b15abcb77c2a93253f5ab7be52d0fb/astroid/as_string.py#L108-L110 |
227,332 | PyCQA/astroid | astroid/as_string.py | AsStringVisitor.visit_annassign | def visit_annassign(self, node):
"""Return an astroid.AugAssign node as string"""
target = node.target.accept(self)
annotation = node.annotation.accept(self)
if node.value is None:
return "%s: %s" % (target, annotation)
return "%s: %s = %s" % (target, annotation, node.value.accept(self)) | python | def visit_annassign(self, node):
target = node.target.accept(self)
annotation = node.annotation.accept(self)
if node.value is None:
return "%s: %s" % (target, annotation)
return "%s: %s = %s" % (target, annotation, node.value.accept(self)) | [
"def",
"visit_annassign",
"(",
"self",
",",
"node",
")",
":",
"target",
"=",
"node",
".",
"target",
".",
"accept",
"(",
"self",
")",
"annotation",
"=",
"node",
".",
"annotation",
".",
"accept",
"(",
"self",
")",
"if",
"node",
".",
"value",
"is",
"Non... | Return an astroid.AugAssign node as string | [
"Return",
"an",
"astroid",
".",
"AugAssign",
"node",
"as",
"string"
] | e0a298df55b15abcb77c2a93253f5ab7be52d0fb | https://github.com/PyCQA/astroid/blob/e0a298df55b15abcb77c2a93253f5ab7be52d0fb/astroid/as_string.py#L112-L119 |
227,333 | PyCQA/astroid | astroid/as_string.py | AsStringVisitor.visit_binop | def visit_binop(self, node):
"""return an astroid.BinOp node as string"""
left = self._precedence_parens(node, node.left)
right = self._precedence_parens(node, node.right, is_left=False)
if node.op == "**":
return "%s%s%s" % (left, node.op, right)
return "%s %s %s" % (left, node.op, right) | python | def visit_binop(self, node):
left = self._precedence_parens(node, node.left)
right = self._precedence_parens(node, node.right, is_left=False)
if node.op == "**":
return "%s%s%s" % (left, node.op, right)
return "%s %s %s" % (left, node.op, right) | [
"def",
"visit_binop",
"(",
"self",
",",
"node",
")",
":",
"left",
"=",
"self",
".",
"_precedence_parens",
"(",
"node",
",",
"node",
".",
"left",
")",
"right",
"=",
"self",
".",
"_precedence_parens",
"(",
"node",
",",
"node",
".",
"right",
",",
"is_left... | return an astroid.BinOp node as string | [
"return",
"an",
"astroid",
".",
"BinOp",
"node",
"as",
"string"
] | e0a298df55b15abcb77c2a93253f5ab7be52d0fb | https://github.com/PyCQA/astroid/blob/e0a298df55b15abcb77c2a93253f5ab7be52d0fb/astroid/as_string.py#L125-L132 |
227,334 | PyCQA/astroid | astroid/as_string.py | AsStringVisitor.visit_boolop | def visit_boolop(self, node):
"""return an astroid.BoolOp node as string"""
values = ["%s" % self._precedence_parens(node, n) for n in node.values]
return (" %s " % node.op).join(values) | python | def visit_boolop(self, node):
values = ["%s" % self._precedence_parens(node, n) for n in node.values]
return (" %s " % node.op).join(values) | [
"def",
"visit_boolop",
"(",
"self",
",",
"node",
")",
":",
"values",
"=",
"[",
"\"%s\"",
"%",
"self",
".",
"_precedence_parens",
"(",
"node",
",",
"n",
")",
"for",
"n",
"in",
"node",
".",
"values",
"]",
"return",
"(",
"\" %s \"",
"%",
"node",
".",
... | return an astroid.BoolOp node as string | [
"return",
"an",
"astroid",
".",
"BoolOp",
"node",
"as",
"string"
] | e0a298df55b15abcb77c2a93253f5ab7be52d0fb | https://github.com/PyCQA/astroid/blob/e0a298df55b15abcb77c2a93253f5ab7be52d0fb/astroid/as_string.py#L134-L137 |
227,335 | PyCQA/astroid | astroid/as_string.py | AsStringVisitor.visit_call | def visit_call(self, node):
"""return an astroid.Call node as string"""
expr_str = self._precedence_parens(node, node.func)
args = [arg.accept(self) for arg in node.args]
if node.keywords:
keywords = [kwarg.accept(self) for kwarg in node.keywords]
else:
keywords = []
args.extend(keywords)
return "%s(%s)" % (expr_str, ", ".join(args)) | python | def visit_call(self, node):
expr_str = self._precedence_parens(node, node.func)
args = [arg.accept(self) for arg in node.args]
if node.keywords:
keywords = [kwarg.accept(self) for kwarg in node.keywords]
else:
keywords = []
args.extend(keywords)
return "%s(%s)" % (expr_str, ", ".join(args)) | [
"def",
"visit_call",
"(",
"self",
",",
"node",
")",
":",
"expr_str",
"=",
"self",
".",
"_precedence_parens",
"(",
"node",
",",
"node",
".",
"func",
")",
"args",
"=",
"[",
"arg",
".",
"accept",
"(",
"self",
")",
"for",
"arg",
"in",
"node",
".",
"arg... | return an astroid.Call node as string | [
"return",
"an",
"astroid",
".",
"Call",
"node",
"as",
"string"
] | e0a298df55b15abcb77c2a93253f5ab7be52d0fb | https://github.com/PyCQA/astroid/blob/e0a298df55b15abcb77c2a93253f5ab7be52d0fb/astroid/as_string.py#L143-L153 |
227,336 | PyCQA/astroid | astroid/as_string.py | AsStringVisitor.visit_classdef | def visit_classdef(self, node):
"""return an astroid.ClassDef node as string"""
decorate = node.decorators.accept(self) if node.decorators else ""
bases = ", ".join(n.accept(self) for n in node.bases)
metaclass = node.metaclass()
if metaclass and not node.has_metaclass_hack():
if bases:
bases = "(%s, metaclass=%s)" % (bases, metaclass.name)
else:
bases = "(metaclass=%s)" % metaclass.name
else:
bases = "(%s)" % bases if bases else ""
docs = self._docs_dedent(node.doc) if node.doc else ""
return "\n\n%sclass %s%s:%s\n%s\n" % (
decorate,
node.name,
bases,
docs,
self._stmt_list(node.body),
) | python | def visit_classdef(self, node):
decorate = node.decorators.accept(self) if node.decorators else ""
bases = ", ".join(n.accept(self) for n in node.bases)
metaclass = node.metaclass()
if metaclass and not node.has_metaclass_hack():
if bases:
bases = "(%s, metaclass=%s)" % (bases, metaclass.name)
else:
bases = "(metaclass=%s)" % metaclass.name
else:
bases = "(%s)" % bases if bases else ""
docs = self._docs_dedent(node.doc) if node.doc else ""
return "\n\n%sclass %s%s:%s\n%s\n" % (
decorate,
node.name,
bases,
docs,
self._stmt_list(node.body),
) | [
"def",
"visit_classdef",
"(",
"self",
",",
"node",
")",
":",
"decorate",
"=",
"node",
".",
"decorators",
".",
"accept",
"(",
"self",
")",
"if",
"node",
".",
"decorators",
"else",
"\"\"",
"bases",
"=",
"\", \"",
".",
"join",
"(",
"n",
".",
"accept",
"... | return an astroid.ClassDef node as string | [
"return",
"an",
"astroid",
".",
"ClassDef",
"node",
"as",
"string"
] | e0a298df55b15abcb77c2a93253f5ab7be52d0fb | https://github.com/PyCQA/astroid/blob/e0a298df55b15abcb77c2a93253f5ab7be52d0fb/astroid/as_string.py#L155-L174 |
227,337 | PyCQA/astroid | astroid/as_string.py | AsStringVisitor.visit_compare | def visit_compare(self, node):
"""return an astroid.Compare node as string"""
rhs_str = " ".join(
[
"%s %s" % (op, self._precedence_parens(node, expr, is_left=False))
for op, expr in node.ops
]
)
return "%s %s" % (self._precedence_parens(node, node.left), rhs_str) | python | def visit_compare(self, node):
rhs_str = " ".join(
[
"%s %s" % (op, self._precedence_parens(node, expr, is_left=False))
for op, expr in node.ops
]
)
return "%s %s" % (self._precedence_parens(node, node.left), rhs_str) | [
"def",
"visit_compare",
"(",
"self",
",",
"node",
")",
":",
"rhs_str",
"=",
"\" \"",
".",
"join",
"(",
"[",
"\"%s %s\"",
"%",
"(",
"op",
",",
"self",
".",
"_precedence_parens",
"(",
"node",
",",
"expr",
",",
"is_left",
"=",
"False",
")",
")",
"for",
... | return an astroid.Compare node as string | [
"return",
"an",
"astroid",
".",
"Compare",
"node",
"as",
"string"
] | e0a298df55b15abcb77c2a93253f5ab7be52d0fb | https://github.com/PyCQA/astroid/blob/e0a298df55b15abcb77c2a93253f5ab7be52d0fb/astroid/as_string.py#L176-L184 |
227,338 | PyCQA/astroid | astroid/as_string.py | AsStringVisitor.visit_delete | def visit_delete(self, node): # XXX check if correct
"""return an astroid.Delete node as string"""
return "del %s" % ", ".join(child.accept(self) for child in node.targets) | python | def visit_delete(self, node): # XXX check if correct
return "del %s" % ", ".join(child.accept(self) for child in node.targets) | [
"def",
"visit_delete",
"(",
"self",
",",
"node",
")",
":",
"# XXX check if correct",
"return",
"\"del %s\"",
"%",
"\", \"",
".",
"join",
"(",
"child",
".",
"accept",
"(",
"self",
")",
"for",
"child",
"in",
"node",
".",
"targets",
")"
] | return an astroid.Delete node as string | [
"return",
"an",
"astroid",
".",
"Delete",
"node",
"as",
"string"
] | e0a298df55b15abcb77c2a93253f5ab7be52d0fb | https://github.com/PyCQA/astroid/blob/e0a298df55b15abcb77c2a93253f5ab7be52d0fb/astroid/as_string.py#L205-L207 |
227,339 | PyCQA/astroid | astroid/as_string.py | AsStringVisitor.visit_decorators | def visit_decorators(self, node):
"""return an astroid.Decorators node as string"""
return "@%s\n" % "\n@".join(item.accept(self) for item in node.nodes) | python | def visit_decorators(self, node):
return "@%s\n" % "\n@".join(item.accept(self) for item in node.nodes) | [
"def",
"visit_decorators",
"(",
"self",
",",
"node",
")",
":",
"return",
"\"@%s\\n\"",
"%",
"\"\\n@\"",
".",
"join",
"(",
"item",
".",
"accept",
"(",
"self",
")",
"for",
"item",
"in",
"node",
".",
"nodes",
")"
] | return an astroid.Decorators node as string | [
"return",
"an",
"astroid",
".",
"Decorators",
"node",
"as",
"string"
] | e0a298df55b15abcb77c2a93253f5ab7be52d0fb | https://github.com/PyCQA/astroid/blob/e0a298df55b15abcb77c2a93253f5ab7be52d0fb/astroid/as_string.py#L217-L219 |
227,340 | PyCQA/astroid | astroid/as_string.py | AsStringVisitor.visit_dictcomp | def visit_dictcomp(self, node):
"""return an astroid.DictComp node as string"""
return "{%s: %s %s}" % (
node.key.accept(self),
node.value.accept(self),
" ".join(n.accept(self) for n in node.generators),
) | python | def visit_dictcomp(self, node):
return "{%s: %s %s}" % (
node.key.accept(self),
node.value.accept(self),
" ".join(n.accept(self) for n in node.generators),
) | [
"def",
"visit_dictcomp",
"(",
"self",
",",
"node",
")",
":",
"return",
"\"{%s: %s %s}\"",
"%",
"(",
"node",
".",
"key",
".",
"accept",
"(",
"self",
")",
",",
"node",
".",
"value",
".",
"accept",
"(",
"self",
")",
",",
"\" \"",
".",
"join",
"(",
"n"... | return an astroid.DictComp node as string | [
"return",
"an",
"astroid",
".",
"DictComp",
"node",
"as",
"string"
] | e0a298df55b15abcb77c2a93253f5ab7be52d0fb | https://github.com/PyCQA/astroid/blob/e0a298df55b15abcb77c2a93253f5ab7be52d0fb/astroid/as_string.py#L238-L244 |
227,341 | PyCQA/astroid | astroid/as_string.py | AsStringVisitor.visit_exec | def visit_exec(self, node):
"""return an astroid.Exec node as string"""
if node.locals:
return "exec %s in %s, %s" % (
node.expr.accept(self),
node.locals.accept(self),
node.globals.accept(self),
)
if node.globals:
return "exec %s in %s" % (node.expr.accept(self), node.globals.accept(self))
return "exec %s" % node.expr.accept(self) | python | def visit_exec(self, node):
if node.locals:
return "exec %s in %s, %s" % (
node.expr.accept(self),
node.locals.accept(self),
node.globals.accept(self),
)
if node.globals:
return "exec %s in %s" % (node.expr.accept(self), node.globals.accept(self))
return "exec %s" % node.expr.accept(self) | [
"def",
"visit_exec",
"(",
"self",
",",
"node",
")",
":",
"if",
"node",
".",
"locals",
":",
"return",
"\"exec %s in %s, %s\"",
"%",
"(",
"node",
".",
"expr",
".",
"accept",
"(",
"self",
")",
",",
"node",
".",
"locals",
".",
"accept",
"(",
"self",
")",... | return an astroid.Exec node as string | [
"return",
"an",
"astroid",
".",
"Exec",
"node",
"as",
"string"
] | e0a298df55b15abcb77c2a93253f5ab7be52d0fb | https://github.com/PyCQA/astroid/blob/e0a298df55b15abcb77c2a93253f5ab7be52d0fb/astroid/as_string.py#L275-L285 |
227,342 | PyCQA/astroid | astroid/as_string.py | AsStringVisitor.visit_extslice | def visit_extslice(self, node):
"""return an astroid.ExtSlice node as string"""
return ", ".join(dim.accept(self) for dim in node.dims) | python | def visit_extslice(self, node):
return ", ".join(dim.accept(self) for dim in node.dims) | [
"def",
"visit_extslice",
"(",
"self",
",",
"node",
")",
":",
"return",
"\", \"",
".",
"join",
"(",
"dim",
".",
"accept",
"(",
"self",
")",
"for",
"dim",
"in",
"node",
".",
"dims",
")"
] | return an astroid.ExtSlice node as string | [
"return",
"an",
"astroid",
".",
"ExtSlice",
"node",
"as",
"string"
] | e0a298df55b15abcb77c2a93253f5ab7be52d0fb | https://github.com/PyCQA/astroid/blob/e0a298df55b15abcb77c2a93253f5ab7be52d0fb/astroid/as_string.py#L287-L289 |
227,343 | PyCQA/astroid | astroid/as_string.py | AsStringVisitor.visit_for | def visit_for(self, node):
"""return an astroid.For node as string"""
fors = "for %s in %s:\n%s" % (
node.target.accept(self),
node.iter.accept(self),
self._stmt_list(node.body),
)
if node.orelse:
fors = "%s\nelse:\n%s" % (fors, self._stmt_list(node.orelse))
return fors | python | def visit_for(self, node):
fors = "for %s in %s:\n%s" % (
node.target.accept(self),
node.iter.accept(self),
self._stmt_list(node.body),
)
if node.orelse:
fors = "%s\nelse:\n%s" % (fors, self._stmt_list(node.orelse))
return fors | [
"def",
"visit_for",
"(",
"self",
",",
"node",
")",
":",
"fors",
"=",
"\"for %s in %s:\\n%s\"",
"%",
"(",
"node",
".",
"target",
".",
"accept",
"(",
"self",
")",
",",
"node",
".",
"iter",
".",
"accept",
"(",
"self",
")",
",",
"self",
".",
"_stmt_list"... | return an astroid.For node as string | [
"return",
"an",
"astroid",
".",
"For",
"node",
"as",
"string"
] | e0a298df55b15abcb77c2a93253f5ab7be52d0fb | https://github.com/PyCQA/astroid/blob/e0a298df55b15abcb77c2a93253f5ab7be52d0fb/astroid/as_string.py#L291-L300 |
227,344 | PyCQA/astroid | astroid/as_string.py | AsStringVisitor.visit_importfrom | def visit_importfrom(self, node):
"""return an astroid.ImportFrom node as string"""
return "from %s import %s" % (
"." * (node.level or 0) + node.modname,
_import_string(node.names),
) | python | def visit_importfrom(self, node):
return "from %s import %s" % (
"." * (node.level or 0) + node.modname,
_import_string(node.names),
) | [
"def",
"visit_importfrom",
"(",
"self",
",",
"node",
")",
":",
"return",
"\"from %s import %s\"",
"%",
"(",
"\".\"",
"*",
"(",
"node",
".",
"level",
"or",
"0",
")",
"+",
"node",
".",
"modname",
",",
"_import_string",
"(",
"node",
".",
"names",
")",
","... | return an astroid.ImportFrom node as string | [
"return",
"an",
"astroid",
".",
"ImportFrom",
"node",
"as",
"string"
] | e0a298df55b15abcb77c2a93253f5ab7be52d0fb | https://github.com/PyCQA/astroid/blob/e0a298df55b15abcb77c2a93253f5ab7be52d0fb/astroid/as_string.py#L302-L307 |
227,345 | PyCQA/astroid | astroid/as_string.py | AsStringVisitor.visit_functiondef | def visit_functiondef(self, node):
"""return an astroid.Function node as string"""
decorate = node.decorators.accept(self) if node.decorators else ""
docs = self._docs_dedent(node.doc) if node.doc else ""
trailer = ":"
if node.returns:
return_annotation = "->" + node.returns.as_string()
trailer = return_annotation + ":"
def_format = "\n%sdef %s(%s)%s%s\n%s"
return def_format % (
decorate,
node.name,
node.args.accept(self),
trailer,
docs,
self._stmt_list(node.body),
) | python | def visit_functiondef(self, node):
decorate = node.decorators.accept(self) if node.decorators else ""
docs = self._docs_dedent(node.doc) if node.doc else ""
trailer = ":"
if node.returns:
return_annotation = "->" + node.returns.as_string()
trailer = return_annotation + ":"
def_format = "\n%sdef %s(%s)%s%s\n%s"
return def_format % (
decorate,
node.name,
node.args.accept(self),
trailer,
docs,
self._stmt_list(node.body),
) | [
"def",
"visit_functiondef",
"(",
"self",
",",
"node",
")",
":",
"decorate",
"=",
"node",
".",
"decorators",
".",
"accept",
"(",
"self",
")",
"if",
"node",
".",
"decorators",
"else",
"\"\"",
"docs",
"=",
"self",
".",
"_docs_dedent",
"(",
"node",
".",
"d... | return an astroid.Function node as string | [
"return",
"an",
"astroid",
".",
"Function",
"node",
"as",
"string"
] | e0a298df55b15abcb77c2a93253f5ab7be52d0fb | https://github.com/PyCQA/astroid/blob/e0a298df55b15abcb77c2a93253f5ab7be52d0fb/astroid/as_string.py#L309-L325 |
227,346 | PyCQA/astroid | astroid/as_string.py | AsStringVisitor.visit_generatorexp | def visit_generatorexp(self, node):
"""return an astroid.GeneratorExp node as string"""
return "(%s %s)" % (
node.elt.accept(self),
" ".join(n.accept(self) for n in node.generators),
) | python | def visit_generatorexp(self, node):
return "(%s %s)" % (
node.elt.accept(self),
" ".join(n.accept(self) for n in node.generators),
) | [
"def",
"visit_generatorexp",
"(",
"self",
",",
"node",
")",
":",
"return",
"\"(%s %s)\"",
"%",
"(",
"node",
".",
"elt",
".",
"accept",
"(",
"self",
")",
",",
"\" \"",
".",
"join",
"(",
"n",
".",
"accept",
"(",
"self",
")",
"for",
"n",
"in",
"node",... | return an astroid.GeneratorExp node as string | [
"return",
"an",
"astroid",
".",
"GeneratorExp",
"node",
"as",
"string"
] | e0a298df55b15abcb77c2a93253f5ab7be52d0fb | https://github.com/PyCQA/astroid/blob/e0a298df55b15abcb77c2a93253f5ab7be52d0fb/astroid/as_string.py#L327-L332 |
227,347 | PyCQA/astroid | astroid/as_string.py | AsStringVisitor.visit_attribute | def visit_attribute(self, node):
"""return an astroid.Getattr node as string"""
return "%s.%s" % (self._precedence_parens(node, node.expr), node.attrname) | python | def visit_attribute(self, node):
return "%s.%s" % (self._precedence_parens(node, node.expr), node.attrname) | [
"def",
"visit_attribute",
"(",
"self",
",",
"node",
")",
":",
"return",
"\"%s.%s\"",
"%",
"(",
"self",
".",
"_precedence_parens",
"(",
"node",
",",
"node",
".",
"expr",
")",
",",
"node",
".",
"attrname",
")"
] | return an astroid.Getattr node as string | [
"return",
"an",
"astroid",
".",
"Getattr",
"node",
"as",
"string"
] | e0a298df55b15abcb77c2a93253f5ab7be52d0fb | https://github.com/PyCQA/astroid/blob/e0a298df55b15abcb77c2a93253f5ab7be52d0fb/astroid/as_string.py#L334-L336 |
227,348 | PyCQA/astroid | astroid/as_string.py | AsStringVisitor.visit_if | def visit_if(self, node):
"""return an astroid.If node as string"""
ifs = ["if %s:\n%s" % (node.test.accept(self), self._stmt_list(node.body))]
if node.has_elif_block():
ifs.append("el%s" % self._stmt_list(node.orelse, indent=False))
elif node.orelse:
ifs.append("else:\n%s" % self._stmt_list(node.orelse))
return "\n".join(ifs) | python | def visit_if(self, node):
ifs = ["if %s:\n%s" % (node.test.accept(self), self._stmt_list(node.body))]
if node.has_elif_block():
ifs.append("el%s" % self._stmt_list(node.orelse, indent=False))
elif node.orelse:
ifs.append("else:\n%s" % self._stmt_list(node.orelse))
return "\n".join(ifs) | [
"def",
"visit_if",
"(",
"self",
",",
"node",
")",
":",
"ifs",
"=",
"[",
"\"if %s:\\n%s\"",
"%",
"(",
"node",
".",
"test",
".",
"accept",
"(",
"self",
")",
",",
"self",
".",
"_stmt_list",
"(",
"node",
".",
"body",
")",
")",
"]",
"if",
"node",
".",... | return an astroid.If node as string | [
"return",
"an",
"astroid",
".",
"If",
"node",
"as",
"string"
] | e0a298df55b15abcb77c2a93253f5ab7be52d0fb | https://github.com/PyCQA/astroid/blob/e0a298df55b15abcb77c2a93253f5ab7be52d0fb/astroid/as_string.py#L342-L349 |
227,349 | PyCQA/astroid | astroid/as_string.py | AsStringVisitor.visit_ifexp | def visit_ifexp(self, node):
"""return an astroid.IfExp node as string"""
return "%s if %s else %s" % (
self._precedence_parens(node, node.body, is_left=True),
self._precedence_parens(node, node.test, is_left=True),
self._precedence_parens(node, node.orelse, is_left=False),
) | python | def visit_ifexp(self, node):
return "%s if %s else %s" % (
self._precedence_parens(node, node.body, is_left=True),
self._precedence_parens(node, node.test, is_left=True),
self._precedence_parens(node, node.orelse, is_left=False),
) | [
"def",
"visit_ifexp",
"(",
"self",
",",
"node",
")",
":",
"return",
"\"%s if %s else %s\"",
"%",
"(",
"self",
".",
"_precedence_parens",
"(",
"node",
",",
"node",
".",
"body",
",",
"is_left",
"=",
"True",
")",
",",
"self",
".",
"_precedence_parens",
"(",
... | return an astroid.IfExp node as string | [
"return",
"an",
"astroid",
".",
"IfExp",
"node",
"as",
"string"
] | e0a298df55b15abcb77c2a93253f5ab7be52d0fb | https://github.com/PyCQA/astroid/blob/e0a298df55b15abcb77c2a93253f5ab7be52d0fb/astroid/as_string.py#L351-L357 |
227,350 | PyCQA/astroid | astroid/as_string.py | AsStringVisitor.visit_keyword | def visit_keyword(self, node):
"""return an astroid.Keyword node as string"""
if node.arg is None:
return "**%s" % node.value.accept(self)
return "%s=%s" % (node.arg, node.value.accept(self)) | python | def visit_keyword(self, node):
if node.arg is None:
return "**%s" % node.value.accept(self)
return "%s=%s" % (node.arg, node.value.accept(self)) | [
"def",
"visit_keyword",
"(",
"self",
",",
"node",
")",
":",
"if",
"node",
".",
"arg",
"is",
"None",
":",
"return",
"\"**%s\"",
"%",
"node",
".",
"value",
".",
"accept",
"(",
"self",
")",
"return",
"\"%s=%s\"",
"%",
"(",
"node",
".",
"arg",
",",
"no... | return an astroid.Keyword node as string | [
"return",
"an",
"astroid",
".",
"Keyword",
"node",
"as",
"string"
] | e0a298df55b15abcb77c2a93253f5ab7be52d0fb | https://github.com/PyCQA/astroid/blob/e0a298df55b15abcb77c2a93253f5ab7be52d0fb/astroid/as_string.py#L363-L367 |
227,351 | PyCQA/astroid | astroid/as_string.py | AsStringVisitor.visit_lambda | def visit_lambda(self, node):
"""return an astroid.Lambda node as string"""
args = node.args.accept(self)
body = node.body.accept(self)
if args:
return "lambda %s: %s" % (args, body)
return "lambda: %s" % body | python | def visit_lambda(self, node):
args = node.args.accept(self)
body = node.body.accept(self)
if args:
return "lambda %s: %s" % (args, body)
return "lambda: %s" % body | [
"def",
"visit_lambda",
"(",
"self",
",",
"node",
")",
":",
"args",
"=",
"node",
".",
"args",
".",
"accept",
"(",
"self",
")",
"body",
"=",
"node",
".",
"body",
".",
"accept",
"(",
"self",
")",
"if",
"args",
":",
"return",
"\"lambda %s: %s\"",
"%",
... | return an astroid.Lambda node as string | [
"return",
"an",
"astroid",
".",
"Lambda",
"node",
"as",
"string"
] | e0a298df55b15abcb77c2a93253f5ab7be52d0fb | https://github.com/PyCQA/astroid/blob/e0a298df55b15abcb77c2a93253f5ab7be52d0fb/astroid/as_string.py#L369-L376 |
227,352 | PyCQA/astroid | astroid/as_string.py | AsStringVisitor.visit_list | def visit_list(self, node):
"""return an astroid.List node as string"""
return "[%s]" % ", ".join(child.accept(self) for child in node.elts) | python | def visit_list(self, node):
return "[%s]" % ", ".join(child.accept(self) for child in node.elts) | [
"def",
"visit_list",
"(",
"self",
",",
"node",
")",
":",
"return",
"\"[%s]\"",
"%",
"\", \"",
".",
"join",
"(",
"child",
".",
"accept",
"(",
"self",
")",
"for",
"child",
"in",
"node",
".",
"elts",
")"
] | return an astroid.List node as string | [
"return",
"an",
"astroid",
".",
"List",
"node",
"as",
"string"
] | e0a298df55b15abcb77c2a93253f5ab7be52d0fb | https://github.com/PyCQA/astroid/blob/e0a298df55b15abcb77c2a93253f5ab7be52d0fb/astroid/as_string.py#L378-L380 |
227,353 | PyCQA/astroid | astroid/as_string.py | AsStringVisitor.visit_listcomp | def visit_listcomp(self, node):
"""return an astroid.ListComp node as string"""
return "[%s %s]" % (
node.elt.accept(self),
" ".join(n.accept(self) for n in node.generators),
) | python | def visit_listcomp(self, node):
return "[%s %s]" % (
node.elt.accept(self),
" ".join(n.accept(self) for n in node.generators),
) | [
"def",
"visit_listcomp",
"(",
"self",
",",
"node",
")",
":",
"return",
"\"[%s %s]\"",
"%",
"(",
"node",
".",
"elt",
".",
"accept",
"(",
"self",
")",
",",
"\" \"",
".",
"join",
"(",
"n",
".",
"accept",
"(",
"self",
")",
"for",
"n",
"in",
"node",
"... | return an astroid.ListComp node as string | [
"return",
"an",
"astroid",
".",
"ListComp",
"node",
"as",
"string"
] | e0a298df55b15abcb77c2a93253f5ab7be52d0fb | https://github.com/PyCQA/astroid/blob/e0a298df55b15abcb77c2a93253f5ab7be52d0fb/astroid/as_string.py#L382-L387 |
227,354 | PyCQA/astroid | astroid/as_string.py | AsStringVisitor.visit_module | def visit_module(self, node):
"""return an astroid.Module node as string"""
docs = '"""%s"""\n\n' % node.doc if node.doc else ""
return docs + "\n".join(n.accept(self) for n in node.body) + "\n\n" | python | def visit_module(self, node):
docs = '"""%s"""\n\n' % node.doc if node.doc else ""
return docs + "\n".join(n.accept(self) for n in node.body) + "\n\n" | [
"def",
"visit_module",
"(",
"self",
",",
"node",
")",
":",
"docs",
"=",
"'\"\"\"%s\"\"\"\\n\\n'",
"%",
"node",
".",
"doc",
"if",
"node",
".",
"doc",
"else",
"\"\"",
"return",
"docs",
"+",
"\"\\n\"",
".",
"join",
"(",
"n",
".",
"accept",
"(",
"self",
... | return an astroid.Module node as string | [
"return",
"an",
"astroid",
".",
"Module",
"node",
"as",
"string"
] | e0a298df55b15abcb77c2a93253f5ab7be52d0fb | https://github.com/PyCQA/astroid/blob/e0a298df55b15abcb77c2a93253f5ab7be52d0fb/astroid/as_string.py#L389-L392 |
227,355 | PyCQA/astroid | astroid/as_string.py | AsStringVisitor.visit_print | def visit_print(self, node):
"""return an astroid.Print node as string"""
nodes = ", ".join(n.accept(self) for n in node.values)
if not node.nl:
nodes = "%s," % nodes
if node.dest:
return "print >> %s, %s" % (node.dest.accept(self), nodes)
return "print %s" % nodes | python | def visit_print(self, node):
nodes = ", ".join(n.accept(self) for n in node.values)
if not node.nl:
nodes = "%s," % nodes
if node.dest:
return "print >> %s, %s" % (node.dest.accept(self), nodes)
return "print %s" % nodes | [
"def",
"visit_print",
"(",
"self",
",",
"node",
")",
":",
"nodes",
"=",
"\", \"",
".",
"join",
"(",
"n",
".",
"accept",
"(",
"self",
")",
"for",
"n",
"in",
"node",
".",
"values",
")",
"if",
"not",
"node",
".",
"nl",
":",
"nodes",
"=",
"\"%s,\"",
... | return an astroid.Print node as string | [
"return",
"an",
"astroid",
".",
"Print",
"node",
"as",
"string"
] | e0a298df55b15abcb77c2a93253f5ab7be52d0fb | https://github.com/PyCQA/astroid/blob/e0a298df55b15abcb77c2a93253f5ab7be52d0fb/astroid/as_string.py#L402-L409 |
227,356 | PyCQA/astroid | astroid/as_string.py | AsStringVisitor.visit_return | def visit_return(self, node):
"""return an astroid.Return node as string"""
if node.is_tuple_return() and len(node.value.elts) > 1:
elts = [child.accept(self) for child in node.value.elts]
return "return %s" % ", ".join(elts)
if node.value:
return "return %s" % node.value.accept(self)
return "return" | python | def visit_return(self, node):
if node.is_tuple_return() and len(node.value.elts) > 1:
elts = [child.accept(self) for child in node.value.elts]
return "return %s" % ", ".join(elts)
if node.value:
return "return %s" % node.value.accept(self)
return "return" | [
"def",
"visit_return",
"(",
"self",
",",
"node",
")",
":",
"if",
"node",
".",
"is_tuple_return",
"(",
")",
"and",
"len",
"(",
"node",
".",
"value",
".",
"elts",
")",
">",
"1",
":",
"elts",
"=",
"[",
"child",
".",
"accept",
"(",
"self",
")",
"for"... | return an astroid.Return node as string | [
"return",
"an",
"astroid",
".",
"Return",
"node",
"as",
"string"
] | e0a298df55b15abcb77c2a93253f5ab7be52d0fb | https://github.com/PyCQA/astroid/blob/e0a298df55b15abcb77c2a93253f5ab7be52d0fb/astroid/as_string.py#L425-L434 |
227,357 | PyCQA/astroid | astroid/as_string.py | AsStringVisitor.visit_set | def visit_set(self, node):
"""return an astroid.Set node as string"""
return "{%s}" % ", ".join(child.accept(self) for child in node.elts) | python | def visit_set(self, node):
return "{%s}" % ", ".join(child.accept(self) for child in node.elts) | [
"def",
"visit_set",
"(",
"self",
",",
"node",
")",
":",
"return",
"\"{%s}\"",
"%",
"\", \"",
".",
"join",
"(",
"child",
".",
"accept",
"(",
"self",
")",
"for",
"child",
"in",
"node",
".",
"elts",
")"
] | return an astroid.Set node as string | [
"return",
"an",
"astroid",
".",
"Set",
"node",
"as",
"string"
] | e0a298df55b15abcb77c2a93253f5ab7be52d0fb | https://github.com/PyCQA/astroid/blob/e0a298df55b15abcb77c2a93253f5ab7be52d0fb/astroid/as_string.py#L440-L442 |
227,358 | PyCQA/astroid | astroid/as_string.py | AsStringVisitor.visit_setcomp | def visit_setcomp(self, node):
"""return an astroid.SetComp node as string"""
return "{%s %s}" % (
node.elt.accept(self),
" ".join(n.accept(self) for n in node.generators),
) | python | def visit_setcomp(self, node):
return "{%s %s}" % (
node.elt.accept(self),
" ".join(n.accept(self) for n in node.generators),
) | [
"def",
"visit_setcomp",
"(",
"self",
",",
"node",
")",
":",
"return",
"\"{%s %s}\"",
"%",
"(",
"node",
".",
"elt",
".",
"accept",
"(",
"self",
")",
",",
"\" \"",
".",
"join",
"(",
"n",
".",
"accept",
"(",
"self",
")",
"for",
"n",
"in",
"node",
".... | return an astroid.SetComp node as string | [
"return",
"an",
"astroid",
".",
"SetComp",
"node",
"as",
"string"
] | e0a298df55b15abcb77c2a93253f5ab7be52d0fb | https://github.com/PyCQA/astroid/blob/e0a298df55b15abcb77c2a93253f5ab7be52d0fb/astroid/as_string.py#L444-L449 |
227,359 | PyCQA/astroid | astroid/as_string.py | AsStringVisitor.visit_slice | def visit_slice(self, node):
"""return an astroid.Slice node as string"""
lower = node.lower.accept(self) if node.lower else ""
upper = node.upper.accept(self) if node.upper else ""
step = node.step.accept(self) if node.step else ""
if step:
return "%s:%s:%s" % (lower, upper, step)
return "%s:%s" % (lower, upper) | python | def visit_slice(self, node):
lower = node.lower.accept(self) if node.lower else ""
upper = node.upper.accept(self) if node.upper else ""
step = node.step.accept(self) if node.step else ""
if step:
return "%s:%s:%s" % (lower, upper, step)
return "%s:%s" % (lower, upper) | [
"def",
"visit_slice",
"(",
"self",
",",
"node",
")",
":",
"lower",
"=",
"node",
".",
"lower",
".",
"accept",
"(",
"self",
")",
"if",
"node",
".",
"lower",
"else",
"\"\"",
"upper",
"=",
"node",
".",
"upper",
".",
"accept",
"(",
"self",
")",
"if",
... | return an astroid.Slice node as string | [
"return",
"an",
"astroid",
".",
"Slice",
"node",
"as",
"string"
] | e0a298df55b15abcb77c2a93253f5ab7be52d0fb | https://github.com/PyCQA/astroid/blob/e0a298df55b15abcb77c2a93253f5ab7be52d0fb/astroid/as_string.py#L451-L458 |
227,360 | PyCQA/astroid | astroid/as_string.py | AsStringVisitor.visit_subscript | def visit_subscript(self, node):
"""return an astroid.Subscript node as string"""
idx = node.slice
if idx.__class__.__name__.lower() == "index":
idx = idx.value
idxstr = idx.accept(self)
if idx.__class__.__name__.lower() == "tuple" and idx.elts:
# Remove parenthesis in tuple and extended slice.
# a[(::1, 1:)] is not valid syntax.
idxstr = idxstr[1:-1]
return "%s[%s]" % (self._precedence_parens(node, node.value), idxstr) | python | def visit_subscript(self, node):
idx = node.slice
if idx.__class__.__name__.lower() == "index":
idx = idx.value
idxstr = idx.accept(self)
if idx.__class__.__name__.lower() == "tuple" and idx.elts:
# Remove parenthesis in tuple and extended slice.
# a[(::1, 1:)] is not valid syntax.
idxstr = idxstr[1:-1]
return "%s[%s]" % (self._precedence_parens(node, node.value), idxstr) | [
"def",
"visit_subscript",
"(",
"self",
",",
"node",
")",
":",
"idx",
"=",
"node",
".",
"slice",
"if",
"idx",
".",
"__class__",
".",
"__name__",
".",
"lower",
"(",
")",
"==",
"\"index\"",
":",
"idx",
"=",
"idx",
".",
"value",
"idxstr",
"=",
"idx",
"... | return an astroid.Subscript node as string | [
"return",
"an",
"astroid",
".",
"Subscript",
"node",
"as",
"string"
] | e0a298df55b15abcb77c2a93253f5ab7be52d0fb | https://github.com/PyCQA/astroid/blob/e0a298df55b15abcb77c2a93253f5ab7be52d0fb/astroid/as_string.py#L460-L470 |
227,361 | PyCQA/astroid | astroid/as_string.py | AsStringVisitor.visit_tryexcept | def visit_tryexcept(self, node):
"""return an astroid.TryExcept node as string"""
trys = ["try:\n%s" % self._stmt_list(node.body)]
for handler in node.handlers:
trys.append(handler.accept(self))
if node.orelse:
trys.append("else:\n%s" % self._stmt_list(node.orelse))
return "\n".join(trys) | python | def visit_tryexcept(self, node):
trys = ["try:\n%s" % self._stmt_list(node.body)]
for handler in node.handlers:
trys.append(handler.accept(self))
if node.orelse:
trys.append("else:\n%s" % self._stmt_list(node.orelse))
return "\n".join(trys) | [
"def",
"visit_tryexcept",
"(",
"self",
",",
"node",
")",
":",
"trys",
"=",
"[",
"\"try:\\n%s\"",
"%",
"self",
".",
"_stmt_list",
"(",
"node",
".",
"body",
")",
"]",
"for",
"handler",
"in",
"node",
".",
"handlers",
":",
"trys",
".",
"append",
"(",
"ha... | return an astroid.TryExcept node as string | [
"return",
"an",
"astroid",
".",
"TryExcept",
"node",
"as",
"string"
] | e0a298df55b15abcb77c2a93253f5ab7be52d0fb | https://github.com/PyCQA/astroid/blob/e0a298df55b15abcb77c2a93253f5ab7be52d0fb/astroid/as_string.py#L472-L479 |
227,362 | PyCQA/astroid | astroid/as_string.py | AsStringVisitor.visit_tryfinally | def visit_tryfinally(self, node):
"""return an astroid.TryFinally node as string"""
return "try:\n%s\nfinally:\n%s" % (
self._stmt_list(node.body),
self._stmt_list(node.finalbody),
) | python | def visit_tryfinally(self, node):
return "try:\n%s\nfinally:\n%s" % (
self._stmt_list(node.body),
self._stmt_list(node.finalbody),
) | [
"def",
"visit_tryfinally",
"(",
"self",
",",
"node",
")",
":",
"return",
"\"try:\\n%s\\nfinally:\\n%s\"",
"%",
"(",
"self",
".",
"_stmt_list",
"(",
"node",
".",
"body",
")",
",",
"self",
".",
"_stmt_list",
"(",
"node",
".",
"finalbody",
")",
",",
")"
] | return an astroid.TryFinally node as string | [
"return",
"an",
"astroid",
".",
"TryFinally",
"node",
"as",
"string"
] | e0a298df55b15abcb77c2a93253f5ab7be52d0fb | https://github.com/PyCQA/astroid/blob/e0a298df55b15abcb77c2a93253f5ab7be52d0fb/astroid/as_string.py#L481-L486 |
227,363 | PyCQA/astroid | astroid/as_string.py | AsStringVisitor.visit_tuple | def visit_tuple(self, node):
"""return an astroid.Tuple node as string"""
if len(node.elts) == 1:
return "(%s, )" % node.elts[0].accept(self)
return "(%s)" % ", ".join(child.accept(self) for child in node.elts) | python | def visit_tuple(self, node):
if len(node.elts) == 1:
return "(%s, )" % node.elts[0].accept(self)
return "(%s)" % ", ".join(child.accept(self) for child in node.elts) | [
"def",
"visit_tuple",
"(",
"self",
",",
"node",
")",
":",
"if",
"len",
"(",
"node",
".",
"elts",
")",
"==",
"1",
":",
"return",
"\"(%s, )\"",
"%",
"node",
".",
"elts",
"[",
"0",
"]",
".",
"accept",
"(",
"self",
")",
"return",
"\"(%s)\"",
"%",
"\"... | return an astroid.Tuple node as string | [
"return",
"an",
"astroid",
".",
"Tuple",
"node",
"as",
"string"
] | e0a298df55b15abcb77c2a93253f5ab7be52d0fb | https://github.com/PyCQA/astroid/blob/e0a298df55b15abcb77c2a93253f5ab7be52d0fb/astroid/as_string.py#L488-L492 |
227,364 | PyCQA/astroid | astroid/as_string.py | AsStringVisitor.visit_unaryop | def visit_unaryop(self, node):
"""return an astroid.UnaryOp node as string"""
if node.op == "not":
operator = "not "
else:
operator = node.op
return "%s%s" % (operator, self._precedence_parens(node, node.operand)) | python | def visit_unaryop(self, node):
if node.op == "not":
operator = "not "
else:
operator = node.op
return "%s%s" % (operator, self._precedence_parens(node, node.operand)) | [
"def",
"visit_unaryop",
"(",
"self",
",",
"node",
")",
":",
"if",
"node",
".",
"op",
"==",
"\"not\"",
":",
"operator",
"=",
"\"not \"",
"else",
":",
"operator",
"=",
"node",
".",
"op",
"return",
"\"%s%s\"",
"%",
"(",
"operator",
",",
"self",
".",
"_p... | return an astroid.UnaryOp node as string | [
"return",
"an",
"astroid",
".",
"UnaryOp",
"node",
"as",
"string"
] | e0a298df55b15abcb77c2a93253f5ab7be52d0fb | https://github.com/PyCQA/astroid/blob/e0a298df55b15abcb77c2a93253f5ab7be52d0fb/astroid/as_string.py#L494-L500 |
227,365 | PyCQA/astroid | astroid/as_string.py | AsStringVisitor.visit_while | def visit_while(self, node):
"""return an astroid.While node as string"""
whiles = "while %s:\n%s" % (node.test.accept(self), self._stmt_list(node.body))
if node.orelse:
whiles = "%s\nelse:\n%s" % (whiles, self._stmt_list(node.orelse))
return whiles | python | def visit_while(self, node):
whiles = "while %s:\n%s" % (node.test.accept(self), self._stmt_list(node.body))
if node.orelse:
whiles = "%s\nelse:\n%s" % (whiles, self._stmt_list(node.orelse))
return whiles | [
"def",
"visit_while",
"(",
"self",
",",
"node",
")",
":",
"whiles",
"=",
"\"while %s:\\n%s\"",
"%",
"(",
"node",
".",
"test",
".",
"accept",
"(",
"self",
")",
",",
"self",
".",
"_stmt_list",
"(",
"node",
".",
"body",
")",
")",
"if",
"node",
".",
"o... | return an astroid.While node as string | [
"return",
"an",
"astroid",
".",
"While",
"node",
"as",
"string"
] | e0a298df55b15abcb77c2a93253f5ab7be52d0fb | https://github.com/PyCQA/astroid/blob/e0a298df55b15abcb77c2a93253f5ab7be52d0fb/astroid/as_string.py#L502-L507 |
227,366 | PyCQA/astroid | astroid/as_string.py | AsStringVisitor.visit_with | def visit_with(self, node): # 'with' without 'as' is possible
"""return an astroid.With node as string"""
items = ", ".join(
("%s" % expr.accept(self)) + (vars and " as %s" % (vars.accept(self)) or "")
for expr, vars in node.items
)
return "with %s:\n%s" % (items, self._stmt_list(node.body)) | python | def visit_with(self, node): # 'with' without 'as' is possible
items = ", ".join(
("%s" % expr.accept(self)) + (vars and " as %s" % (vars.accept(self)) or "")
for expr, vars in node.items
)
return "with %s:\n%s" % (items, self._stmt_list(node.body)) | [
"def",
"visit_with",
"(",
"self",
",",
"node",
")",
":",
"# 'with' without 'as' is possible",
"items",
"=",
"\", \"",
".",
"join",
"(",
"(",
"\"%s\"",
"%",
"expr",
".",
"accept",
"(",
"self",
")",
")",
"+",
"(",
"vars",
"and",
"\" as %s\"",
"%",
"(",
"... | return an astroid.With node as string | [
"return",
"an",
"astroid",
".",
"With",
"node",
"as",
"string"
] | e0a298df55b15abcb77c2a93253f5ab7be52d0fb | https://github.com/PyCQA/astroid/blob/e0a298df55b15abcb77c2a93253f5ab7be52d0fb/astroid/as_string.py#L509-L515 |
227,367 | PyCQA/astroid | astroid/as_string.py | AsStringVisitor3.visit_yieldfrom | def visit_yieldfrom(self, node):
""" Return an astroid.YieldFrom node as string. """
yi_val = (" " + node.value.accept(self)) if node.value else ""
expr = "yield from" + yi_val
if node.parent.is_statement:
return expr
return "(%s)" % (expr,) | python | def visit_yieldfrom(self, node):
yi_val = (" " + node.value.accept(self)) if node.value else ""
expr = "yield from" + yi_val
if node.parent.is_statement:
return expr
return "(%s)" % (expr,) | [
"def",
"visit_yieldfrom",
"(",
"self",
",",
"node",
")",
":",
"yi_val",
"=",
"(",
"\" \"",
"+",
"node",
".",
"value",
".",
"accept",
"(",
"self",
")",
")",
"if",
"node",
".",
"value",
"else",
"\"\"",
"expr",
"=",
"\"yield from\"",
"+",
"yi_val",
"if"... | Return an astroid.YieldFrom node as string. | [
"Return",
"an",
"astroid",
".",
"YieldFrom",
"node",
"as",
"string",
"."
] | e0a298df55b15abcb77c2a93253f5ab7be52d0fb | https://github.com/PyCQA/astroid/blob/e0a298df55b15abcb77c2a93253f5ab7be52d0fb/astroid/as_string.py#L573-L580 |
227,368 | PyCQA/astroid | astroid/context.py | bind_context_to_node | def bind_context_to_node(context, node):
"""Give a context a boundnode
to retrieve the correct function name or attribute value
with from further inference.
Do not use an existing context since the boundnode could then
be incorrectly propagated higher up in the call stack.
:param context: Context to use
:type context: Optional(context)
:param node: Node to do name lookups from
:type node NodeNG:
:returns: A new context
:rtype: InferenceContext
"""
context = copy_context(context)
context.boundnode = node
return context | python | def bind_context_to_node(context, node):
context = copy_context(context)
context.boundnode = node
return context | [
"def",
"bind_context_to_node",
"(",
"context",
",",
"node",
")",
":",
"context",
"=",
"copy_context",
"(",
"context",
")",
"context",
".",
"boundnode",
"=",
"node",
"return",
"context"
] | Give a context a boundnode
to retrieve the correct function name or attribute value
with from further inference.
Do not use an existing context since the boundnode could then
be incorrectly propagated higher up in the call stack.
:param context: Context to use
:type context: Optional(context)
:param node: Node to do name lookups from
:type node NodeNG:
:returns: A new context
:rtype: InferenceContext | [
"Give",
"a",
"context",
"a",
"boundnode",
"to",
"retrieve",
"the",
"correct",
"function",
"name",
"or",
"attribute",
"value",
"with",
"from",
"further",
"inference",
"."
] | e0a298df55b15abcb77c2a93253f5ab7be52d0fb | https://github.com/PyCQA/astroid/blob/e0a298df55b15abcb77c2a93253f5ab7be52d0fb/astroid/context.py#L160-L179 |
227,369 | PyCQA/astroid | astroid/context.py | InferenceContext.push | def push(self, node):
"""Push node into inference path
:return: True if node is already in context path else False
:rtype: bool
Allows one to see if the given node has already
been looked at for this inference context"""
name = self.lookupname
if (node, name) in self.path:
return True
self.path.add((node, name))
return False | python | def push(self, node):
name = self.lookupname
if (node, name) in self.path:
return True
self.path.add((node, name))
return False | [
"def",
"push",
"(",
"self",
",",
"node",
")",
":",
"name",
"=",
"self",
".",
"lookupname",
"if",
"(",
"node",
",",
"name",
")",
"in",
"self",
".",
"path",
":",
"return",
"True",
"self",
".",
"path",
".",
"add",
"(",
"(",
"node",
",",
"name",
")... | Push node into inference path
:return: True if node is already in context path else False
:rtype: bool
Allows one to see if the given node has already
been looked at for this inference context | [
"Push",
"node",
"into",
"inference",
"path"
] | e0a298df55b15abcb77c2a93253f5ab7be52d0fb | https://github.com/PyCQA/astroid/blob/e0a298df55b15abcb77c2a93253f5ab7be52d0fb/astroid/context.py#L80-L93 |
227,370 | PyCQA/astroid | astroid/context.py | InferenceContext.clone | def clone(self):
"""Clone inference path
For example, each side of a binary operation (BinOp)
starts with the same context but diverge as each side is inferred
so the InferenceContext will need be cloned"""
# XXX copy lookupname/callcontext ?
clone = InferenceContext(self.path, inferred=self.inferred)
clone.callcontext = self.callcontext
clone.boundnode = self.boundnode
clone.extra_context = self.extra_context
return clone | python | def clone(self):
# XXX copy lookupname/callcontext ?
clone = InferenceContext(self.path, inferred=self.inferred)
clone.callcontext = self.callcontext
clone.boundnode = self.boundnode
clone.extra_context = self.extra_context
return clone | [
"def",
"clone",
"(",
"self",
")",
":",
"# XXX copy lookupname/callcontext ?",
"clone",
"=",
"InferenceContext",
"(",
"self",
".",
"path",
",",
"inferred",
"=",
"self",
".",
"inferred",
")",
"clone",
".",
"callcontext",
"=",
"self",
".",
"callcontext",
"clone",... | Clone inference path
For example, each side of a binary operation (BinOp)
starts with the same context but diverge as each side is inferred
so the InferenceContext will need be cloned | [
"Clone",
"inference",
"path"
] | e0a298df55b15abcb77c2a93253f5ab7be52d0fb | https://github.com/PyCQA/astroid/blob/e0a298df55b15abcb77c2a93253f5ab7be52d0fb/astroid/context.py#L95-L106 |
227,371 | PyCQA/astroid | astroid/context.py | InferenceContext.cache_generator | def cache_generator(self, key, generator):
"""Cache result of generator into dictionary
Used to cache inference results"""
results = []
for result in generator:
results.append(result)
yield result
self.inferred[key] = tuple(results) | python | def cache_generator(self, key, generator):
results = []
for result in generator:
results.append(result)
yield result
self.inferred[key] = tuple(results) | [
"def",
"cache_generator",
"(",
"self",
",",
"key",
",",
"generator",
")",
":",
"results",
"=",
"[",
"]",
"for",
"result",
"in",
"generator",
":",
"results",
".",
"append",
"(",
"result",
")",
"yield",
"result",
"self",
".",
"inferred",
"[",
"key",
"]",... | Cache result of generator into dictionary
Used to cache inference results | [
"Cache",
"result",
"of",
"generator",
"into",
"dictionary"
] | e0a298df55b15abcb77c2a93253f5ab7be52d0fb | https://github.com/PyCQA/astroid/blob/e0a298df55b15abcb77c2a93253f5ab7be52d0fb/astroid/context.py#L108-L117 |
227,372 | alanjds/drf-nested-routers | rest_framework_nested/viewsets.py | NestedViewSetMixin.get_queryset | def get_queryset(self):
"""
Filter the `QuerySet` based on its parents as defined in the
`serializer_class.parent_lookup_kwargs`.
"""
queryset = super(NestedViewSetMixin, self).get_queryset()
if hasattr(self.serializer_class, 'parent_lookup_kwargs'):
orm_filters = {}
for query_param, field_name in self.serializer_class.parent_lookup_kwargs.items():
orm_filters[field_name] = self.kwargs[query_param]
return queryset.filter(**orm_filters)
return queryset | python | def get_queryset(self):
queryset = super(NestedViewSetMixin, self).get_queryset()
if hasattr(self.serializer_class, 'parent_lookup_kwargs'):
orm_filters = {}
for query_param, field_name in self.serializer_class.parent_lookup_kwargs.items():
orm_filters[field_name] = self.kwargs[query_param]
return queryset.filter(**orm_filters)
return queryset | [
"def",
"get_queryset",
"(",
"self",
")",
":",
"queryset",
"=",
"super",
"(",
"NestedViewSetMixin",
",",
"self",
")",
".",
"get_queryset",
"(",
")",
"if",
"hasattr",
"(",
"self",
".",
"serializer_class",
",",
"'parent_lookup_kwargs'",
")",
":",
"orm_filters",
... | Filter the `QuerySet` based on its parents as defined in the
`serializer_class.parent_lookup_kwargs`. | [
"Filter",
"the",
"QuerySet",
"based",
"on",
"its",
"parents",
"as",
"defined",
"in",
"the",
"serializer_class",
".",
"parent_lookup_kwargs",
"."
] | 8c48cae40522612debaca761503b4e1a6f1cdba4 | https://github.com/alanjds/drf-nested-routers/blob/8c48cae40522612debaca761503b4e1a6f1cdba4/rest_framework_nested/viewsets.py#L2-L13 |
227,373 | buguroo/pyknow | pyknow/matchers/rete/__init__.py | ReteMatcher.changes | def changes(self, adding=None, deleting=None):
"""Pass the given changes to the root_node."""
if deleting is not None:
for deleted in deleting:
self.root_node.remove(deleted)
if adding is not None:
for added in adding:
self.root_node.add(added)
added = list()
removed = list()
for csn in self._get_conflict_set_nodes():
c_added, c_removed = csn.get_activations()
added.extend(c_added)
removed.extend(c_removed)
return (added, removed) | python | def changes(self, adding=None, deleting=None):
if deleting is not None:
for deleted in deleting:
self.root_node.remove(deleted)
if adding is not None:
for added in adding:
self.root_node.add(added)
added = list()
removed = list()
for csn in self._get_conflict_set_nodes():
c_added, c_removed = csn.get_activations()
added.extend(c_added)
removed.extend(c_removed)
return (added, removed) | [
"def",
"changes",
"(",
"self",
",",
"adding",
"=",
"None",
",",
"deleting",
"=",
"None",
")",
":",
"if",
"deleting",
"is",
"not",
"None",
":",
"for",
"deleted",
"in",
"deleting",
":",
"self",
".",
"root_node",
".",
"remove",
"(",
"deleted",
")",
"if"... | Pass the given changes to the root_node. | [
"Pass",
"the",
"given",
"changes",
"to",
"the",
"root_node",
"."
] | 48818336f2e9a126f1964f2d8dc22d37ff800fe8 | https://github.com/buguroo/pyknow/blob/48818336f2e9a126f1964f2d8dc22d37ff800fe8/pyknow/matchers/rete/__init__.py#L49-L67 |
227,374 | buguroo/pyknow | pyknow/matchers/rete/__init__.py | ReteMatcher.build_alpha_part | def build_alpha_part(ruleset, root_node):
"""
Given a set of already adapted rules, build the alpha part of
the RETE network starting at `root_node`.
"""
# Adds a dummy rule with InitialFact as LHS for always generate
# the alpha part matching InitialFact(). This is needed for the
# CE using InitialFact
ruleset = ruleset.copy()
ruleset.add(Rule(InitialFact()))
# Generate a dictionary with rules and the set of facts of the
# rule.
rule_facts = {rule: extract_facts(rule) for rule in ruleset}
# For each fact build a list of checker function capable of
# check for each part in the fact.
fact_checks = {fact: set(generate_checks(fact))
for fact in chain.from_iterable(rule_facts.values())}
# Make a ranking of the most used checks
check_rank = Counter(chain.from_iterable(fact_checks.values()))
def weighted_check_sort(check):
"""Sort check by its type and number of times seen."""
if isinstance(check, TypeCheck):
return (float('inf'), hash(check))
elif isinstance(check, FactCapture):
return (float('-inf'), hash(check))
elif isinstance(check, FeatureCheck):
return (check_rank[check], hash(check))
else:
raise TypeError("Unknown check type.") # pragma: no cover
def weighted_rule_sort(rule):
"""Sort rules by the average weight of its checks."""
total = 0
for fact in rule_facts[rule]:
for check in fact_checks[fact]:
total += check_rank[check]
return total / len(rule_facts[rule])
sorted_rules = sorted(ruleset, key=weighted_rule_sort, reverse=True)
fact_terminal_nodes = dict()
# For rule in rank order and for each rule fact also in rank
# order, build the alpha brank looking for an existing node
# first.
for rule in sorted_rules:
for fact in rule_facts[rule]:
current_node = root_node
fact_sorted_checks = sorted(
fact_checks[fact],
key=weighted_check_sort,
reverse=True)
for check in fact_sorted_checks:
# Look for a child node with the given check in the
# current parent node.
for child in current_node.children:
if child.node.matcher is check:
current_node = child.node
break
else:
# Create a new node and append as child
new_node = FeatureTesterNode(check)
current_node.add_child(new_node, new_node.activate)
current_node = new_node
fact_terminal_nodes[fact] = current_node
# Return this dictionary containing the last alpha node for each
# fact.
return fact_terminal_nodes | python | def build_alpha_part(ruleset, root_node):
# Adds a dummy rule with InitialFact as LHS for always generate
# the alpha part matching InitialFact(). This is needed for the
# CE using InitialFact
ruleset = ruleset.copy()
ruleset.add(Rule(InitialFact()))
# Generate a dictionary with rules and the set of facts of the
# rule.
rule_facts = {rule: extract_facts(rule) for rule in ruleset}
# For each fact build a list of checker function capable of
# check for each part in the fact.
fact_checks = {fact: set(generate_checks(fact))
for fact in chain.from_iterable(rule_facts.values())}
# Make a ranking of the most used checks
check_rank = Counter(chain.from_iterable(fact_checks.values()))
def weighted_check_sort(check):
"""Sort check by its type and number of times seen."""
if isinstance(check, TypeCheck):
return (float('inf'), hash(check))
elif isinstance(check, FactCapture):
return (float('-inf'), hash(check))
elif isinstance(check, FeatureCheck):
return (check_rank[check], hash(check))
else:
raise TypeError("Unknown check type.") # pragma: no cover
def weighted_rule_sort(rule):
"""Sort rules by the average weight of its checks."""
total = 0
for fact in rule_facts[rule]:
for check in fact_checks[fact]:
total += check_rank[check]
return total / len(rule_facts[rule])
sorted_rules = sorted(ruleset, key=weighted_rule_sort, reverse=True)
fact_terminal_nodes = dict()
# For rule in rank order and for each rule fact also in rank
# order, build the alpha brank looking for an existing node
# first.
for rule in sorted_rules:
for fact in rule_facts[rule]:
current_node = root_node
fact_sorted_checks = sorted(
fact_checks[fact],
key=weighted_check_sort,
reverse=True)
for check in fact_sorted_checks:
# Look for a child node with the given check in the
# current parent node.
for child in current_node.children:
if child.node.matcher is check:
current_node = child.node
break
else:
# Create a new node and append as child
new_node = FeatureTesterNode(check)
current_node.add_child(new_node, new_node.activate)
current_node = new_node
fact_terminal_nodes[fact] = current_node
# Return this dictionary containing the last alpha node for each
# fact.
return fact_terminal_nodes | [
"def",
"build_alpha_part",
"(",
"ruleset",
",",
"root_node",
")",
":",
"# Adds a dummy rule with InitialFact as LHS for always generate",
"# the alpha part matching InitialFact(). This is needed for the",
"# CE using InitialFact",
"ruleset",
"=",
"ruleset",
".",
"copy",
"(",
")",
... | Given a set of already adapted rules, build the alpha part of
the RETE network starting at `root_node`. | [
"Given",
"a",
"set",
"of",
"already",
"adapted",
"rules",
"build",
"the",
"alpha",
"part",
"of",
"the",
"RETE",
"network",
"starting",
"at",
"root_node",
"."
] | 48818336f2e9a126f1964f2d8dc22d37ff800fe8 | https://github.com/buguroo/pyknow/blob/48818336f2e9a126f1964f2d8dc22d37ff800fe8/pyknow/matchers/rete/__init__.py#L87-L161 |
227,375 | buguroo/pyknow | pyknow/matchers/rete/__init__.py | ReteMatcher.build_beta_part | def build_beta_part(ruleset, alpha_terminals):
"""
Given a set of already adapted rules, and a dictionary of
patterns and alpha_nodes, wire up the beta part of the RETE
network.
"""
for rule in ruleset:
if isinstance(rule[0], OR):
for subrule in rule[0]:
wire_rule(rule, alpha_terminals, lhs=subrule)
else:
wire_rule(rule, alpha_terminals, lhs=rule) | python | def build_beta_part(ruleset, alpha_terminals):
for rule in ruleset:
if isinstance(rule[0], OR):
for subrule in rule[0]:
wire_rule(rule, alpha_terminals, lhs=subrule)
else:
wire_rule(rule, alpha_terminals, lhs=rule) | [
"def",
"build_beta_part",
"(",
"ruleset",
",",
"alpha_terminals",
")",
":",
"for",
"rule",
"in",
"ruleset",
":",
"if",
"isinstance",
"(",
"rule",
"[",
"0",
"]",
",",
"OR",
")",
":",
"for",
"subrule",
"in",
"rule",
"[",
"0",
"]",
":",
"wire_rule",
"("... | Given a set of already adapted rules, and a dictionary of
patterns and alpha_nodes, wire up the beta part of the RETE
network. | [
"Given",
"a",
"set",
"of",
"already",
"adapted",
"rules",
"and",
"a",
"dictionary",
"of",
"patterns",
"and",
"alpha_nodes",
"wire",
"up",
"the",
"beta",
"part",
"of",
"the",
"RETE",
"network",
"."
] | 48818336f2e9a126f1964f2d8dc22d37ff800fe8 | https://github.com/buguroo/pyknow/blob/48818336f2e9a126f1964f2d8dc22d37ff800fe8/pyknow/matchers/rete/__init__.py#L164-L176 |
227,376 | buguroo/pyknow | pyknow/matchers/rete/__init__.py | ReteMatcher.print_network | def print_network(self): # pragma: no cover
"""
Generate a graphviz compatible graph.
"""
edges = set()
def gen_edges(node):
nonlocal edges
name = str(id(node))
yield '{name} [label="{cls_name}"];'.format(
name=name,
cls_name=str(node))
for child in node.children:
if (node, child.callback) not in edges:
yield ('{parent} -> {child} '
'[label="{child_label}"];').format(
parent=name,
child=str(id(child.node)),
child_label=child.callback.__name__)
edges.add((node, child.callback))
yield from gen_edges(child.node)
return "digraph {\n %s \n}" % ("\n".join(
gen_edges(self.root_node))) | python | def print_network(self): # pragma: no cover
edges = set()
def gen_edges(node):
nonlocal edges
name = str(id(node))
yield '{name} [label="{cls_name}"];'.format(
name=name,
cls_name=str(node))
for child in node.children:
if (node, child.callback) not in edges:
yield ('{parent} -> {child} '
'[label="{child_label}"];').format(
parent=name,
child=str(id(child.node)),
child_label=child.callback.__name__)
edges.add((node, child.callback))
yield from gen_edges(child.node)
return "digraph {\n %s \n}" % ("\n".join(
gen_edges(self.root_node))) | [
"def",
"print_network",
"(",
"self",
")",
":",
"# pragma: no cover",
"edges",
"=",
"set",
"(",
")",
"def",
"gen_edges",
"(",
"node",
")",
":",
"nonlocal",
"edges",
"name",
"=",
"str",
"(",
"id",
"(",
"node",
")",
")",
"yield",
"'{name} [label=\"{cls_name}\... | Generate a graphviz compatible graph. | [
"Generate",
"a",
"graphviz",
"compatible",
"graph",
"."
] | 48818336f2e9a126f1964f2d8dc22d37ff800fe8 | https://github.com/buguroo/pyknow/blob/48818336f2e9a126f1964f2d8dc22d37ff800fe8/pyknow/matchers/rete/__init__.py#L178-L204 |
227,377 | buguroo/pyknow | pyknow/matchers/rete/abstract.py | Node.reset | def reset(self):
"""Reset itself and recursively all its children."""
watchers.MATCHER.debug("Node <%s> reset", self)
self._reset()
for child in self.children:
child.node.reset() | python | def reset(self):
watchers.MATCHER.debug("Node <%s> reset", self)
self._reset()
for child in self.children:
child.node.reset() | [
"def",
"reset",
"(",
"self",
")",
":",
"watchers",
".",
"MATCHER",
".",
"debug",
"(",
"\"Node <%s> reset\"",
",",
"self",
")",
"self",
".",
"_reset",
"(",
")",
"for",
"child",
"in",
"self",
".",
"children",
":",
"child",
".",
"node",
".",
"reset",
"(... | Reset itself and recursively all its children. | [
"Reset",
"itself",
"and",
"recursively",
"all",
"its",
"children",
"."
] | 48818336f2e9a126f1964f2d8dc22d37ff800fe8 | https://github.com/buguroo/pyknow/blob/48818336f2e9a126f1964f2d8dc22d37ff800fe8/pyknow/matchers/rete/abstract.py#L20-L25 |
227,378 | buguroo/pyknow | pyknow/matchers/rete/abstract.py | OneInputNode.activate | def activate(self, token):
"""Make a copy of the received token and call `self._activate`."""
if watchers.worth('MATCHER', 'DEBUG'): # pragma: no cover
watchers.MATCHER.debug(
"Node <%s> activated with token %r", self, token)
return self._activate(token.copy()) | python | def activate(self, token):
if watchers.worth('MATCHER', 'DEBUG'): # pragma: no cover
watchers.MATCHER.debug(
"Node <%s> activated with token %r", self, token)
return self._activate(token.copy()) | [
"def",
"activate",
"(",
"self",
",",
"token",
")",
":",
"if",
"watchers",
".",
"worth",
"(",
"'MATCHER'",
",",
"'DEBUG'",
")",
":",
"# pragma: no cover",
"watchers",
".",
"MATCHER",
".",
"debug",
"(",
"\"Node <%s> activated with token %r\"",
",",
"self",
",",
... | Make a copy of the received token and call `self._activate`. | [
"Make",
"a",
"copy",
"of",
"the",
"received",
"token",
"and",
"call",
"self",
".",
"_activate",
"."
] | 48818336f2e9a126f1964f2d8dc22d37ff800fe8 | https://github.com/buguroo/pyknow/blob/48818336f2e9a126f1964f2d8dc22d37ff800fe8/pyknow/matchers/rete/abstract.py#L39-L46 |
227,379 | buguroo/pyknow | pyknow/matchers/rete/abstract.py | TwoInputNode.activate_left | def activate_left(self, token):
"""Make a copy of the received token and call `_activate_left`."""
watchers.MATCHER.debug(
"Node <%s> activated left with token %r", self, token)
return self._activate_left(token.copy()) | python | def activate_left(self, token):
watchers.MATCHER.debug(
"Node <%s> activated left with token %r", self, token)
return self._activate_left(token.copy()) | [
"def",
"activate_left",
"(",
"self",
",",
"token",
")",
":",
"watchers",
".",
"MATCHER",
".",
"debug",
"(",
"\"Node <%s> activated left with token %r\"",
",",
"self",
",",
"token",
")",
"return",
"self",
".",
"_activate_left",
"(",
"token",
".",
"copy",
"(",
... | Make a copy of the received token and call `_activate_left`. | [
"Make",
"a",
"copy",
"of",
"the",
"received",
"token",
"and",
"call",
"_activate_left",
"."
] | 48818336f2e9a126f1964f2d8dc22d37ff800fe8 | https://github.com/buguroo/pyknow/blob/48818336f2e9a126f1964f2d8dc22d37ff800fe8/pyknow/matchers/rete/abstract.py#L57-L61 |
227,380 | buguroo/pyknow | pyknow/matchers/rete/abstract.py | TwoInputNode.activate_right | def activate_right(self, token):
"""Make a copy of the received token and call `_activate_right`."""
watchers.MATCHER.debug(
"Node <%s> activated right with token %r", self, token)
return self._activate_right(token.copy()) | python | def activate_right(self, token):
watchers.MATCHER.debug(
"Node <%s> activated right with token %r", self, token)
return self._activate_right(token.copy()) | [
"def",
"activate_right",
"(",
"self",
",",
"token",
")",
":",
"watchers",
".",
"MATCHER",
".",
"debug",
"(",
"\"Node <%s> activated right with token %r\"",
",",
"self",
",",
"token",
")",
"return",
"self",
".",
"_activate_right",
"(",
"token",
".",
"copy",
"("... | Make a copy of the received token and call `_activate_right`. | [
"Make",
"a",
"copy",
"of",
"the",
"received",
"token",
"and",
"call",
"_activate_right",
"."
] | 48818336f2e9a126f1964f2d8dc22d37ff800fe8 | https://github.com/buguroo/pyknow/blob/48818336f2e9a126f1964f2d8dc22d37ff800fe8/pyknow/matchers/rete/abstract.py#L68-L72 |
227,381 | buguroo/pyknow | pyknow/engine.py | KnowledgeEngine.duplicate | def duplicate(self, template_fact, **modifiers):
"""Create a new fact from an existing one."""
newfact = template_fact.copy()
newfact.update(dict(self._get_real_modifiers(**modifiers)))
return self.declare(newfact) | python | def duplicate(self, template_fact, **modifiers):
newfact = template_fact.copy()
newfact.update(dict(self._get_real_modifiers(**modifiers)))
return self.declare(newfact) | [
"def",
"duplicate",
"(",
"self",
",",
"template_fact",
",",
"*",
"*",
"modifiers",
")",
":",
"newfact",
"=",
"template_fact",
".",
"copy",
"(",
")",
"newfact",
".",
"update",
"(",
"dict",
"(",
"self",
".",
"_get_real_modifiers",
"(",
"*",
"*",
"modifiers... | Create a new fact from an existing one. | [
"Create",
"a",
"new",
"fact",
"from",
"an",
"existing",
"one",
"."
] | 48818336f2e9a126f1964f2d8dc22d37ff800fe8 | https://github.com/buguroo/pyknow/blob/48818336f2e9a126f1964f2d8dc22d37ff800fe8/pyknow/engine.py#L85-L91 |
227,382 | buguroo/pyknow | pyknow/engine.py | KnowledgeEngine.get_deffacts | def get_deffacts(self):
"""Return the existing deffacts sorted by the internal order"""
return sorted(self._get_by_type(DefFacts), key=lambda d: d.order) | python | def get_deffacts(self):
return sorted(self._get_by_type(DefFacts), key=lambda d: d.order) | [
"def",
"get_deffacts",
"(",
"self",
")",
":",
"return",
"sorted",
"(",
"self",
".",
"_get_by_type",
"(",
"DefFacts",
")",
",",
"key",
"=",
"lambda",
"d",
":",
"d",
".",
"order",
")"
] | Return the existing deffacts sorted by the internal order | [
"Return",
"the",
"existing",
"deffacts",
"sorted",
"by",
"the",
"internal",
"order"
] | 48818336f2e9a126f1964f2d8dc22d37ff800fe8 | https://github.com/buguroo/pyknow/blob/48818336f2e9a126f1964f2d8dc22d37ff800fe8/pyknow/engine.py#L107-L109 |
227,383 | buguroo/pyknow | pyknow/engine.py | KnowledgeEngine.retract | def retract(self, idx_or_declared_fact):
"""
Retracts a specific fact, using its index
.. note::
This updates the agenda
"""
self.facts.retract(idx_or_declared_fact)
if not self.running:
added, removed = self.get_activations()
self.strategy.update_agenda(self.agenda, added, removed) | python | def retract(self, idx_or_declared_fact):
self.facts.retract(idx_or_declared_fact)
if not self.running:
added, removed = self.get_activations()
self.strategy.update_agenda(self.agenda, added, removed) | [
"def",
"retract",
"(",
"self",
",",
"idx_or_declared_fact",
")",
":",
"self",
".",
"facts",
".",
"retract",
"(",
"idx_or_declared_fact",
")",
"if",
"not",
"self",
".",
"running",
":",
"added",
",",
"removed",
"=",
"self",
".",
"get_activations",
"(",
")",
... | Retracts a specific fact, using its index
.. note::
This updates the agenda | [
"Retracts",
"a",
"specific",
"fact",
"using",
"its",
"index"
] | 48818336f2e9a126f1964f2d8dc22d37ff800fe8 | https://github.com/buguroo/pyknow/blob/48818336f2e9a126f1964f2d8dc22d37ff800fe8/pyknow/engine.py#L117-L128 |
227,384 | buguroo/pyknow | pyknow/engine.py | KnowledgeEngine.run | def run(self, steps=float('inf')):
"""
Execute agenda activations
"""
self.running = True
activation = None
execution = 0
while steps > 0 and self.running:
added, removed = self.get_activations()
self.strategy.update_agenda(self.agenda, added, removed)
if watchers.worth('AGENDA', 'DEBUG'): # pragma: no cover
for idx, act in enumerate(self.agenda.activations):
watchers.AGENDA.debug(
"%d: %r %r",
idx,
act.rule.__name__,
", ".join(str(f) for f in act.facts))
activation = self.agenda.get_next()
if activation is None:
break
else:
steps -= 1
execution += 1
watchers.RULES.info(
"FIRE %s %s: %s",
execution,
activation.rule.__name__,
", ".join(str(f) for f in activation.facts))
activation.rule(
self,
**{k: v
for k, v in activation.context.items()
if not k.startswith('__')})
self.running = False | python | def run(self, steps=float('inf')):
self.running = True
activation = None
execution = 0
while steps > 0 and self.running:
added, removed = self.get_activations()
self.strategy.update_agenda(self.agenda, added, removed)
if watchers.worth('AGENDA', 'DEBUG'): # pragma: no cover
for idx, act in enumerate(self.agenda.activations):
watchers.AGENDA.debug(
"%d: %r %r",
idx,
act.rule.__name__,
", ".join(str(f) for f in act.facts))
activation = self.agenda.get_next()
if activation is None:
break
else:
steps -= 1
execution += 1
watchers.RULES.info(
"FIRE %s %s: %s",
execution,
activation.rule.__name__,
", ".join(str(f) for f in activation.facts))
activation.rule(
self,
**{k: v
for k, v in activation.context.items()
if not k.startswith('__')})
self.running = False | [
"def",
"run",
"(",
"self",
",",
"steps",
"=",
"float",
"(",
"'inf'",
")",
")",
":",
"self",
".",
"running",
"=",
"True",
"activation",
"=",
"None",
"execution",
"=",
"0",
"while",
"steps",
">",
"0",
"and",
"self",
".",
"running",
":",
"added",
",",... | Execute agenda activations | [
"Execute",
"agenda",
"activations"
] | 48818336f2e9a126f1964f2d8dc22d37ff800fe8 | https://github.com/buguroo/pyknow/blob/48818336f2e9a126f1964f2d8dc22d37ff800fe8/pyknow/engine.py#L130-L171 |
227,385 | buguroo/pyknow | pyknow/engine.py | KnowledgeEngine.__declare | def __declare(self, *facts):
"""
Internal declaration method. Used for ``declare`` and ``deffacts``
"""
if any(f.has_field_constraints() for f in facts):
raise TypeError(
"Declared facts cannot contain conditional elements")
elif any(f.has_nested_accessor() for f in facts):
raise KeyError(
"Cannot declare facts containing double underscores as keys.")
else:
last_inserted = None
for fact in facts:
last_inserted = self.facts.declare(fact)
if not self.running:
added, removed = self.get_activations()
self.strategy.update_agenda(self.agenda, added, removed)
return last_inserted | python | def __declare(self, *facts):
if any(f.has_field_constraints() for f in facts):
raise TypeError(
"Declared facts cannot contain conditional elements")
elif any(f.has_nested_accessor() for f in facts):
raise KeyError(
"Cannot declare facts containing double underscores as keys.")
else:
last_inserted = None
for fact in facts:
last_inserted = self.facts.declare(fact)
if not self.running:
added, removed = self.get_activations()
self.strategy.update_agenda(self.agenda, added, removed)
return last_inserted | [
"def",
"__declare",
"(",
"self",
",",
"*",
"facts",
")",
":",
"if",
"any",
"(",
"f",
".",
"has_field_constraints",
"(",
")",
"for",
"f",
"in",
"facts",
")",
":",
"raise",
"TypeError",
"(",
"\"Declared facts cannot contain conditional elements\"",
")",
"elif",
... | Internal declaration method. Used for ``declare`` and ``deffacts`` | [
"Internal",
"declaration",
"method",
".",
"Used",
"for",
"declare",
"and",
"deffacts"
] | 48818336f2e9a126f1964f2d8dc22d37ff800fe8 | https://github.com/buguroo/pyknow/blob/48818336f2e9a126f1964f2d8dc22d37ff800fe8/pyknow/engine.py#L212-L231 |
227,386 | buguroo/pyknow | pyknow/engine.py | KnowledgeEngine.declare | def declare(self, *facts):
"""
Declare from inside a fact, equivalent to ``assert`` in clips.
.. note::
This updates the agenda.
"""
if not self.facts:
watchers.ENGINE.warning("Declaring fact before reset()")
return self.__declare(*facts) | python | def declare(self, *facts):
if not self.facts:
watchers.ENGINE.warning("Declaring fact before reset()")
return self.__declare(*facts) | [
"def",
"declare",
"(",
"self",
",",
"*",
"facts",
")",
":",
"if",
"not",
"self",
".",
"facts",
":",
"watchers",
".",
"ENGINE",
".",
"warning",
"(",
"\"Declaring fact before reset()\"",
")",
"return",
"self",
".",
"__declare",
"(",
"*",
"facts",
")"
] | Declare from inside a fact, equivalent to ``assert`` in clips.
.. note::
This updates the agenda. | [
"Declare",
"from",
"inside",
"a",
"fact",
"equivalent",
"to",
"assert",
"in",
"clips",
"."
] | 48818336f2e9a126f1964f2d8dc22d37ff800fe8 | https://github.com/buguroo/pyknow/blob/48818336f2e9a126f1964f2d8dc22d37ff800fe8/pyknow/engine.py#L233-L244 |
227,387 | buguroo/pyknow | pyknow/operator.py | REGEX | def REGEX(pattern, flags=0):
"""Regular expression matching."""
return P(lambda x: re.match(pattern, x, flags=flags)) | python | def REGEX(pattern, flags=0):
return P(lambda x: re.match(pattern, x, flags=flags)) | [
"def",
"REGEX",
"(",
"pattern",
",",
"flags",
"=",
"0",
")",
":",
"return",
"P",
"(",
"lambda",
"x",
":",
"re",
".",
"match",
"(",
"pattern",
",",
"x",
",",
"flags",
"=",
"flags",
")",
")"
] | Regular expression matching. | [
"Regular",
"expression",
"matching",
"."
] | 48818336f2e9a126f1964f2d8dc22d37ff800fe8 | https://github.com/buguroo/pyknow/blob/48818336f2e9a126f1964f2d8dc22d37ff800fe8/pyknow/operator.py#L127-L129 |
227,388 | buguroo/pyknow | pyknow/operator.py | ILIKE | def ILIKE(pattern):
"""Unix shell-style wildcards. Case-insensitive"""
return P(lambda x: fnmatch.fnmatch(x.lower(), pattern.lower())) | python | def ILIKE(pattern):
return P(lambda x: fnmatch.fnmatch(x.lower(), pattern.lower())) | [
"def",
"ILIKE",
"(",
"pattern",
")",
":",
"return",
"P",
"(",
"lambda",
"x",
":",
"fnmatch",
".",
"fnmatch",
"(",
"x",
".",
"lower",
"(",
")",
",",
"pattern",
".",
"lower",
"(",
")",
")",
")"
] | Unix shell-style wildcards. Case-insensitive | [
"Unix",
"shell",
"-",
"style",
"wildcards",
".",
"Case",
"-",
"insensitive"
] | 48818336f2e9a126f1964f2d8dc22d37ff800fe8 | https://github.com/buguroo/pyknow/blob/48818336f2e9a126f1964f2d8dc22d37ff800fe8/pyknow/operator.py#L137-L139 |
227,389 | buguroo/pyknow | pyknow/watchers.py | worth | def worth(what, level_name):
"""Returns `True` if the watcher `what` would log under `level_name`."""
return (logging.NOTSET
< globals()[what].level
<= getattr(logging, level_name)) | python | def worth(what, level_name):
return (logging.NOTSET
< globals()[what].level
<= getattr(logging, level_name)) | [
"def",
"worth",
"(",
"what",
",",
"level_name",
")",
":",
"return",
"(",
"logging",
".",
"NOTSET",
"<",
"globals",
"(",
")",
"[",
"what",
"]",
".",
"level",
"<=",
"getattr",
"(",
"logging",
",",
"level_name",
")",
")"
] | Returns `True` if the watcher `what` would log under `level_name`. | [
"Returns",
"True",
"if",
"the",
"watcher",
"what",
"would",
"log",
"under",
"level_name",
"."
] | 48818336f2e9a126f1964f2d8dc22d37ff800fe8 | https://github.com/buguroo/pyknow/blob/48818336f2e9a126f1964f2d8dc22d37ff800fe8/pyknow/watchers.py#L22-L26 |
227,390 | buguroo/pyknow | pyknow/watchers.py | watch | def watch(*what, level=logging.DEBUG):
"""
Enable watchers.
Defaults to enable all watchers, accepts a list names of watchers to
enable.
"""
if not what:
what = ALL
for watcher_name in what:
watcher = globals()[watcher_name]
watcher.setLevel(level) | python | def watch(*what, level=logging.DEBUG):
if not what:
what = ALL
for watcher_name in what:
watcher = globals()[watcher_name]
watcher.setLevel(level) | [
"def",
"watch",
"(",
"*",
"what",
",",
"level",
"=",
"logging",
".",
"DEBUG",
")",
":",
"if",
"not",
"what",
":",
"what",
"=",
"ALL",
"for",
"watcher_name",
"in",
"what",
":",
"watcher",
"=",
"globals",
"(",
")",
"[",
"watcher_name",
"]",
"watcher",
... | Enable watchers.
Defaults to enable all watchers, accepts a list names of watchers to
enable. | [
"Enable",
"watchers",
"."
] | 48818336f2e9a126f1964f2d8dc22d37ff800fe8 | https://github.com/buguroo/pyknow/blob/48818336f2e9a126f1964f2d8dc22d37ff800fe8/pyknow/watchers.py#L29-L42 |
227,391 | buguroo/pyknow | pyknow/matchers/rete/utils.py | extract_facts | def extract_facts(rule):
"""Given a rule, return a set containing all rule LHS facts."""
def _extract_facts(ce):
if isinstance(ce, Fact):
yield ce
elif isinstance(ce, TEST):
pass
else:
for e in ce:
yield from _extract_facts(e)
return set(_extract_facts(rule)) | python | def extract_facts(rule):
def _extract_facts(ce):
if isinstance(ce, Fact):
yield ce
elif isinstance(ce, TEST):
pass
else:
for e in ce:
yield from _extract_facts(e)
return set(_extract_facts(rule)) | [
"def",
"extract_facts",
"(",
"rule",
")",
":",
"def",
"_extract_facts",
"(",
"ce",
")",
":",
"if",
"isinstance",
"(",
"ce",
",",
"Fact",
")",
":",
"yield",
"ce",
"elif",
"isinstance",
"(",
"ce",
",",
"TEST",
")",
":",
"pass",
"else",
":",
"for",
"e... | Given a rule, return a set containing all rule LHS facts. | [
"Given",
"a",
"rule",
"return",
"a",
"set",
"containing",
"all",
"rule",
"LHS",
"facts",
"."
] | 48818336f2e9a126f1964f2d8dc22d37ff800fe8 | https://github.com/buguroo/pyknow/blob/48818336f2e9a126f1964f2d8dc22d37ff800fe8/pyknow/matchers/rete/utils.py#L69-L80 |
227,392 | buguroo/pyknow | pyknow/matchers/rete/utils.py | generate_checks | def generate_checks(fact):
"""Given a fact, generate a list of Check objects for checking it."""
yield TypeCheck(type(fact))
fact_captured = False
for key, value in fact.items():
if (isinstance(key, str)
and key.startswith('__')
and key.endswith('__')):
# Special fact feature
if key == '__bind__':
yield FactCapture(value)
fact_captured = True
else: # pragma: no cover
yield FeatureCheck(key, value)
else:
yield FeatureCheck(key, value)
# Assign the matching fact to the context
if not fact_captured:
yield FactCapture("__pattern_%s__" % id(fact)) | python | def generate_checks(fact):
yield TypeCheck(type(fact))
fact_captured = False
for key, value in fact.items():
if (isinstance(key, str)
and key.startswith('__')
and key.endswith('__')):
# Special fact feature
if key == '__bind__':
yield FactCapture(value)
fact_captured = True
else: # pragma: no cover
yield FeatureCheck(key, value)
else:
yield FeatureCheck(key, value)
# Assign the matching fact to the context
if not fact_captured:
yield FactCapture("__pattern_%s__" % id(fact)) | [
"def",
"generate_checks",
"(",
"fact",
")",
":",
"yield",
"TypeCheck",
"(",
"type",
"(",
"fact",
")",
")",
"fact_captured",
"=",
"False",
"for",
"key",
",",
"value",
"in",
"fact",
".",
"items",
"(",
")",
":",
"if",
"(",
"isinstance",
"(",
"key",
",",... | Given a fact, generate a list of Check objects for checking it. | [
"Given",
"a",
"fact",
"generate",
"a",
"list",
"of",
"Check",
"objects",
"for",
"checking",
"it",
"."
] | 48818336f2e9a126f1964f2d8dc22d37ff800fe8 | https://github.com/buguroo/pyknow/blob/48818336f2e9a126f1964f2d8dc22d37ff800fe8/pyknow/matchers/rete/utils.py#L83-L104 |
227,393 | buguroo/pyknow | pyknow/matchers/rete/nodes.py | BusNode.add | def add(self, fact):
"""Create a VALID token and send it to all children."""
token = Token.valid(fact)
MATCHER.debug("<BusNode> added %r", token)
for child in self.children:
child.callback(token) | python | def add(self, fact):
token = Token.valid(fact)
MATCHER.debug("<BusNode> added %r", token)
for child in self.children:
child.callback(token) | [
"def",
"add",
"(",
"self",
",",
"fact",
")",
":",
"token",
"=",
"Token",
".",
"valid",
"(",
"fact",
")",
"MATCHER",
".",
"debug",
"(",
"\"<BusNode> added %r\"",
",",
"token",
")",
"for",
"child",
"in",
"self",
".",
"children",
":",
"child",
".",
"cal... | Create a VALID token and send it to all children. | [
"Create",
"a",
"VALID",
"token",
"and",
"send",
"it",
"to",
"all",
"children",
"."
] | 48818336f2e9a126f1964f2d8dc22d37ff800fe8 | https://github.com/buguroo/pyknow/blob/48818336f2e9a126f1964f2d8dc22d37ff800fe8/pyknow/matchers/rete/nodes.py#L36-L41 |
227,394 | buguroo/pyknow | pyknow/matchers/rete/nodes.py | BusNode.remove | def remove(self, fact):
"""Create an INVALID token and send it to all children."""
token = Token.invalid(fact)
MATCHER.debug("<BusNode> added %r", token)
for child in self.children:
child.callback(token) | python | def remove(self, fact):
token = Token.invalid(fact)
MATCHER.debug("<BusNode> added %r", token)
for child in self.children:
child.callback(token) | [
"def",
"remove",
"(",
"self",
",",
"fact",
")",
":",
"token",
"=",
"Token",
".",
"invalid",
"(",
"fact",
")",
"MATCHER",
".",
"debug",
"(",
"\"<BusNode> added %r\"",
",",
"token",
")",
"for",
"child",
"in",
"self",
".",
"children",
":",
"child",
".",
... | Create an INVALID token and send it to all children. | [
"Create",
"an",
"INVALID",
"token",
"and",
"send",
"it",
"to",
"all",
"children",
"."
] | 48818336f2e9a126f1964f2d8dc22d37ff800fe8 | https://github.com/buguroo/pyknow/blob/48818336f2e9a126f1964f2d8dc22d37ff800fe8/pyknow/matchers/rete/nodes.py#L43-L48 |
227,395 | buguroo/pyknow | pyknow/matchers/rete/nodes.py | OrdinaryMatchNode.__activation | def __activation(self, token, branch_memory, matching_memory,
is_left=True):
"""
Node activation internal function.
This is a generalization of both activation functions.
The given token is added or removed from `branch_memory`
depending of its tag.
For any other data in `matching_memory` the match function will
be called and if a match occurs a new token will be produced and
sent to all children.
"""
if token.is_valid():
branch_memory.append(token.to_info())
else:
with suppress(ValueError):
branch_memory.remove(token.to_info())
for other_data, other_context in matching_memory:
other_context = dict(other_context)
if is_left:
left_context = token.context
right_context = other_context
else:
left_context = other_context
right_context = token.context
match = self.matcher(left_context, right_context)
if match:
MATCH.info("%s (%s | %s) = True",
self.__class__.__name__,
left_context,
right_context)
newcontext = {k: v for k, v in token.context.items()
if isinstance(k, str)}
for k, v in other_context.items():
if not isinstance(k, tuple):
# Negated value are not needed any further
newcontext[k] = v
newtoken = Token(token.tag,
token.data | other_data,
newcontext)
for child in self.children:
child.callback(newtoken)
else:
MATCH.debug("%s (%s | %s) = False",
self.__class__.__name__,
left_context,
right_context) | python | def __activation(self, token, branch_memory, matching_memory,
is_left=True):
if token.is_valid():
branch_memory.append(token.to_info())
else:
with suppress(ValueError):
branch_memory.remove(token.to_info())
for other_data, other_context in matching_memory:
other_context = dict(other_context)
if is_left:
left_context = token.context
right_context = other_context
else:
left_context = other_context
right_context = token.context
match = self.matcher(left_context, right_context)
if match:
MATCH.info("%s (%s | %s) = True",
self.__class__.__name__,
left_context,
right_context)
newcontext = {k: v for k, v in token.context.items()
if isinstance(k, str)}
for k, v in other_context.items():
if not isinstance(k, tuple):
# Negated value are not needed any further
newcontext[k] = v
newtoken = Token(token.tag,
token.data | other_data,
newcontext)
for child in self.children:
child.callback(newtoken)
else:
MATCH.debug("%s (%s | %s) = False",
self.__class__.__name__,
left_context,
right_context) | [
"def",
"__activation",
"(",
"self",
",",
"token",
",",
"branch_memory",
",",
"matching_memory",
",",
"is_left",
"=",
"True",
")",
":",
"if",
"token",
".",
"is_valid",
"(",
")",
":",
"branch_memory",
".",
"append",
"(",
"token",
".",
"to_info",
"(",
")",
... | Node activation internal function.
This is a generalization of both activation functions.
The given token is added or removed from `branch_memory`
depending of its tag.
For any other data in `matching_memory` the match function will
be called and if a match occurs a new token will be produced and
sent to all children. | [
"Node",
"activation",
"internal",
"function",
"."
] | 48818336f2e9a126f1964f2d8dc22d37ff800fe8 | https://github.com/buguroo/pyknow/blob/48818336f2e9a126f1964f2d8dc22d37ff800fe8/pyknow/matchers/rete/nodes.py#L160-L216 |
227,396 | buguroo/pyknow | pyknow/matchers/rete/nodes.py | OrdinaryMatchNode._activate_left | def _activate_left(self, token):
"""Node left activation."""
self.__activation(token,
self.left_memory,
self.right_memory,
is_left=True) | python | def _activate_left(self, token):
self.__activation(token,
self.left_memory,
self.right_memory,
is_left=True) | [
"def",
"_activate_left",
"(",
"self",
",",
"token",
")",
":",
"self",
".",
"__activation",
"(",
"token",
",",
"self",
".",
"left_memory",
",",
"self",
".",
"right_memory",
",",
"is_left",
"=",
"True",
")"
] | Node left activation. | [
"Node",
"left",
"activation",
"."
] | 48818336f2e9a126f1964f2d8dc22d37ff800fe8 | https://github.com/buguroo/pyknow/blob/48818336f2e9a126f1964f2d8dc22d37ff800fe8/pyknow/matchers/rete/nodes.py#L218-L223 |
227,397 | buguroo/pyknow | pyknow/matchers/rete/nodes.py | OrdinaryMatchNode._activate_right | def _activate_right(self, token):
"""Node right activation."""
self.__activation(token,
self.right_memory,
self.left_memory,
is_left=False) | python | def _activate_right(self, token):
self.__activation(token,
self.right_memory,
self.left_memory,
is_left=False) | [
"def",
"_activate_right",
"(",
"self",
",",
"token",
")",
":",
"self",
".",
"__activation",
"(",
"token",
",",
"self",
".",
"right_memory",
",",
"self",
".",
"left_memory",
",",
"is_left",
"=",
"False",
")"
] | Node right activation. | [
"Node",
"right",
"activation",
"."
] | 48818336f2e9a126f1964f2d8dc22d37ff800fe8 | https://github.com/buguroo/pyknow/blob/48818336f2e9a126f1964f2d8dc22d37ff800fe8/pyknow/matchers/rete/nodes.py#L225-L230 |
227,398 | buguroo/pyknow | pyknow/matchers/rete/nodes.py | ConflictSetNode._activate | def _activate(self, token):
"""Activate this node for the given token."""
info = token.to_info()
activation = Activation(
self.rule,
frozenset(info.data),
{k: v for k, v in info.context if isinstance(k, str)})
if token.is_valid():
if info not in self.memory:
self.memory.add(info)
if activation in self.removed:
self.removed.remove(activation)
else:
self.added.add(activation)
else:
try:
self.memory.remove(info)
except ValueError:
pass
else:
if activation in self.added:
self.added.remove(activation)
else:
self.removed.add(activation) | python | def _activate(self, token):
info = token.to_info()
activation = Activation(
self.rule,
frozenset(info.data),
{k: v for k, v in info.context if isinstance(k, str)})
if token.is_valid():
if info not in self.memory:
self.memory.add(info)
if activation in self.removed:
self.removed.remove(activation)
else:
self.added.add(activation)
else:
try:
self.memory.remove(info)
except ValueError:
pass
else:
if activation in self.added:
self.added.remove(activation)
else:
self.removed.add(activation) | [
"def",
"_activate",
"(",
"self",
",",
"token",
")",
":",
"info",
"=",
"token",
".",
"to_info",
"(",
")",
"activation",
"=",
"Activation",
"(",
"self",
".",
"rule",
",",
"frozenset",
"(",
"info",
".",
"data",
")",
",",
"{",
"k",
":",
"v",
"for",
"... | Activate this node for the given token. | [
"Activate",
"this",
"node",
"for",
"the",
"given",
"token",
"."
] | 48818336f2e9a126f1964f2d8dc22d37ff800fe8 | https://github.com/buguroo/pyknow/blob/48818336f2e9a126f1964f2d8dc22d37ff800fe8/pyknow/matchers/rete/nodes.py#L262-L288 |
227,399 | buguroo/pyknow | pyknow/matchers/rete/nodes.py | ConflictSetNode.get_activations | def get_activations(self):
"""Return a list of activations."""
res = (self.added, self.removed)
self.added = set()
self.removed = set()
return res | python | def get_activations(self):
res = (self.added, self.removed)
self.added = set()
self.removed = set()
return res | [
"def",
"get_activations",
"(",
"self",
")",
":",
"res",
"=",
"(",
"self",
".",
"added",
",",
"self",
".",
"removed",
")",
"self",
".",
"added",
"=",
"set",
"(",
")",
"self",
".",
"removed",
"=",
"set",
"(",
")",
"return",
"res"
] | Return a list of activations. | [
"Return",
"a",
"list",
"of",
"activations",
"."
] | 48818336f2e9a126f1964f2d8dc22d37ff800fe8 | https://github.com/buguroo/pyknow/blob/48818336f2e9a126f1964f2d8dc22d37ff800fe8/pyknow/matchers/rete/nodes.py#L290-L297 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.