Development of an internal social media platform with personalised dashboards for students
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

objects.py 7.9KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220
  1. # Copyright (c) 2015-2016 Cara Vinson <ceridwenv@gmail.com>
  2. # Copyright (c) 2015-2016 Claudiu Popa <pcmanticore@gmail.com>
  3. # Licensed under the LGPL: https://www.gnu.org/licenses/old-licenses/lgpl-2.1.en.html
  4. # For details: https://github.com/PyCQA/astroid/blob/master/COPYING.LESSER
  5. """
  6. Inference objects are a way to represent composite AST nodes,
  7. which are used only as inference results, so they can't be found in the
  8. original AST tree. For instance, inferring the following frozenset use,
  9. leads to an inferred FrozenSet:
  10. Call(func=Name('frozenset'), args=Tuple(...))
  11. """
  12. import six
  13. from astroid import bases
  14. from astroid import decorators
  15. from astroid import exceptions
  16. from astroid import MANAGER
  17. from astroid import node_classes
  18. from astroid import scoped_nodes
  19. from astroid import util
  20. BUILTINS = six.moves.builtins.__name__
  21. objectmodel = util.lazy_import('interpreter.objectmodel')
  22. class FrozenSet(node_classes._BaseContainer):
  23. """class representing a FrozenSet composite node"""
  24. def pytype(self):
  25. return '%s.frozenset' % BUILTINS
  26. def _infer(self, context=None):
  27. yield self
  28. @decorators.cachedproperty
  29. def _proxied(self): # pylint: disable=method-hidden
  30. builtins = MANAGER.astroid_cache[BUILTINS]
  31. return builtins.getattr('frozenset')[0]
  32. class Super(node_classes.NodeNG):
  33. """Proxy class over a super call.
  34. This class offers almost the same behaviour as Python's super,
  35. which is MRO lookups for retrieving attributes from the parents.
  36. The *mro_pointer* is the place in the MRO from where we should
  37. start looking, not counting it. *mro_type* is the object which
  38. provides the MRO, it can be both a type or an instance.
  39. *self_class* is the class where the super call is, while
  40. *scope* is the function where the super call is.
  41. """
  42. # pylint: disable=unnecessary-lambda
  43. special_attributes = util.lazy_descriptor(lambda: objectmodel.SuperModel())
  44. # pylint: disable=super-init-not-called
  45. def __init__(self, mro_pointer, mro_type, self_class, scope):
  46. self.type = mro_type
  47. self.mro_pointer = mro_pointer
  48. self._class_based = False
  49. self._self_class = self_class
  50. self._scope = scope
  51. def _infer(self, context=None):
  52. yield self
  53. def super_mro(self):
  54. """Get the MRO which will be used to lookup attributes in this super."""
  55. if not isinstance(self.mro_pointer, scoped_nodes.ClassDef):
  56. raise exceptions.SuperError(
  57. "The first argument to super must be a subtype of "
  58. "type, not {mro_pointer}.", super_=self)
  59. if isinstance(self.type, scoped_nodes.ClassDef):
  60. # `super(type, type)`, most likely in a class method.
  61. self._class_based = True
  62. mro_type = self.type
  63. else:
  64. mro_type = getattr(self.type, '_proxied', None)
  65. if not isinstance(mro_type, (bases.Instance, scoped_nodes.ClassDef)):
  66. raise exceptions.SuperError(
  67. "The second argument to super must be an "
  68. "instance or subtype of type, not {type}.",
  69. super_=self)
  70. if not mro_type.newstyle:
  71. raise exceptions.SuperError("Unable to call super on old-style classes.", super_=self)
  72. mro = mro_type.mro()
  73. if self.mro_pointer not in mro:
  74. raise exceptions.SuperError(
  75. "The second argument to super must be an "
  76. "instance or subtype of type, not {type}.",
  77. super_=self)
  78. index = mro.index(self.mro_pointer)
  79. return mro[index + 1:]
  80. @decorators.cachedproperty
  81. def _proxied(self):
  82. builtins = MANAGER.astroid_cache[BUILTINS]
  83. return builtins.getattr('super')[0]
  84. def pytype(self):
  85. return '%s.super' % BUILTINS
  86. def display_type(self):
  87. return 'Super of'
  88. @property
  89. def name(self):
  90. """Get the name of the MRO pointer."""
  91. return self.mro_pointer.name
  92. def igetattr(self, name, context=None):
  93. """Retrieve the inferred values of the given attribute name."""
  94. if name in self.special_attributes:
  95. yield self.special_attributes.lookup(name)
  96. return
  97. try:
  98. mro = self.super_mro()
  99. # Don't let invalid MROs or invalid super calls
  100. # leak out as is from this function.
  101. except exceptions.SuperError as exc:
  102. util.reraise(exceptions.AttributeInferenceError(
  103. ('Lookup for {name} on {target!r} because super call {super!r} '
  104. 'is invalid.'),
  105. target=self, attribute=name, context=context, super_=exc.super_))
  106. except exceptions.MroError as exc:
  107. util.reraise(exceptions.AttributeInferenceError(
  108. ('Lookup for {name} on {target!r} failed because {cls!r} has an '
  109. 'invalid MRO.'),
  110. target=self, attribute=name, context=context, mros=exc.mros,
  111. cls=exc.cls))
  112. found = False
  113. for cls in mro:
  114. if name not in cls.locals:
  115. continue
  116. found = True
  117. for inferred in bases._infer_stmts([cls[name]], context, frame=self):
  118. if not isinstance(inferred, scoped_nodes.FunctionDef):
  119. yield inferred
  120. continue
  121. # We can obtain different descriptors from a super depending
  122. # on what we are accessing and where the super call is.
  123. if inferred.type == 'classmethod':
  124. yield bases.BoundMethod(inferred, cls)
  125. elif self._scope.type == 'classmethod' and inferred.type == 'method':
  126. yield inferred
  127. elif self._class_based or inferred.type == 'staticmethod':
  128. yield inferred
  129. elif bases._is_property(inferred):
  130. # TODO: support other descriptors as well.
  131. for value in inferred.infer_call_result(self, context):
  132. yield value
  133. else:
  134. yield bases.BoundMethod(inferred, cls)
  135. if not found:
  136. raise exceptions.AttributeInferenceError(target=self,
  137. attribute=name,
  138. context=context)
  139. def getattr(self, name, context=None):
  140. return list(self.igetattr(name, context=context))
  141. class ExceptionInstance(bases.Instance):
  142. """Class for instances of exceptions
  143. It has special treatment for some of the exceptions's attributes,
  144. which are transformed at runtime into certain concrete objects, such as
  145. the case of .args.
  146. """
  147. # pylint: disable=unnecessary-lambda
  148. special_attributes = util.lazy_descriptor(lambda: objectmodel.ExceptionInstanceModel())
  149. class DictInstance(bases.Instance):
  150. """Special kind of instances for dictionaries
  151. This instance knows the underlying object model of the dictionaries, which means
  152. that methods such as .values or .items can be properly inferred.
  153. """
  154. # pylint: disable=unnecessary-lambda
  155. special_attributes = util.lazy_descriptor(lambda: objectmodel.DictModel())
  156. # Custom objects tailored for dictionaries, which are used to
  157. # disambiguate between the types of Python 2 dict's method returns
  158. # and Python 3 (where they return set like objects).
  159. class DictItems(bases.Proxy):
  160. __str__ = node_classes.NodeNG.__str__
  161. __repr__ = node_classes.NodeNG.__repr__
  162. class DictKeys(bases.Proxy):
  163. __str__ = node_classes.NodeNG.__str__
  164. __repr__ = node_classes.NodeNG.__repr__
  165. class DictValues(bases.Proxy):
  166. __str__ = node_classes.NodeNG.__str__
  167. __repr__ = node_classes.NodeNG.__repr__
  168. # TODO: Hack to solve the circular import problem between node_classes and objects
  169. # This is not needed in 2.0, which has a cleaner design overall
  170. node_classes.Dict.__bases__ = (node_classes.NodeNG, DictInstance)