3
# producing nicer code objects by exec
4
from pypy.tool.sourcetools import NiceCompile
5
_compile = NiceCompile(globals())
7
def _coerce(left, right):
9
return coerce(left, right)
13
obj_setattr = object.__setattr__
14
obj_getattribute = object.__getattribute__
16
HMASK = long(sys.maxint)
26
# we use slots that we remove from type __dict__ for special attributes
28
# for classobj they are __bases__ and __name__ (classobj_bases_slot, classobj_name_slot)
29
# for instance it's __class__ (instance_class_slot)
32
# ____________________________________________________________
35
def type_err(arg, expected, v):
36
return TypeError("argument %s must be %s, not %s" % (arg, expected, type(v).__name__))
38
def set_name(cls, name):
39
if not isinstance(name, str):
40
raise TypeError, "__name__ must be a string object"
41
classobj_name_slot.__set__(cls, name)
43
def set_bases(cls, bases):
44
if not isinstance(bases, tuple):
45
raise TypeError, "__bases__ must be a tuple object"
47
if not isinstance(b, classobj):
48
raise TypeError, "__bases__ items must be classes"
49
classobj_bases_slot.__set__(cls, bases)
51
def set_dict(cls, dic):
52
if not isinstance(dic, dict):
53
raise TypeError, "__dict__ must be a dictionary object"
54
obj_setattr(cls, '__dict__', dic)
56
def retrieve(obj, attr):
57
dic = obj_getattribute(obj, '__dict__')
61
raise AttributeError, attr
63
def lookup(cls, attr):
64
# returns (value, class it was found in)
66
v = retrieve(cls, attr)
68
except AttributeError:
69
for b in classobj_bases_slot.__get__(cls):
70
v, found = lookup(b, attr)
75
def get_class_module(cls):
77
mod = retrieve(cls, "__module__")
78
except AttributeError:
80
if not isinstance(mod, str):
84
def mro_lookup(v, name):
87
except AttributeError:
90
if name in x.__dict__:
91
return x.__dict__[name]
95
func = obj.__getitem__
103
# let geninterplevel retrieve the PyPy builtin instead
104
_seqiter.geninterplevel_name = lambda gen: "space.builtin.get('_seqiter')"
106
OLD_STYLE_CLASSES_IMPL = object()
108
class classobj(object):
110
__slots__ = ('_name', '_bases', '__dict__')
112
def __new__(subtype, name, bases, dic):
113
if not isinstance(name, str):
114
raise type_err('name', 'string', name)
119
if not isinstance(bases, tuple):
120
raise type_err('bases', 'tuple', bases)
122
if not isinstance(dic, dict):
123
raise type_err('dict', 'dict', dic)
128
dic['__doc__'] = None
136
g = sys._getframe(i).f_globals
137
if not g.get('OLD_STYLE_CLASSES_IMPL',None) is OLD_STYLE_CLASSES_IMPL:
143
modname = g.get('__name__', None)
144
if modname is not None:
145
dic['__module__'] = modname
148
if not isinstance(b, classobj):
149
if callable(type(b)):
150
return type(b)(name, bases, dic)
151
raise TypeError,"base must be class"
154
new_class = object.__new__(classobj)
156
obj_setattr(new_class, '__dict__', dic)
157
classobj_name_slot.__set__(new_class, name)
158
classobj_bases_slot.__set__(new_class, bases)
162
def __setattr__(self, attr, value):
163
if attr == '__name__':
164
set_name(self, value)
165
elif attr == '__bases__':
166
set_bases(self, value)
167
elif attr == '__dict__':
168
set_dict(self, value)
170
obj_setattr(self, attr, value)
172
def __delattr__(self, attr):
173
if attr in ('__name__', '__bases__', '__dict__'):
174
classobj.__setattr__(self, attr, None)
176
object.__delattr__(self, attr)
179
def __getattribute__(self, attr):
180
if attr == '__dict__':
181
return obj_getattribute(self, '__dict__')
182
if attr == '__name__':
183
return classobj_name_slot.__get__(self)
184
if attr == '__bases__':
185
return classobj_bases_slot.__get__(self)
187
v, found = lookup(self, attr)
189
raise AttributeError, "class %s has no attribute %s" % (self.__name__, attr)
191
descr_get = mro_lookup(v, '__get__')
192
if descr_get is None:
194
return descr_get(v, None, self)
197
mod = get_class_module(self)
198
return "<class %s.%s at 0x%x>" % (mod, self.__name__, uid(self))
201
mod = get_class_module(self)
205
return "%s.%s" % (mod, self.__name__)
207
def __call__(self, *args, **kwds):
208
inst = object.__new__(instance)
210
instance_class_slot.__set__(inst, self)
211
init = instance_getattr1(inst,'__init__', False)
213
ret = init(*args, **kwds)
215
raise TypeError("__init__() should return None")
217
raise TypeError("this constructor takes no arguments")
220
# capture _name, _bases slots for usage and then hide them!
222
classobj_name_slot = classobj._name
223
classobj_bases_slot = classobj._bases
225
del classobj._name, classobj._bases
227
# ____________________________________________________________
230
def instance_getattr1(inst, name, exc=True):
231
if name == "__dict__":
232
return obj_getattribute(inst, name)
233
elif name == "__class__":
234
return instance_class_slot.__get__(inst)
236
return retrieve(inst, name)
237
except AttributeError:
238
cls = instance_class_slot.__get__(inst)
239
v, found = lookup(cls, name)
242
raise AttributeError, "%s instance has no attribute %s" % (cls.__name__, name)
245
descr_get = mro_lookup(v, '__get__')
246
if descr_get is None:
248
return descr_get(v, inst, cls)
250
class instance(object):
252
__slots__ = ('_class', '__dict__')
254
def __getattribute__(self, name):
256
return instance_getattr1(self, name)
257
except AttributeError:
258
getattr = instance_getattr1(self, '__getattr__', exc=False)
259
if getattr is not None:
263
def __new__(typ, klass, dic=None):
264
# typ is not used at all
265
if not isinstance(klass,classobj):
266
raise TypeError("instance() first arg must be class")
269
elif not isinstance(dic, dict):
270
raise TypeError("instance() second arg must be dictionary or None")
271
inst = object.__new__(instance)
272
instance_class_slot.__set__(inst, klass)
273
obj_setattr(inst, '__dict__', dic)
277
func = instance_getattr1(self, '__del__', exc=False)
281
def __setattr__(self, name, value):
282
if name == '__dict__':
283
if not isinstance(value, dict):
284
raise TypeError("__dict__ must be set to a dictionary")
285
obj_setattr(self, '__dict__', value)
286
elif name == '__class__':
287
if not isinstance(value, classobj):
288
raise TypeError("__class__ must be set to a class")
289
instance_class_slot.__set__(self, value)
291
setattr = instance_getattr1(self, '__setattr__', exc=False)
292
if setattr is not None:
295
self.__dict__[name] = value
297
def __delattr__(self, name):
298
# abuse __setattr__ to get the complaints :-)
299
# this is as funny as in CPython
300
if name in ('__dict__', '__class__'):
301
instance.__setattr__(self, name, None)
303
delattr = instance_getattr1(self, '__delattr__', exc=False)
304
if delattr is not None:
308
del self.__dict__[name]
310
raise AttributeError("%s instance has no attribute '%s'" % (
311
self.__class__.__name__,name) )
315
func = instance_getattr1(self, '__repr__')
316
except AttributeError:
317
klass = self.__class__
318
mod = get_class_module(klass)
319
return "<%s.%s instance at 0x%x>" % (mod, klass.__name__, uid(self))
324
func = instance_getattr1(self, '__str__')
325
except AttributeError:
326
return instance.__repr__(self)
330
_eq = instance_getattr1(self, "__eq__", False)
331
_cmp = instance_getattr1(self, "__cmp__", False)
332
_hash = instance_getattr1(self, "__hash__", False)
333
if (_eq or _cmp) and not _hash:
334
raise TypeError("unhashable instance")
337
if not isinstance(ret, int):
338
raise TypeError("__hash__() should return an int")
341
return object.__hash__(self)
344
ret = instance_getattr1(self,'__len__')()
345
if isinstance(ret, int):
347
raise ValueError("__len__() should return >= 0")
350
raise TypeError("__len__() should return an int")
352
def __getitem__(self, key):
353
return instance_getattr1(self, '__getitem__')(key)
355
def __setitem__(self, key, value):
356
instance_getattr1(self, '__setitem__')(key, value)
358
def __delitem__(self, key):
359
instance_getattr1(self, '__delitem__')(key)
361
def __getslice__(self, i, j):
362
func = instance_getattr1(self, '__getslice__', False)
368
def __setslice__(self, i, j, sequence):
369
func = instance_getattr1(self, '__setslice__', False)
373
self[i:j:] = sequence
375
def __delslice__(self, i, j):
376
func = instance_getattr1(self, '__delslice__', False)
382
def __contains__(self, obj):
383
func = instance_getattr1(self, '__contains__', False)
385
return bool(func(obj))
386
# now do it ourselves
393
for op in "neg pos abs invert int long float oct hex".split():
396
def __%(op)s__(self):
397
return instance_getattr1(self, '__%(op)s__')()
403
func = instance_getattr1(self, '__index__', False)
407
raise TypeError('object cannot be interpreted as an index')
411
def __coerce__(self, other):
412
func = instance_getattr1(self, '__coerce__', False)
415
return NotImplemented
419
for op in "or and xor lshift rshift add sub mul div mod divmod floordiv truediv".split():
421
if op in ['and', 'or']:
423
if op not in ['divmod']:
424
opref = 'operator.' + opref
427
def __%(op)s__(self, other):
428
coerced = _coerce(self, other)
429
if coerced is None or coerced[0] is self:
430
func = instance_getattr1(self, '__%(op)s__', False)
433
return NotImplemented
435
return %(opref)s(coerced[0], coerced[1])
437
def __r%(op)s__(self, other):
438
coerced = _coerce(self, other)
439
if coerced is None or coerced[0] is self:
440
func = instance_getattr1(self, '__r%(op)s__', False)
443
return NotImplemented
445
return %(opref)s(coerced[1], coerced[0])
447
""", {"op": op, "opref": opref})
452
for op in 'mod and pow truediv lshift xor rshift floordiv div sub mul add or'.split():
455
def __i%(op)s__(self, other):
456
func = instance_getattr1(self, '__i%(op)s__', False)
459
return NotImplemented
465
def __pow__(self, other, modulo=None):
467
coerced = _coerce(self, other)
468
if coerced is None or coerced[0] is self:
469
func = instance_getattr1(self, '__pow__', False)
472
return NotImplemented
474
return operator.pow(coerced[0], coerced[1], None)
476
# CPython also doesn't try coercion in this case
477
func = instance_getattr1(self, '__pow__', False)
479
return func(other, modulo)
480
return NotImplemented
483
def __rpow__(self, other, modulo=None):
485
coerced = _coerce(self, other)
486
if coerced is None or coerced[0] is self:
487
func = instance_getattr1(self, '__rpow__', False)
490
return NotImplemented
492
return operator.pow(coerced[1], coerced[0], None)
494
# CPython also doesn't try coercion in this case
495
func = instance_getattr1(self, '__rpow__', False)
497
return func(other, modulo)
498
return NotImplemented
501
def __nonzero__(self):
502
func = instance_getattr1(self, '__nonzero__', False)
504
func = instance_getattr1(self, '__len__', False)
505
if not func: # default to true
508
if isinstance(ret, int):
510
raise ValueError("__nonzero__() should return >= 0")
513
raise TypeError("__nonzero__() should return an int")
516
def __call__(self, *args, **kwds):
517
func = instance_getattr1(self, '__call__', False)
519
raise AttributeError, "%s instance has no __call__ method" % (self.__class__.__name__)
520
return func(*args, **kwds)
522
# rich comparison operations
523
for op in 'eq ne gt lt ge le'.split():
526
def __%(op)s__(self, other):
528
return instance_getattr1(self, '__%(op)s__')(other)
529
except AttributeError:
530
return NotImplemented
537
func = instance_getattr1(self, '__iter__', False)
540
if not mro_lookup(ret, 'next'):
541
raise TypeError, ("__iter__ returned non-iterator of type %s"
542
% type(ret).__name__)
544
func = instance_getattr1(self, '__getitem__', False)
546
raise TypeError, "iteration over non-sequence"
547
# moved sequiter away from here:
548
# flow space cannot handle nested functions.
549
return _seqiter(self)
552
func = instance_getattr1(self, 'next', False)
554
raise TypeError, "instance has no next() method"
557
def __cmp__(self, other): # do all the work here like CPython
558
coerced = _coerce(self, other)
565
if not isinstance(v, instance) and not isinstance(w, instance):
567
if isinstance(v, instance):
568
func = instance_getattr1(v, '__cmp__', False)
571
if isinstance(res, int):
577
raise TypeError,"__cmp__ must return int"
578
if isinstance(w, instance):
579
func = instance_getattr1(w, '__cmp__', False)
582
if isinstance(res, int):
588
raise TypeError,"__cmp__ must return int"
589
return NotImplemented
591
# capture _class slot for usage and then hide them!
592
instance_class_slot = instance._class
595
def purify(): # to use in geninterplevel case, because global side-effects are lost
598
del classobj.__slots__
600
del instance.__slots__
603
del _compile, NiceCompile