| 1 |
"""The builtin object type implementation""" |
| 2 |
|
| 3 |
from pypy.interpreter.baseobjspace import W_Root |
| 4 |
from pypy.interpreter.error import OperationError, oefmt |
| 5 |
from pypy.interpreter.gateway import applevel, interp2app, unwrap_spec |
| 6 |
from pypy.interpreter.typedef import ( |
| 7 |
GetSetProperty, TypeDef, default_identity_hash) |
| 8 |
from pypy.objspace.descroperation import Object |
| 9 |
from pypy.interpreter.function import StaticMethod |
| 10 |
|
| 11 |
from rpython.rlib.objectmodel import specialize |
| 12 |
|
| 13 |
|
| 14 |
app = applevel(r''' |
| 15 |
import sys |
| 16 |
|
| 17 |
def _abstract_method_error(typ): |
| 18 |
methods = ", ".join(sorted(typ.__abstractmethods__)) |
| 19 |
method_s = 's' if len(typ.__abstractmethods__) > 1 else '' |
| 20 |
err = "Can't instantiate abstract class %s with abstract method%s %s" |
| 21 |
raise TypeError(err % (typ.__name__, method_s, methods)) |
| 22 |
|
| 23 |
def reduce_1(obj, proto): |
| 24 |
import copyreg |
| 25 |
return copyreg._reduce_ex(obj, proto) |
| 26 |
|
| 27 |
def reduce_2(obj, proto, args, kwargs): |
| 28 |
cls = obj.__class__ |
| 29 |
|
| 30 |
if not hasattr(type(obj), "__new__"): |
| 31 |
raise TypeError("can't pickle %s objects" % type(obj).__name__) |
| 32 |
|
| 33 |
try: |
| 34 |
copyreg = sys.modules['copyreg'] |
| 35 |
except KeyError: |
| 36 |
import copyreg |
| 37 |
|
| 38 |
if not isinstance(args, tuple): |
| 39 |
raise TypeError("__getnewargs__ should return a tuple") |
| 40 |
if not kwargs: |
| 41 |
newobj = copyreg.__newobj__ |
| 42 |
args2 = (cls,) + args |
| 43 |
else: |
| 44 |
newobj = copyreg.__newobj_ex__ |
| 45 |
args2 = (cls, args, kwargs) |
| 46 |
state = obj.__getstate__() |
| 47 |
listitems = iter(obj) if isinstance(obj, list) else None |
| 48 |
dictitems = iter(obj.items()) if isinstance(obj, dict) else None |
| 49 |
|
| 50 |
return newobj, args2, state, listitems, dictitems |
| 51 |
|
| 52 |
|
| 53 |
def get_slotvalues(obj): |
| 54 |
names = slotnames(obj.__class__) |
| 55 |
if not names: |
| 56 |
return None |
| 57 |
slots = {} |
| 58 |
for name in names: |
| 59 |
try: |
| 60 |
value = getattr(obj, name) |
| 61 |
except AttributeError: |
| 62 |
pass |
| 63 |
else: |
| 64 |
slots[name] = value |
| 65 |
return slots |
| 66 |
|
| 67 |
|
| 68 |
def slotnames(cls): |
| 69 |
if not isinstance(cls, type): |
| 70 |
return None |
| 71 |
|
| 72 |
try: |
| 73 |
return cls.__dict__["__slotnames__"] |
| 74 |
except KeyError: |
| 75 |
pass |
| 76 |
|
| 77 |
try: |
| 78 |
copyreg = sys.modules['copyreg'] |
| 79 |
except KeyError: |
| 80 |
import copyreg |
| 81 |
slotnames = copyreg._slotnames(cls) |
| 82 |
if not isinstance(slotnames, list) and slotnames is not None: |
| 83 |
raise TypeError("copyreg._slotnames didn't return a list or None") |
| 84 |
return slotnames |
| 85 |
''', filename=__file__) |
| 86 |
|
| 87 |
_abstract_method_error = app.interphook("_abstract_method_error") |
| 88 |
reduce_1 = app.interphook('reduce_1') |
| 89 |
reduce_2 = app.interphook('reduce_2') |
| 90 |
get_slotvalues = app.interphook('get_slotvalues') |
| 91 |
|
| 92 |
|
| 93 |
class W_ObjectObject(W_Root): |
| 94 |
"""Instances of this class are what the user can directly see with an |
| 95 |
'object()' call.""" |
| 96 |
|
| 97 |
|
| 98 |
def _excess_args(__args__): |
| 99 |
return bool(__args__.arguments_w) or bool(__args__.keyword_names_w) |
| 100 |
|
| 101 |
@specialize.memo() |
| 102 |
def _object_new(space): |
| 103 |
"Utility that returns the function object.__new__." |
| 104 |
w_x = space.lookup_in_type(space.w_object, '__new__') |
| 105 |
assert isinstance(w_x, StaticMethod) |
| 106 |
return w_x.w_function |
| 107 |
|
| 108 |
@specialize.memo() |
| 109 |
def _object_init(space): |
| 110 |
"Utility that returns the function object.__init__." |
| 111 |
return space.lookup_in_type(space.w_object, '__init__') |
| 112 |
|
| 113 |
def _same_static_method(space, w_x, w_y): |
| 114 |
|
| 115 |
if isinstance(w_x, StaticMethod): w_x = w_x.w_function |
| 116 |
return space.is_w(w_x, w_y) |
| 117 |
|
| 118 |
def descr__new__(space, w_type, __args__): |
| 119 |
from pypy.objspace.std.typeobject import _precheck_for_new |
| 120 |
w_type = _precheck_for_new(space, w_type) |
| 121 |
|
| 122 |
if _excess_args(__args__): |
| 123 |
tp_new = space.lookup_in_type(w_type, '__new__') |
| 124 |
tp_init = space.lookup_in_type(w_type, '__init__') |
| 125 |
if not _same_static_method(space, tp_new, _object_new(space)): |
| 126 |
raise oefmt(space.w_TypeError, |
| 127 |
"object.__new__() takes exactly one argument (the type to instantiate)") |
| 128 |
if space.is_w(tp_init, _object_init(space)): |
| 129 |
raise oefmt(space.w_TypeError, |
| 130 |
"%s() takes no arguments", w_type.name) |
| 131 |
if w_type.is_abstract(): |
| 132 |
_abstract_method_error(space, w_type) |
| 133 |
return space.allocate_instance(W_ObjectObject, w_type) |
| 134 |
|
| 135 |
|
| 136 |
def descr___subclasshook__(space, __args__): |
| 137 |
return space.w_NotImplemented |
| 138 |
|
| 139 |
def descr___init_subclass__(space, w_cls): |
| 140 |
return space.w_None |
| 141 |
|
| 142 |
def descr__init__(space, w_obj, __args__): |
| 143 |
if _excess_args(__args__): |
| 144 |
w_type = space.type(w_obj) |
| 145 |
tp_new = space.lookup_in_type(w_type, '__new__') |
| 146 |
tp_init = space.lookup_in_type(w_type, '__init__') |
| 147 |
if not space.is_w(tp_init, _object_init(space)): |
| 148 |
raise oefmt(space.w_TypeError, |
| 149 |
"object.__init__() takes exactly one argument (the instance to initialize)") |
| 150 |
elif _same_static_method(space, tp_new, _object_new(space)): |
| 151 |
raise oefmt(space.w_TypeError, |
| 152 |
"%T.__init__() takes exactly one argument (the instance to initialize)", |
| 153 |
w_obj) |
| 154 |
|
| 155 |
|
| 156 |
def descr_get___class__(space, w_obj): |
| 157 |
return space.type(w_obj) |
| 158 |
|
| 159 |
|
| 160 |
def descr_set___class__(space, w_obj, w_newcls): |
| 161 |
from pypy.objspace.std.typeobject import W_TypeObject |
| 162 |
from pypy.interpreter.module import Module |
| 163 |
|
| 164 |
if not isinstance(w_newcls, W_TypeObject): |
| 165 |
raise oefmt(space.w_TypeError, |
| 166 |
"__class__ must be set to a class, not '%T' " |
| 167 |
"object", w_newcls) |
| 168 |
if not (w_newcls.is_heaptype() or |
| 169 |
w_newcls is space.gettypeobject(Module.typedef)): |
| 170 |
raise oefmt(space.w_TypeError, |
| 171 |
"__class__ assignment only supported for heap types " |
| 172 |
"or ModuleType subclasses") |
| 173 |
w_oldcls = space.type(w_obj) |
| 174 |
assert isinstance(w_oldcls, W_TypeObject) |
| 175 |
if (w_oldcls.get_full_instance_layout() == |
| 176 |
w_newcls.get_full_instance_layout()): |
| 177 |
w_obj.setclass(space, w_newcls) |
| 178 |
else: |
| 179 |
raise oefmt(space.w_TypeError, |
| 180 |
"__class__ assignment: '%N' object layout differs from " |
| 181 |
"'%N'", w_oldcls, w_newcls) |
| 182 |
|
| 183 |
|
| 184 |
def descr__repr__(space, w_obj): |
| 185 |
classname = space.getfulltypename(w_obj) |
| 186 |
return w_obj.getrepr(space, '%s object' % (classname,)) |
| 187 |
descr__repr__.__text_signature__ = '($self, /)' |
| 188 |
descr__init__.__text_signature__ = '($self, /, *args, **kwargs)' |
| 189 |
descr__new__.__text_signature__ = '($type, *args, **kwargs)' |
| 190 |
|
| 191 |
|
| 192 |
def descr__str__(space, w_obj): |
| 193 |
w_type = space.type(w_obj) |
| 194 |
w_impl = w_type.lookup("__repr__") |
| 195 |
if w_impl is None: |
| 196 |
|
| 197 |
raise oefmt(space.w_TypeError, "operand does not support unary str") |
| 198 |
return space.get_and_call_function(w_impl, w_obj) |
| 199 |
|
| 200 |
|
| 201 |
def _getnewargs(space, w_obj): |
| 202 |
w_descr = space.lookup(w_obj, '__getnewargs_ex__') |
| 203 |
hasargs = True |
| 204 |
if w_descr is not None: |
| 205 |
w_result = space.get_and_call_function(w_descr, w_obj) |
| 206 |
if not space.isinstance_w(w_result, space.w_tuple): |
| 207 |
raise oefmt(space.w_TypeError, |
| 208 |
"__getnewargs_ex__ should return a tuple, not '%T'", w_result) |
| 209 |
n = space.len_w(w_result) |
| 210 |
if n != 2: |
| 211 |
raise oefmt(space.w_ValueError, |
| 212 |
"__getnewargs_ex__ should return a tuple of length 2, not %d", |
| 213 |
n) |
| 214 |
w_args, w_kwargs = space.fixedview(w_result, 2) |
| 215 |
if not space.isinstance_w(w_args, space.w_tuple): |
| 216 |
raise oefmt(space.w_TypeError, |
| 217 |
"first item of the tuple returned by __getnewargs_ex__ must " |
| 218 |
"be a tuple, not '%T'", w_args) |
| 219 |
if not space.isinstance_w(w_kwargs, space.w_dict): |
| 220 |
raise oefmt(space.w_TypeError, |
| 221 |
"second item of the tuple returned by __getnewargs_ex__ must " |
| 222 |
"be a dict, not '%T'", w_kwargs) |
| 223 |
else: |
| 224 |
w_descr = space.lookup(w_obj, '__getnewargs__') |
| 225 |
if w_descr is not None: |
| 226 |
w_args = space.get_and_call_function(w_descr, w_obj) |
| 227 |
if not space.isinstance_w(w_args, space.w_tuple): |
| 228 |
raise oefmt(space.w_TypeError, |
| 229 |
"__getnewargs__ should return a tuple, not '%T'", w_args) |
| 230 |
else: |
| 231 |
hasargs = False |
| 232 |
w_args = space.newtuple([]) |
| 233 |
w_kwargs = space.w_None |
| 234 |
return hasargs, w_args, w_kwargs |
| 235 |
|
| 236 |
def descr__getstate__(space, w_obj): |
| 237 |
"""Helper for pickle""" |
| 238 |
return object_getstate_default(space, w_obj, 0) |
| 239 |
|
| 240 |
def descr__reduce__(space, w_obj): |
| 241 |
"""Helper for pickle""" |
| 242 |
w_proto = space.newint(0) |
| 243 |
return reduce_1(space, w_obj, w_proto) |
| 244 |
|
| 245 |
def object_getstate_default(space, w_obj, required): |
| 246 |
w_obj_type = space.type(w_obj) |
| 247 |
if required and w_obj_type.layout.typedef.variable_sized: |
| 248 |
|
| 249 |
raise oefmt(space.w_TypeError, "cannot pickle %N objects", w_obj) |
| 250 |
w_objdict = space.findattr(w_obj, space.newtext("__dict__")) |
| 251 |
if w_objdict and space.len_w(w_objdict) > 0: |
| 252 |
w_ret = space.call_method(w_objdict, 'copy') |
| 253 |
else: |
| 254 |
w_ret = space.w_None |
| 255 |
w_slots = get_slotvalues(space, w_obj) |
| 256 |
if w_slots is not space.w_None: |
| 257 |
w_ret = space.newtuple([w_ret, w_slots]) |
| 258 |
return w_ret |
| 259 |
|
| 260 |
@unwrap_spec(proto=int) |
| 261 |
def descr__reduce_ex__(space, w_obj, proto): |
| 262 |
"""Helper for pickle""" |
| 263 |
w_st_reduce = space.newtext('__reduce__') |
| 264 |
w_reduce = space.findattr(w_obj, w_st_reduce) |
| 265 |
if w_reduce is not None: |
| 266 |
|
| 267 |
|
| 268 |
w_cls_reduce = space.getattr(space.type(w_obj), w_st_reduce) |
| 269 |
w_obj_reduce = space.getattr(space.w_object, w_st_reduce) |
| 270 |
override = not space.is_w(w_cls_reduce, w_obj_reduce) |
| 271 |
if override: |
| 272 |
return space.call_function(w_reduce) |
| 273 |
w_proto = space.newint(proto) |
| 274 |
if proto >= 2: |
| 275 |
hasargs, w_args, w_kwargs = _getnewargs(space, w_obj) |
| 276 |
w_getstate = space.lookup(w_obj, '__get_state__') |
| 277 |
if w_getstate is None: |
| 278 |
required = (not hasargs and |
| 279 |
not space.isinstance_w(w_obj, space.w_list) and |
| 280 |
not space.isinstance_w(w_obj, space.w_dict)) |
| 281 |
w_obj_type = space.type(w_obj) |
| 282 |
if required and w_obj_type.layout.typedef.variable_sized: |
| 283 |
raise oefmt( |
| 284 |
space.w_TypeError, "cannot pickle %N objects", w_obj_type) |
| 285 |
return reduce_2(space, w_obj, w_proto, w_args, w_kwargs) |
| 286 |
return reduce_1(space, w_obj, w_proto) |
| 287 |
|
| 288 |
def descr___format__(space, w_obj, w_format_spec): |
| 289 |
if space.isinstance_w(w_format_spec, space.w_unicode): |
| 290 |
if space.len_w(w_format_spec) > 0: |
| 291 |
raise oefmt(space.w_TypeError, |
| 292 |
"unsupported format string passed to %T.__format__", |
| 293 |
w_obj) |
| 294 |
w_as_str = space.call_function(space.w_unicode, w_obj) |
| 295 |
elif space.isinstance_w(w_format_spec, space.w_bytes): |
| 296 |
if space.len_w(w_format_spec) > 0: |
| 297 |
raise oefmt(space.w_TypeError, |
| 298 |
"unsupported format string passed to %T.__format__", |
| 299 |
w_obj) |
| 300 |
w_as_str = space.str(w_obj) |
| 301 |
else: |
| 302 |
raise oefmt(space.w_TypeError, "format_spec must be a string") |
| 303 |
return w_as_str |
| 304 |
|
| 305 |
def descr__eq__(space, w_self, w_other): |
| 306 |
if space.is_w(w_self, w_other): |
| 307 |
return space.w_True |
| 308 |
|
| 309 |
|
| 310 |
return space.w_NotImplemented |
| 311 |
|
| 312 |
def descr__ne__(space, w_self, w_other): |
| 313 |
|
| 314 |
|
| 315 |
w_eq = space.lookup(w_self, '__eq__') |
| 316 |
w_res = space.get_and_call_function(w_eq, w_self, w_other) |
| 317 |
if space.is_w(w_res, space.w_NotImplemented): |
| 318 |
return w_res |
| 319 |
return space.not_(w_res) |
| 320 |
|
| 321 |
def descr_richcompare(space, w_self, w_other): |
| 322 |
return space.w_NotImplemented |
| 323 |
|
| 324 |
def descr__dir__(space, w_obj): |
| 325 |
from pypy.objspace.std.util import _objectdir |
| 326 |
return space.call_function(space.w_list, _objectdir(space, w_obj)) |
| 327 |
|
| 328 |
class ObjectObjectDocstrings: |
| 329 |
|
| 330 |
def __new__(): |
| 331 |
"""Create and return a new object. See help(type) for accurate signature.""" |
| 332 |
|
| 333 |
def __init__(): |
| 334 |
"""Initialize self. See help(type(self)) for accurate signature.""" |
| 335 |
|
| 336 |
def __class__(): |
| 337 |
"""type(object) -> the object's type |
| 338 |
type(name, bases, dict, **kwds) -> a new type""" |
| 339 |
|
| 340 |
def __repr__(): |
| 341 |
"""Return repr(self).""" |
| 342 |
|
| 343 |
def __str__(): |
| 344 |
"""Return str(self).""" |
| 345 |
|
| 346 |
def __hash__(): |
| 347 |
"""Return hash(self).""" |
| 348 |
|
| 349 |
def __eq__(): |
| 350 |
"""Return self==value.""" |
| 351 |
|
| 352 |
def __ne__(): |
| 353 |
"""Return self!=value.""" |
| 354 |
|
| 355 |
def __lt__(): |
| 356 |
"""Return self<value.""" |
| 357 |
|
| 358 |
def __le__(): |
| 359 |
"""Return self<=value.""" |
| 360 |
|
| 361 |
def __gt__(): |
| 362 |
"""Return self>value.""" |
| 363 |
|
| 364 |
def __ge__(): |
| 365 |
"""Return self>=value.""" |
| 366 |
|
| 367 |
def __getattribute__(): |
| 368 |
"""Return getattr(self, name).""" |
| 369 |
|
| 370 |
def __setattr__(): |
| 371 |
"""Implement setattr(self, name, value).""" |
| 372 |
|
| 373 |
def __delattr__(): |
| 374 |
"""Implement delattr(self, name).""" |
| 375 |
|
| 376 |
def __dir__(): |
| 377 |
"""Default dir() implementation.""" |
| 378 |
|
| 379 |
def __format__(): |
| 380 |
"""Default object formatter.""" |
| 381 |
|
| 382 |
def __reduce__(): |
| 383 |
"""Helper for pickle.""" |
| 384 |
|
| 385 |
def __reduce_ex__(): |
| 386 |
"""Helper for pickle.""" |
| 387 |
|
| 388 |
def __getstate__(): |
| 389 |
"""Helper for pickle.""" |
| 390 |
|
| 391 |
def __subclasshook__(): |
| 392 |
"""Abstract classes can override this to customize issubclass(). |
| 393 |
|
| 394 |
This is invoked early on by abc.ABCMeta.__subclasscheck__(). |
| 395 |
It should return True, False or NotImplemented. If it returns |
| 396 |
NotImplemented, the normal algorithm is used. Otherwise, it |
| 397 |
overrides the normal algorithm (and the outcome is cached). |
| 398 |
""" |
| 399 |
|
| 400 |
def __init_subclass__(): |
| 401 |
"""This method is called when a class is subclassed. |
| 402 |
|
| 403 |
The default implementation does nothing. It may be |
| 404 |
overridden to extend subclasses. |
| 405 |
""" |
| 406 |
|
| 407 |
W_ObjectObject.typedef = TypeDef("object", |
| 408 |
__rpython_level_class__ = W_ObjectObject, |
| 409 |
_text_signature_='()', |
| 410 |
__doc__ = "The most base type", |
| 411 |
__new__ = interp2app(descr__new__, |
| 412 |
doc=ObjectObjectDocstrings.__new__.__doc__), |
| 413 |
__subclasshook__ = interp2app(descr___subclasshook__, as_classmethod=True, |
| 414 |
doc=ObjectObjectDocstrings.__subclasshook__.__doc__), |
| 415 |
__init_subclass__ = interp2app(descr___init_subclass__, as_classmethod=True, |
| 416 |
doc=ObjectObjectDocstrings.__init_subclass__.__doc__), |
| 417 |
|
| 418 |
|
| 419 |
__getattribute__ = interp2app(Object.descr__getattribute__.im_func, |
| 420 |
doc=ObjectObjectDocstrings.__getattribute__.__doc__), |
| 421 |
__setattr__ = interp2app(Object.descr__setattr__.im_func, |
| 422 |
doc=ObjectObjectDocstrings.__setattr__.__doc__), |
| 423 |
__delattr__ = interp2app(Object.descr__delattr__.im_func, |
| 424 |
doc=ObjectObjectDocstrings.__delattr__.__doc__), |
| 425 |
|
| 426 |
__getstate__ = interp2app(descr__getstate__, |
| 427 |
doc=ObjectObjectDocstrings.__getstate__.__doc__), |
| 428 |
__init__ = interp2app(descr__init__, |
| 429 |
doc=ObjectObjectDocstrings.__init__.__doc__), |
| 430 |
__class__ = GetSetProperty(descr_get___class__, descr_set___class__, |
| 431 |
doc=ObjectObjectDocstrings.__class__.__doc__), |
| 432 |
__repr__ = interp2app(descr__repr__, |
| 433 |
doc=ObjectObjectDocstrings.__repr__.__doc__), |
| 434 |
__str__ = interp2app(descr__str__, |
| 435 |
doc=ObjectObjectDocstrings.__str__.__doc__), |
| 436 |
__hash__ = interp2app(default_identity_hash, |
| 437 |
doc=ObjectObjectDocstrings.__hash__.__doc__), |
| 438 |
__reduce__ = interp2app(descr__reduce__, |
| 439 |
doc=ObjectObjectDocstrings.__reduce__.__doc__), |
| 440 |
__reduce_ex__ = interp2app(descr__reduce_ex__, |
| 441 |
doc=ObjectObjectDocstrings.__reduce_ex__.__doc__), |
| 442 |
__format__ = interp2app(descr___format__, |
| 443 |
doc=ObjectObjectDocstrings.__format__.__doc__), |
| 444 |
__dir__ = interp2app(descr__dir__, |
| 445 |
doc=ObjectObjectDocstrings.__dir__.__doc__), |
| 446 |
|
| 447 |
__eq__ = interp2app(descr__eq__, |
| 448 |
doc=ObjectObjectDocstrings.__eq__.__doc__), |
| 449 |
__ne__ = interp2app(descr__ne__, |
| 450 |
doc=ObjectObjectDocstrings.__ne__.__doc__), |
| 451 |
__le__ = interp2app(descr_richcompare, |
| 452 |
doc=ObjectObjectDocstrings.__le__.__doc__), |
| 453 |
__lt__ = interp2app(descr_richcompare, |
| 454 |
doc=ObjectObjectDocstrings.__lt__.__doc__), |
| 455 |
__ge__ = interp2app(descr_richcompare, |
| 456 |
doc=ObjectObjectDocstrings.__ge__.__doc__), |
| 457 |
__gt__ = interp2app(descr_richcompare, |
| 458 |
doc=ObjectObjectDocstrings.__gt__.__doc__), |
| 459 |
) |