PageRenderTime 49ms CodeModel.GetById 18ms RepoModel.GetById 0ms app.codeStats 0ms

/pypy/module/__builtin__/interp_classobj.py

https://bitbucket.org/dac_io/pypy
Python | 793 lines | 678 code | 80 blank | 35 comment | 181 complexity | 34411905fc6b2296910931bbb78473a5 MD5 | raw file
  1. import new
  2. from pypy.interpreter.error import OperationError, operationerrfmt
  3. from pypy.interpreter.gateway import interp2app
  4. from pypy.interpreter.typedef import TypeDef, make_weakref_descr
  5. from pypy.interpreter.baseobjspace import Wrappable
  6. from pypy.interpreter.typedef import GetSetProperty, descr_get_dict, descr_set_dict
  7. from pypy.rlib.objectmodel import compute_identity_hash
  8. from pypy.rlib.debug import make_sure_not_resized
  9. from pypy.rlib import jit
  10. def raise_type_err(space, argument, expected, w_obj):
  11. type_name = space.type(w_obj).getname(space)
  12. raise operationerrfmt(space.w_TypeError,
  13. "argument %s must be %s, not %s",
  14. argument, expected, type_name)
  15. def unwrap_attr(space, w_attr):
  16. try:
  17. return space.str_w(w_attr)
  18. except OperationError, e:
  19. if not e.match(space, space.w_TypeError):
  20. raise
  21. return "?" # any string different from "__dict__" & co. is fine
  22. # XXX it's not clear that we have to catch the TypeError...
  23. def descr_classobj_new(space, w_subtype, w_name, w_bases, w_dict):
  24. if not space.is_true(space.isinstance(w_bases, space.w_tuple)):
  25. raise_type_err(space, 'bases', 'tuple', w_bases)
  26. if not space.is_true(space.isinstance(w_dict, space.w_dict)):
  27. raise_type_err(space, 'bases', 'tuple', w_bases)
  28. if not space.is_true(space.contains(w_dict, space.wrap("__doc__"))):
  29. space.setitem(w_dict, space.wrap("__doc__"), space.w_None)
  30. # XXX missing: lengthy and obscure logic about "__module__"
  31. bases_w = space.fixedview(w_bases)
  32. for w_base in bases_w:
  33. if not isinstance(w_base, W_ClassObject):
  34. w_metaclass = space.type(w_base)
  35. if space.is_true(space.callable(w_metaclass)):
  36. return space.call_function(w_metaclass, w_name,
  37. w_bases, w_dict)
  38. raise OperationError(space.w_TypeError,
  39. space.wrap("base must be class"))
  40. return W_ClassObject(space, w_name, bases_w, w_dict)
  41. class W_ClassObject(Wrappable):
  42. def __init__(self, space, w_name, bases, w_dict):
  43. self.name = space.str_w(w_name)
  44. make_sure_not_resized(bases)
  45. self.bases_w = bases
  46. self.w_dict = w_dict
  47. def instantiate(self, space):
  48. cache = space.fromcache(Cache)
  49. if self.lookup(space, '__del__') is not None:
  50. w_inst = cache.cls_with_del(space, self)
  51. else:
  52. w_inst = cache.cls_without_del(space, self)
  53. return w_inst
  54. def getdict(self, space):
  55. return self.w_dict
  56. def setdict(self, space, w_dict):
  57. if not space.is_true(space.isinstance(w_dict, space.w_dict)):
  58. raise OperationError(
  59. space.w_TypeError,
  60. space.wrap("__dict__ must be a dictionary object"))
  61. self.w_dict = w_dict
  62. def setname(self, space, w_newname):
  63. if not space.is_true(space.isinstance(w_newname, space.w_str)):
  64. raise OperationError(
  65. space.w_TypeError,
  66. space.wrap("__name__ must be a string object"))
  67. self.name = space.str_w(w_newname)
  68. def setbases(self, space, w_bases):
  69. # XXX in theory, this misses a check against inheritance cycles
  70. # although on pypy we don't get a segfault for infinite
  71. # recursion anyway
  72. if not space.is_true(space.isinstance(w_bases, space.w_tuple)):
  73. raise OperationError(
  74. space.w_TypeError,
  75. space.wrap("__bases__ must be a tuple object"))
  76. bases_w = space.fixedview(w_bases)
  77. for w_base in bases_w:
  78. if not isinstance(w_base, W_ClassObject):
  79. raise OperationError(space.w_TypeError,
  80. space.wrap("__bases__ items must be classes"))
  81. self.bases_w = bases_w
  82. def is_subclass_of(self, other):
  83. assert isinstance(other, W_ClassObject)
  84. if self is other:
  85. return True
  86. for base in self.bases_w:
  87. assert isinstance(base, W_ClassObject)
  88. if base.is_subclass_of(other):
  89. return True
  90. return False
  91. @jit.unroll_safe
  92. def lookup(self, space, attr):
  93. # returns w_value or interplevel None
  94. w_result = space.finditem_str(self.w_dict, attr)
  95. if w_result is not None:
  96. return w_result
  97. for base in self.bases_w:
  98. # XXX fix annotation of bases_w to be a list of W_ClassObjects
  99. assert isinstance(base, W_ClassObject)
  100. w_result = base.lookup(space, attr)
  101. if w_result is not None:
  102. return w_result
  103. return None
  104. def descr_getattribute(self, space, w_attr):
  105. name = unwrap_attr(space, w_attr)
  106. if name and name[0] == "_":
  107. if name == "__dict__":
  108. return self.w_dict
  109. elif name == "__name__":
  110. return space.wrap(self.name)
  111. elif name == "__bases__":
  112. return space.newtuple(self.bases_w)
  113. w_value = self.lookup(space, name)
  114. if w_value is None:
  115. raise operationerrfmt(
  116. space.w_AttributeError,
  117. "class %s has no attribute '%s'",
  118. self.name, name)
  119. w_descr_get = space.lookup(w_value, '__get__')
  120. if w_descr_get is None:
  121. return w_value
  122. return space.call_function(w_descr_get, w_value, space.w_None, self)
  123. def descr_setattr(self, space, w_attr, w_value):
  124. name = unwrap_attr(space, w_attr)
  125. if name and name[0] == "_":
  126. if name == "__dict__":
  127. self.setdict(space, w_value)
  128. return
  129. elif name == "__name__":
  130. self.setname(space, w_value)
  131. return
  132. elif name == "__bases__":
  133. self.setbases(space, w_value)
  134. return
  135. elif name == "__del__":
  136. if self.lookup(space, name) is None:
  137. msg = ("a __del__ method added to an existing class "
  138. "will not be called")
  139. space.warn(msg, space.w_RuntimeWarning)
  140. space.setitem(self.w_dict, w_attr, w_value)
  141. def descr_delattr(self, space, w_attr):
  142. name = unwrap_attr(space, w_attr)
  143. if name in ("__dict__", "__name__", "__bases__"):
  144. raise operationerrfmt(
  145. space.w_TypeError,
  146. "cannot delete attribute '%s'", name)
  147. try:
  148. space.delitem(self.w_dict, w_attr)
  149. except OperationError, e:
  150. if not e.match(space, space.w_KeyError):
  151. raise
  152. raise operationerrfmt(
  153. space.w_AttributeError,
  154. "class %s has no attribute '%s'",
  155. self.name, name)
  156. def descr_repr(self, space):
  157. mod = self.get_module_string(space)
  158. return self.getrepr(space, "class %s.%s" % (mod, self.name))
  159. def descr_str(self, space):
  160. mod = self.get_module_string(space)
  161. if mod == "?":
  162. return space.wrap(self.name)
  163. else:
  164. return space.wrap("%s.%s" % (mod, self.name))
  165. def get_module_string(self, space):
  166. try:
  167. w_mod = self.descr_getattribute(space, space.wrap("__module__"))
  168. except OperationError, e:
  169. if not e.match(space, space.w_AttributeError):
  170. raise
  171. return "?"
  172. if space.is_true(space.isinstance(w_mod, space.w_str)):
  173. return space.str_w(w_mod)
  174. return "?"
  175. def __repr__(self):
  176. # NOT_RPYTHON
  177. return '<W_ClassObject(%s)>' % self.name
  178. class Cache:
  179. def __init__(self, space):
  180. from pypy.interpreter.typedef import _usersubclswithfeature
  181. # evil
  182. self.cls_without_del = _usersubclswithfeature(
  183. space.config, W_InstanceObject, "dict", "weakref")
  184. self.cls_with_del = _usersubclswithfeature(
  185. space.config, self.cls_without_del, "del")
  186. def class_descr_call(space, w_self, __args__):
  187. self = space.interp_w(W_ClassObject, w_self)
  188. w_inst = self.instantiate(space)
  189. w_init = w_inst.getattr_from_class(space, '__init__')
  190. if w_init is not None:
  191. w_result = space.call_args(w_init, __args__)
  192. if not space.is_w(w_result, space.w_None):
  193. raise OperationError(
  194. space.w_TypeError,
  195. space.wrap("__init__() should return None"))
  196. elif __args__.arguments_w or __args__.keywords:
  197. raise OperationError(
  198. space.w_TypeError,
  199. space.wrap("this constructor takes no arguments"))
  200. return w_inst
  201. W_ClassObject.typedef = TypeDef("classobj",
  202. __new__ = interp2app(descr_classobj_new),
  203. __repr__ = interp2app(W_ClassObject.descr_repr),
  204. __str__ = interp2app(W_ClassObject.descr_str),
  205. __call__ = interp2app(class_descr_call),
  206. __getattribute__ = interp2app(W_ClassObject.descr_getattribute),
  207. __setattr__ = interp2app(W_ClassObject.descr_setattr),
  208. __delattr__ = interp2app(W_ClassObject.descr_delattr),
  209. __weakref__ = make_weakref_descr(W_ClassObject),
  210. )
  211. W_ClassObject.typedef.acceptable_as_base_class = False
  212. def make_unary_instance_method(name):
  213. def unaryop(self, space):
  214. w_meth = self.getattr(space, name, True)
  215. return space.call_function(w_meth)
  216. unaryop.func_name = name
  217. return unaryop
  218. def make_binary_returning_notimplemented_instance_method(name):
  219. def binaryop(self, space, w_other):
  220. try:
  221. w_meth = self.getattr(space, name, False)
  222. except OperationError, e:
  223. if e.match(space, space.w_AttributeError):
  224. return space.w_NotImplemented
  225. raise
  226. else:
  227. if w_meth is None:
  228. return space.w_NotImplemented
  229. return space.call_function(w_meth, w_other)
  230. binaryop.func_name = name
  231. return binaryop
  232. def make_binary_instance_method(name):
  233. specialname = "__%s__" % (name, )
  234. rspecialname = "__r%s__" % (name, )
  235. objspacename = name
  236. if name in ['and', 'or']:
  237. objspacename = name + '_'
  238. def binaryop(self, space, w_other):
  239. w_a, w_b = _coerce_helper(space, self, w_other)
  240. if w_a is None:
  241. w_a = self
  242. w_b = w_other
  243. if w_a is self:
  244. w_meth = self.getattr(space, specialname, False)
  245. if w_meth is None:
  246. return space.w_NotImplemented
  247. return space.call_function(w_meth, w_b)
  248. else:
  249. return getattr(space, objspacename)(w_a, w_b)
  250. binaryop.func_name = name
  251. def rbinaryop(self, space, w_other):
  252. w_a, w_b = _coerce_helper(space, self, w_other)
  253. if w_a is None or w_a is self:
  254. w_meth = self.getattr(space, rspecialname, False)
  255. if w_meth is None:
  256. return space.w_NotImplemented
  257. return space.call_function(w_meth, w_other)
  258. else:
  259. return getattr(space, objspacename)(w_b, w_a)
  260. rbinaryop.func_name = "r" + name
  261. return binaryop, rbinaryop
  262. def _coerce_helper(space, w_self, w_other):
  263. try:
  264. w_tup = space.coerce(w_self, w_other)
  265. except OperationError, e:
  266. if not e.match(space, space.w_TypeError):
  267. raise
  268. return [None, None]
  269. return space.fixedview(w_tup, 2)
  270. def descr_instance_new(space, w_type, w_class, w_dict=None):
  271. # w_type is not used at all
  272. if not isinstance(w_class, W_ClassObject):
  273. raise OperationError(
  274. space.w_TypeError,
  275. space.wrap("instance() first arg must be class"))
  276. w_result = w_class.instantiate(space)
  277. if not space.is_w(w_dict, space.w_None):
  278. w_result.setdict(space, w_dict)
  279. return w_result
  280. class W_InstanceObject(Wrappable):
  281. def __init__(self, space, w_class):
  282. # note that user_setup is overridden by the typedef.py machinery
  283. self.user_setup(space, space.gettypeobject(self.typedef))
  284. assert isinstance(w_class, W_ClassObject)
  285. self.w_class = w_class
  286. def user_setup(self, space, w_subtype):
  287. self.space = space
  288. def set_oldstyle_class(self, space, w_class):
  289. if w_class is None or not isinstance(w_class, W_ClassObject):
  290. raise OperationError(
  291. space.w_TypeError,
  292. space.wrap("__class__ must be set to a class"))
  293. self.w_class = w_class
  294. def getattr_from_class(self, space, name):
  295. # Look up w_name in the class dict, and call its __get__.
  296. # This method ignores the instance dict and the __getattr__.
  297. # Returns None if not found.
  298. assert isinstance(name, str)
  299. w_value = self.w_class.lookup(space, name)
  300. if w_value is None:
  301. return None
  302. w_descr_get = space.lookup(w_value, '__get__')
  303. if w_descr_get is None:
  304. return w_value
  305. return space.call_function(w_descr_get, w_value, self, self.w_class)
  306. def getattr(self, space, name, exc=True):
  307. # Normal getattr rules: look up w_name in the instance dict,
  308. # in the class dict, and then via a call to __getatttr__.
  309. assert isinstance(name, str)
  310. w_result = self.getdictvalue(space, name)
  311. if w_result is not None:
  312. return w_result
  313. w_result = self.getattr_from_class(space, name)
  314. if w_result is not None:
  315. return w_result
  316. w_meth = self.getattr_from_class(space, '__getattr__')
  317. if w_meth is not None:
  318. try:
  319. return space.call_function(w_meth, space.wrap(name))
  320. except OperationError, e:
  321. if not exc and e.match(space, space.w_AttributeError):
  322. return None # eat the AttributeError
  323. raise
  324. # not found at all
  325. if exc:
  326. raise operationerrfmt(
  327. space.w_AttributeError,
  328. "%s instance has no attribute '%s'",
  329. self.w_class.name, name)
  330. else:
  331. return None
  332. def descr_getattribute(self, space, w_attr):
  333. name = space.str_w(w_attr)
  334. if len(name) >= 8 and name[0] == '_':
  335. if name == "__dict__":
  336. return self.getdict(space)
  337. elif name == "__class__":
  338. return self.w_class
  339. return self.getattr(space, name)
  340. def descr_setattr(self, space, w_name, w_value):
  341. name = unwrap_attr(space, w_name)
  342. w_meth = self.getattr_from_class(space, '__setattr__')
  343. if name and name[0] == "_":
  344. if name == '__dict__':
  345. self.setdict(space, w_value)
  346. return
  347. if name == '__class__':
  348. self.set_oldstyle_class(space, w_value)
  349. return
  350. if name == '__del__' and w_meth is None:
  351. cache = space.fromcache(Cache)
  352. if (not isinstance(self, cache.cls_with_del)
  353. and self.getdictvalue(space, '__del__') is None):
  354. msg = ("a __del__ method added to an instance "
  355. "with no __del__ in the class will not be called")
  356. space.warn(msg, space.w_RuntimeWarning)
  357. if w_meth is not None:
  358. space.call_function(w_meth, w_name, w_value)
  359. else:
  360. self.setdictvalue(space, name, w_value)
  361. def descr_delattr(self, space, w_name):
  362. name = unwrap_attr(space, w_name)
  363. if name and name[0] == "_":
  364. if name == '__dict__':
  365. # use setdict to raise the error
  366. self.setdict(space, space.w_None)
  367. return
  368. elif name == '__class__':
  369. # use set_oldstyle_class to raise the error
  370. self.set_oldstyle_class(space, None)
  371. return
  372. w_meth = self.getattr_from_class(space, '__delattr__')
  373. if w_meth is not None:
  374. space.call_function(w_meth, w_name)
  375. else:
  376. if not self.deldictvalue(space, name):
  377. raise operationerrfmt(
  378. space.w_AttributeError,
  379. "%s instance has no attribute '%s'",
  380. self.w_class.name, name)
  381. def descr_repr(self, space):
  382. w_meth = self.getattr(space, '__repr__', False)
  383. if w_meth is None:
  384. w_class = self.w_class
  385. mod = w_class.get_module_string(space)
  386. return self.getrepr(space, "%s.%s instance" % (mod, w_class.name))
  387. return space.call_function(w_meth)
  388. def descr_str(self, space):
  389. w_meth = self.getattr(space, '__str__', False)
  390. if w_meth is None:
  391. return self.descr_repr(space)
  392. return space.call_function(w_meth)
  393. def descr_unicode(self, space):
  394. w_meth = self.getattr(space, '__unicode__', False)
  395. if w_meth is None:
  396. return self.descr_str(space)
  397. return space.call_function(w_meth)
  398. def descr_format(self, space, w_format_spec):
  399. w_meth = self.getattr(space, "__format__", False)
  400. if w_meth is not None:
  401. return space.call_function(w_meth, w_format_spec)
  402. else:
  403. if space.isinstance_w(w_format_spec, space.w_unicode):
  404. w_as_str = self.descr_unicode(space)
  405. else:
  406. w_as_str = self.descr_str(space)
  407. if space.len_w(w_format_spec) > 0:
  408. space.warn(
  409. ("object.__format__ with a non-empty format string is "
  410. "deprecated"),
  411. space.w_PendingDeprecationWarning
  412. )
  413. return space.format(w_as_str, w_format_spec)
  414. def descr_len(self, space):
  415. w_meth = self.getattr(space, '__len__')
  416. w_result = space.call_function(w_meth)
  417. if space.is_true(space.isinstance(w_result, space.w_int)):
  418. if space.is_true(space.lt(w_result, space.wrap(0))):
  419. raise OperationError(
  420. space.w_ValueError,
  421. space.wrap("__len__() should return >= 0"))
  422. return w_result
  423. raise OperationError(
  424. space.w_TypeError,
  425. space.wrap("__len__() should return an int"))
  426. def descr_getitem(self, space, w_key):
  427. w_meth = self.getattr(space, '__getitem__')
  428. return space.call_function(w_meth, w_key)
  429. def descr_setitem(self, space, w_key, w_value):
  430. w_meth = self.getattr(space, '__setitem__')
  431. space.call_function(w_meth, w_key, w_value)
  432. def descr_delitem(self, space, w_key):
  433. w_meth = self.getattr(space, '__delitem__')
  434. space.call_function(w_meth, w_key)
  435. def descr_iter(self, space):
  436. w_meth = self.getattr(space, '__iter__', False)
  437. if w_meth is not None:
  438. return space.call_function(w_meth)
  439. w_meth = self.getattr(space, '__getitem__', False)
  440. if w_meth is None:
  441. raise OperationError(
  442. space.w_TypeError,
  443. space.wrap("iteration over non-sequence"))
  444. return space.newseqiter(self)
  445. #XXX do I really need a next method? the old implementation had one, but I
  446. # don't see the point
  447. def descr_getslice(self, space, w_i, w_j):
  448. w_meth = self.getattr(space, '__getslice__', False)
  449. if w_meth is not None:
  450. return space.call_function(w_meth, w_i, w_j)
  451. else:
  452. return space.getitem(self, space.newslice(w_i, w_j, space.w_None))
  453. def descr_setslice(self, space, w_i, w_j, w_sequence):
  454. w_meth = self.getattr(space, '__setslice__', False)
  455. if w_meth is not None:
  456. space.call_function(w_meth, w_i, w_j, w_sequence)
  457. else:
  458. space.setitem(self, space.newslice(w_i, w_j, space.w_None),
  459. w_sequence)
  460. def descr_delslice(self, space, w_i, w_j):
  461. w_meth = self.getattr(space, '__delslice__', False)
  462. if w_meth is not None:
  463. space.call_function(w_meth, w_i, w_j)
  464. else:
  465. return space.delitem(self, space.newslice(w_i, w_j, space.w_None))
  466. def descr_call(self, space, __args__):
  467. w_meth = self.getattr(space, '__call__')
  468. return space.call_args(w_meth, __args__)
  469. def descr_nonzero(self, space):
  470. w_func = self.getattr(space, '__nonzero__', False)
  471. if w_func is None:
  472. w_func = self.getattr(space, '__len__', False)
  473. if w_func is None:
  474. return space.w_True
  475. w_result = space.call_function(w_func)
  476. if space.is_true(space.isinstance(w_result, space.w_int)):
  477. if space.is_true(space.lt(w_result, space.wrap(0))):
  478. raise OperationError(
  479. space.w_ValueError,
  480. space.wrap("__nonzero__() should return >= 0"))
  481. return w_result
  482. raise OperationError(
  483. space.w_TypeError,
  484. space.wrap("__nonzero__() should return an int"))
  485. def descr_cmp(self, space, w_other): # do all the work here like CPython
  486. w_a, w_b = _coerce_helper(space, self, w_other)
  487. if w_a is None:
  488. w_a = self
  489. w_b = w_other
  490. else:
  491. if (not isinstance(w_a, W_InstanceObject) and
  492. not isinstance(w_b, W_InstanceObject)):
  493. return space.cmp(w_a, w_b)
  494. if isinstance(w_a, W_InstanceObject):
  495. w_func = w_a.getattr(space, '__cmp__', False)
  496. if w_func is not None:
  497. w_res = space.call_function(w_func, w_b)
  498. if space.is_w(w_res, space.w_NotImplemented):
  499. return w_res
  500. try:
  501. res = space.int_w(w_res)
  502. except OperationError, e:
  503. if e.match(space, space.w_TypeError):
  504. raise OperationError(
  505. space.w_TypeError,
  506. space.wrap("__cmp__ must return int"))
  507. raise
  508. if res > 0:
  509. return space.wrap(1)
  510. if res < 0:
  511. return space.wrap(-1)
  512. return space.wrap(0)
  513. if isinstance(w_b, W_InstanceObject):
  514. w_func = w_b.getattr(space, '__cmp__', False)
  515. if w_func is not None:
  516. w_res = space.call_function(w_func, w_a)
  517. if space.is_w(w_res, space.w_NotImplemented):
  518. return w_res
  519. try:
  520. res = space.int_w(w_res)
  521. except OperationError, e:
  522. if e.match(space, space.w_TypeError):
  523. raise OperationError(
  524. space.w_TypeError,
  525. space.wrap("__cmp__ must return int"))
  526. raise
  527. if res < 0:
  528. return space.wrap(1)
  529. if res > 0:
  530. return space.wrap(-1)
  531. return space.wrap(0)
  532. return space.w_NotImplemented
  533. def descr_hash(self, space):
  534. w_func = self.getattr(space, '__hash__', False)
  535. if w_func is None:
  536. w_eq = self.getattr(space, '__eq__', False)
  537. w_cmp = self.getattr(space, '__cmp__', False)
  538. if w_eq is not None or w_cmp is not None:
  539. raise OperationError(space.w_TypeError,
  540. space.wrap("unhashable instance"))
  541. else:
  542. return space.wrap(compute_identity_hash(self))
  543. w_ret = space.call_function(w_func)
  544. if (not space.is_true(space.isinstance(w_ret, space.w_int)) and
  545. not space.is_true(space.isinstance(w_ret, space.w_long))):
  546. raise OperationError(
  547. space.w_TypeError,
  548. space.wrap("__hash__ must return int or long"))
  549. return w_ret
  550. def descr_int(self, space):
  551. w_func = self.getattr(space, '__int__', False)
  552. if w_func is not None:
  553. return space.call_function(w_func)
  554. w_truncated = space.trunc(self)
  555. # int() needs to return an int
  556. try:
  557. return space.int(w_truncated)
  558. except OperationError:
  559. # Raise a different error
  560. raise OperationError(
  561. space.w_TypeError,
  562. space.wrap("__trunc__ returned non-Integral"))
  563. def descr_long(self, space):
  564. w_func = self.getattr(space, '__long__', False)
  565. if w_func is not None:
  566. return space.call_function(w_func)
  567. return self.descr_int(space)
  568. def descr_index(self, space):
  569. w_func = self.getattr(space, '__index__', False)
  570. if w_func is not None:
  571. return space.call_function(w_func)
  572. raise OperationError(
  573. space.w_TypeError,
  574. space.wrap("object cannot be interpreted as an index"))
  575. def descr_contains(self, space, w_obj):
  576. w_func = self.getattr(space, '__contains__', False)
  577. if w_func is not None:
  578. return space.wrap(space.is_true(space.call_function(w_func, w_obj)))
  579. # now do it ourselves
  580. w_iter = space.iter(self)
  581. while 1:
  582. try:
  583. w_x = space.next(w_iter)
  584. except OperationError, e:
  585. if e.match(space, space.w_StopIteration):
  586. return space.w_False
  587. raise
  588. if space.eq_w(w_x, w_obj):
  589. return space.w_True
  590. def descr_pow(self, space, w_other, w_modulo=None):
  591. if space.is_w(w_modulo, space.w_None):
  592. w_a, w_b = _coerce_helper(space, self, w_other)
  593. if w_a is None:
  594. w_a = self
  595. w_b = w_other
  596. if w_a is self:
  597. w_func = self.getattr(space, '__pow__', False)
  598. if w_func is not None:
  599. return space.call_function(w_func, w_other)
  600. return space.w_NotImplemented
  601. else:
  602. return space.pow(w_a, w_b, space.w_None)
  603. else:
  604. # CPython also doesn't try coercion in this case
  605. w_func = self.getattr(space, '__pow__', False)
  606. if w_func is not None:
  607. return space.call_function(w_func, w_other, w_modulo)
  608. return space.w_NotImplemented
  609. def descr_rpow(self, space, w_other, w_modulo=None):
  610. if space.is_w(w_modulo, space.w_None):
  611. w_a, w_b = _coerce_helper(space, self, w_other)
  612. if w_a is None:
  613. w_a = self
  614. w_b = w_other
  615. if w_a is self:
  616. w_func = self.getattr(space, '__rpow__', False)
  617. if w_func is not None:
  618. return space.call_function(w_func, w_other)
  619. return space.w_NotImplemented
  620. else:
  621. return space.pow(w_b, w_a, space.w_None)
  622. else:
  623. # CPython also doesn't try coercion in this case
  624. w_func = self.getattr(space, '__rpow__', False)
  625. if w_func is not None:
  626. return space.call_function(w_func, w_other, w_modulo)
  627. return space.w_NotImplemented
  628. def descr_next(self, space):
  629. w_func = self.getattr(space, 'next', False)
  630. if w_func is None:
  631. raise OperationError(space.w_TypeError,
  632. space.wrap("instance has no next() method"))
  633. return space.call_function(w_func)
  634. def descr_del(self, space):
  635. # Note that this is called from executioncontext.UserDelAction
  636. # via the space.userdel() method.
  637. w_func = self.getdictvalue(space, '__del__')
  638. if w_func is None:
  639. w_func = self.getattr_from_class(space, '__del__')
  640. if w_func is not None:
  641. space.call_function(w_func)
  642. def descr_exit(self, space, w_type, w_value, w_tb):
  643. w_func = self.getattr(space, '__exit__', False)
  644. if w_func is not None:
  645. return space.call_function(w_func, w_type, w_value, w_tb)
  646. rawdict = {}
  647. # unary operations
  648. for op in "neg pos abs invert trunc float oct hex enter reversed".split():
  649. specialname = "__%s__" % (op, )
  650. # fool the gateway logic by giving it a real unbound method
  651. meth = new.instancemethod(
  652. make_unary_instance_method(specialname),
  653. None,
  654. W_InstanceObject)
  655. rawdict[specialname] = interp2app(meth)
  656. # binary operations that return NotImplemented if they fail
  657. # e.g. rich comparisons, coerce and inplace ops
  658. for op in 'eq ne gt lt ge le coerce imod iand ipow itruediv ilshift ixor irshift ifloordiv idiv isub imul iadd ior'.split():
  659. specialname = "__%s__" % (op, )
  660. # fool the gateway logic by giving it a real unbound method
  661. meth = new.instancemethod(
  662. make_binary_returning_notimplemented_instance_method(specialname),
  663. None,
  664. W_InstanceObject)
  665. rawdict[specialname] = interp2app(meth)
  666. for op in "or and xor lshift rshift add sub mul div mod divmod floordiv truediv".split():
  667. specialname = "__%s__" % (op, )
  668. rspecialname = "__r%s__" % (op, )
  669. func, rfunc = make_binary_instance_method(op)
  670. # fool the gateway logic by giving it a real unbound method
  671. meth = new.instancemethod(func, None, W_InstanceObject)
  672. rawdict[specialname] = interp2app(meth)
  673. rmeth = new.instancemethod(rfunc, None, W_InstanceObject)
  674. rawdict[rspecialname] = interp2app(rmeth)
  675. def descr_del_dict(space, w_inst):
  676. # use setdict to raise the error
  677. w_inst.setdict(space, space.w_None)
  678. dict_descr = GetSetProperty(descr_get_dict, descr_set_dict, descr_del_dict)
  679. dict_descr.name = '__dict__'
  680. W_InstanceObject.typedef = TypeDef("instance",
  681. __new__ = interp2app(descr_instance_new),
  682. __getattribute__ = interp2app(W_InstanceObject.descr_getattribute),
  683. __setattr__ = interp2app(W_InstanceObject.descr_setattr),
  684. __delattr__ = interp2app(W_InstanceObject.descr_delattr),
  685. __repr__ = interp2app(W_InstanceObject.descr_repr),
  686. __str__ = interp2app(W_InstanceObject.descr_str),
  687. __unicode__ = interp2app(W_InstanceObject.descr_unicode),
  688. __format__ = interp2app(W_InstanceObject.descr_format),
  689. __len__ = interp2app(W_InstanceObject.descr_len),
  690. __getitem__ = interp2app(W_InstanceObject.descr_getitem),
  691. __setitem__ = interp2app(W_InstanceObject.descr_setitem),
  692. __delitem__ = interp2app(W_InstanceObject.descr_delitem),
  693. __iter__ = interp2app(W_InstanceObject.descr_iter),
  694. __getslice__ = interp2app(W_InstanceObject.descr_getslice),
  695. __setslice__ = interp2app(W_InstanceObject.descr_setslice),
  696. __delslice__ = interp2app(W_InstanceObject.descr_delslice),
  697. __call__ = interp2app(W_InstanceObject.descr_call),
  698. __nonzero__ = interp2app(W_InstanceObject.descr_nonzero),
  699. __cmp__ = interp2app(W_InstanceObject.descr_cmp),
  700. __hash__ = interp2app(W_InstanceObject.descr_hash),
  701. __int__ = interp2app(W_InstanceObject.descr_int),
  702. __long__ = interp2app(W_InstanceObject.descr_long),
  703. __index__ = interp2app(W_InstanceObject.descr_index),
  704. __contains__ = interp2app(W_InstanceObject.descr_contains),
  705. __pow__ = interp2app(W_InstanceObject.descr_pow),
  706. __rpow__ = interp2app(W_InstanceObject.descr_rpow),
  707. next = interp2app(W_InstanceObject.descr_next),
  708. __del__ = interp2app(W_InstanceObject.descr_del),
  709. __exit__ = interp2app(W_InstanceObject.descr_exit),
  710. __dict__ = dict_descr,
  711. **rawdict
  712. )
  713. W_InstanceObject.typedef.acceptable_as_base_class = False