Exemple #1
0
    def test_metaclass_typedef(self):
        py.test.skip("Not implemented yet")

        # Define a metaclass
        class W_MyMetaclass(W_TypeObject):
            def f(w_self, space):
                return space.wrap(42)

        W_MyMetaclass.typedef = StdTypeDef(
            "MyMeta",
            W_TypeObject.typedef,
            f=interp2app(W_MyMetaclass.f, unwrap_spec=["self", ObjSpace]),
        )

        # Define a type, instance of the above metaclass
        class W_MyType(Wrappable):
            pass

        def MyType_descr_new(space, w_cls):
            return space.wrap(W_MyType())

        W_MyType.typedef = StdTypeDef(
            "MyType",
            __new__=interp2app(MyType_descr_new),
        )
        W_MyType.typedef.meta = W_MyMetaclass

        # Test it
        w_mytype = self.space.gettypeobject(W_MyType.typedef)
        self.space.appexec([w_mytype], """(MyType):
            x = MyType()
            assert type(x).f() == 42

            class MyDerived(MyType):
                pass
            y = MyDerived()
            assert type(y).f() == 42
        """)
Exemple #2
0
    def test_not_acceptable_as_base_class(self):
        space = self.space

        class W_Stuff(W_Object):
            pass

        def descr__new__(space, w_subtype):
            return space.allocate_instance(W_Stuff, w_subtype)

        W_Stuff.typedef = StdTypeDef("stuff", __new__=interp2app(descr__new__))
        W_Stuff.typedef.acceptable_as_base_class = False
        w_stufftype = space.gettypeobject(W_Stuff.typedef)
        space.appexec([w_stufftype], """(stufftype):
            x = stufftype.__new__(stufftype)
            assert type(x) is stufftype
            raises(TypeError, stufftype.__new__)
            raises(TypeError, stufftype.__new__, int)
            raises(TypeError, stufftype.__new__, 42)
            raises(TypeError, stufftype.__new__, stufftype, 511)
            raises(TypeError, type, 'sub', (stufftype,), {})
        """)
Exemple #3
0
def descr_get_denominator(space, w_obj):
    return space.wrap(1)

def descr_get_real(space, w_obj):
    return space.int(w_obj)

def descr_get_imag(space, w_obj):
    return space.wrap(0)

# ____________________________________________________________

int_typedef = StdTypeDef("int",
    __doc__ = '''int(x[, base]) -> integer

Convert a string or number to an integer, if possible.  A floating point
argument will be truncated towards zero (this does not include a string
representation of a floating point number!)  When converting a string, use
the optional base.  It is an error to supply a base when converting a
non-string. If the argument is outside the integer range a long object
will be returned instead.''',
    __new__ = gateway.interp2app(descr__new__),
    conjugate = gateway.interp2app(descr_conjugate),
    bit_length = gateway.interp2app(descr_bit_length),
    numerator = typedef.GetSetProperty(descr_get_numerator),
    denominator = typedef.GetSetProperty(descr_get_denominator),
    real = typedef.GetSetProperty(descr_get_real),
    imag = typedef.GetSetProperty(descr_get_imag),
)
int_typedef.registermethods(globals())
Exemple #4
0
frozenset_reduce                = SMM('__reduce__',1,
                                      doc='Return state information for'
                                          ' pickling.')
# 2.6 methods
frozenset_isdisjoint            = SMM('isdisjoint', 2,
                                      doc='Return True if two sets have a'
                                          ' null intersection.')

register_all(vars(), globals())

def descr__frozenset__new__(space, w_frozensettype,
                            w_iterable=gateway.NoneNotWrapped):
    from pypy.objspace.std.setobject import W_FrozensetObject
    from pypy.objspace.std.setobject import make_setdata_from_w_iterable
    if (space.is_w(w_frozensettype, space.w_frozenset) and
        w_iterable is not None and type(w_iterable) is W_FrozensetObject):
        return w_iterable
    w_obj = space.allocate_instance(W_FrozensetObject, w_frozensettype)
    data = make_setdata_from_w_iterable(space, w_iterable)
    W_FrozensetObject.__init__(w_obj, space, data)
    return w_obj

frozenset_typedef = StdTypeDef("frozenset",
    __doc__ = """frozenset(iterable) --> frozenset object

Build an immutable unordered collection.""",
    __new__ = gateway.interp2app(descr__frozenset__new__),
    )

frozenset_typedef.registermethods(globals())
Exemple #5
0
        space.newtuple([w_self.w_start,
                        w_self.w_stop,
                        w_self.w_step]),
        ])

# ____________________________________________________________

def slicewprop(name):
    def fget(space, w_obj):
        from pypy.objspace.std.sliceobject import W_SliceObject
        if not isinstance(w_obj, W_SliceObject):
            raise OperationError(space.w_TypeError,
                                 space.wrap("descriptor is for 'slice'"))
        return getattr(w_obj, name)
    return GetSetProperty(fget)


slice_typedef = StdTypeDef("slice",
    __doc__ = '''slice([start,] stop[, step])

Create a slice object.  This is used for extended slicing (e.g. a[0:10:2]).''',
    __new__ = gateway.interp2app(descr__new__),
    __hash__ = None,
    __reduce__ = gateway.interp2app(descr__reduce__),
    start = slicewprop('w_start'),
    stop  = slicewprop('w_stop'),
    step  = slicewprop('w_step'),
    )
slice_typedef.acceptable_as_base_class = False
slice_typedef.registermethods(globals())
Exemple #6
0
                  doc="count(obj) -> number of times obj appears in the tuple")

tuple_index = SMM("index", 4, defaults=(0, sys.maxint),
                  doc="index(obj, [start, [stop]]) -> first index that obj "
                  "appears in the tuple")


def descr__new__(space, w_tupletype, w_sequence=gateway.NoneNotWrapped):
    from pypy.objspace.std.tupleobject import W_TupleObject
    if w_sequence is None:
        tuple_w = []
    elif (space.is_w(w_tupletype, space.w_tuple) and
          space.is_w(space.type(w_sequence), space.w_tuple)):
        return w_sequence
    else:
        tuple_w = space.fixedview(w_sequence)
    w_obj = space.allocate_instance(W_TupleObject, w_tupletype)
    W_TupleObject.__init__(w_obj, tuple_w)
    return w_obj

# ____________________________________________________________

tuple_typedef = StdTypeDef("tuple",
    __doc__ = '''tuple() -> an empty tuple
tuple(sequence) -> tuple initialized from sequence's items

If the argument is a tuple, the return value is the same object.''',
    __new__ = gateway.interp2app(descr__new__),
    )
tuple_typedef.registermethods(globals())
Exemple #7
0
                                                  encoding, errors)
        if space.is_w(w_unicodetype, space.w_unicode):
            return w_value

    if space.config.objspace.std.withropeunicode:
        assert isinstance(w_value, W_RopeUnicodeObject)
        w_newobj = space.allocate_instance(W_RopeUnicodeObject, w_unicodetype)
        W_RopeUnicodeObject.__init__(w_newobj, w_value._node)
        return w_newobj

    assert isinstance(w_value, W_UnicodeObject)
    w_newobj = space.allocate_instance(W_UnicodeObject, w_unicodetype)
    W_UnicodeObject.__init__(w_newobj, w_value._value)
    return w_newobj

# ____________________________________________________________

unicode_typedef = StdTypeDef("unicode", basestring_typedef,
    __new__ = gateway.interp2app(descr_new_),
    __doc__ = '''unicode(string [, encoding[, errors]]) -> object

Create a new Unicode object from the given encoded string.
encoding defaults to the current default string encoding.
errors can be 'strict', 'replace' or 'ignore' and defaults to 'strict'.'''
    )

unicode_typedef.registermethods(globals())

unitypedef = unicode_typedef
register_all(vars(), globals())
Exemple #8
0
                  defaults=(0, sys.maxint),
                  doc="index(obj, [start, [stop]]) -> first index that obj "
                  "appears in the tuple")


def descr__new__(space, w_tupletype, w_sequence=gateway.NoneNotWrapped):
    from pypy.objspace.std.tupleobject import W_TupleObject
    if w_sequence is None:
        tuple_w = []
    elif (space.is_w(w_tupletype, space.w_tuple)
          and space.is_w(space.type(w_sequence), space.w_tuple)):
        return w_sequence
    else:
        tuple_w = space.fixedview(w_sequence)
    w_obj = space.allocate_instance(W_TupleObject, w_tupletype)
    W_TupleObject.__init__(w_obj, tuple_w)
    return w_obj


# ____________________________________________________________

tuple_typedef = StdTypeDef(
    "tuple",
    __doc__='''tuple() -> an empty tuple
tuple(sequence) -> tuple initialized from sequence's items

If the argument is a tuple, the return value is the same object.''',
    __new__=gateway.interp2app(descr__new__),
)
tuple_typedef.registermethods(globals())
Exemple #9
0
    import copy_reg
    slotnames = copy_reg._slotnames(cls)
    if not isinstance(slotnames, list) and slotnames is not None:
        raise TypeError, "copy_reg._slotnames didn't return a list or None"
    return slotnames
''', filename=__file__)

reduce_1 = app.interphook('reduce_1')
reduce_2 = app.interphook('reduce_2')

# ____________________________________________________________

object_typedef = StdTypeDef("object",
    __getattribute__ = gateway.interp2app(Object.descr__getattribute__.im_func),
    __setattr__ = gateway.interp2app(Object.descr__setattr__.im_func),
    __delattr__ = gateway.interp2app(Object.descr__delattr__.im_func),
    __str__ = gateway.interp2app(descr__str__),
    __repr__ = gateway.interp2app(descr__repr__),
    __class__ = GetSetProperty(descr__class__, descr_set___class__),
    __doc__ = '''The most base type''',
    __new__ = gateway.interp2app(descr__new__),
    __hash__ = gateway.interp2app(default_identity_hash),
    __reduce_ex__ = gateway.interp2app(descr__reduce_ex__),
    __reduce__ = gateway.interp2app(descr__reduce__),
    __format__ = gateway.interp2app(descr___format__),
    __subclasshook__ = gateway.interp2app(descr___subclasshook__,
                                          as_classmethod=True),
    __init__ = gateway.interp2app(descr__init__),
    )
Exemple #10
0
                                                  encoding, errors)
        if space.is_w(w_unicodetype, space.w_unicode):
            return w_value

    if space.config.objspace.std.withropeunicode:
        assert isinstance(w_value, W_RopeUnicodeObject)
        w_newobj = space.allocate_instance(W_RopeUnicodeObject, w_unicodetype)
        W_RopeUnicodeObject.__init__(w_newobj, w_value._node)
        return w_newobj

    assert isinstance(w_value, W_UnicodeObject)
    w_newobj = space.allocate_instance(W_UnicodeObject, w_unicodetype)
    W_UnicodeObject.__init__(w_newobj, w_value._value)
    return w_newobj

# ____________________________________________________________

unicode_typedef = StdTypeDef("unicode", basestring_typedef,
    __new__ = gateway.interp2app(descr_new_),
    __doc__ = '''unicode(string [, encoding[, errors]]) -> object

Create a new Unicode object from the given encoded string.
encoding defaults to the current default string encoding.
errors can be 'strict', 'replace' or 'ignore' and defaults to 'strict'.'''
    )

unicode_typedef.registermethods(globals())

unitypedef = unicode_typedef
register_all(vars(), globals())
Exemple #11
0
from pypy.objspace.std.stdtypedef import StdTypeDef


basestring_typedef = StdTypeDef("basestring",
    __doc__ =  ("basestring cannot be instantiated; "
                "it is the base for str and unicode.")
    )
Exemple #12
0
set_update                      = SMM('update', 1, varargs_w=True,
                                      doc='Update the set, adding elements'
                                          ' from all others.')
set_reduce                      = SMM('__reduce__',1,
                                      doc='Return state information for'
                                          ' pickling.')
# 2.6 methods
set_isdisjoint                  = SMM('isdisjoint', 2,
                                      doc='Return True if two sets have a'
                                          ' null intersection.')

register_all(vars(), globals())

def descr__new__(space, w_settype, __args__):
    from pypy.objspace.std.setobject import W_SetObject, newset
    w_obj = space.allocate_instance(W_SetObject, w_settype)
    W_SetObject.__init__(w_obj, space)
    return w_obj

set_typedef = StdTypeDef("set",
    __doc__ = """set(iterable) --> set object

Build an unordered collection.""",
    __new__ = gateway.interp2app(descr__new__),
    __hash__ = None,
    )

set_typedef.registermethods(globals())

setiter_typedef = StdTypeDef("setiterator")
    W_ComplexObject.__init__(w_obj, realval, imagval)
    return w_obj

def complexwprop(name):
    def fget(space, w_obj):
        from pypy.objspace.std.complexobject import W_ComplexObject
        if not isinstance(w_obj, W_ComplexObject):
            raise OperationError(space.w_TypeError,
                                 space.wrap("descriptor is for 'complex'"))
        return space.newfloat(getattr(w_obj, name))
    return GetSetProperty(fget)
    
def descr___getnewargs__(space,  w_self):
    from pypy.objspace.std.complexobject import W_ComplexObject
    assert isinstance(w_self, W_ComplexObject)
    return space.newtuple([space.newcomplex(w_self.realval,w_self.imagval)]) 
    
complex_typedef = StdTypeDef("complex",
    __doc__ = """complex(real[, imag]) -> complex number
        
Create a complex number from a real part and an optional imaginary part.
This is equivalent to (real + imag*1j) where imag defaults to 0.""",
    __new__ = newmethod(descr__new__),
    __getnewargs__ = newmethod(descr___getnewargs__),
    real = complexwprop('realval'),
    imag = complexwprop('imagval'),
    )

complex_typedef.custom_hash = True
complex_typedef.registermethods(globals())
Exemple #14
0
                        ' the list')

def list_reversed__ANY(space, w_list):
    from pypy.objspace.std.iterobject import W_ReverseSeqIterObject
    return W_ReverseSeqIterObject(space, w_list, -1)

register_all(vars(), globals())

# ____________________________________________________________

def descr__new__(space, w_listtype, __args__):
    from pypy.objspace.std.listobject import W_ListObject
    w_obj = space.allocate_instance(W_ListObject, w_listtype)
    w_obj.clear(space)
    return w_obj

# ____________________________________________________________

list_typedef = StdTypeDef("list",
    __doc__ = '''list() -> new list
list(sequence) -> new list initialized from sequence's items''',
    __new__ = gateway.interp2app(descr__new__),
    __hash__ = None,
    )
list_typedef.registermethods(globals())

# ____________________________________________________________

def get_list_index(space, w_index):
    return space.getindex_w(w_index, space.w_IndexError, "list index")
Exemple #15
0

# ____________________________________________________________


def slicewprop(name):
    def fget(space, w_obj):
        from pypy.objspace.std.sliceobject import W_SliceObject
        if not isinstance(w_obj, W_SliceObject):
            raise OperationError(space.w_TypeError,
                                 space.wrap("descriptor is for 'slice'"))
        return getattr(w_obj, name)

    return GetSetProperty(fget)


slice_typedef = StdTypeDef(
    "slice",
    __doc__='''slice([start,] stop[, step])

Create a slice object.  This is used for extended slicing (e.g. a[0:10:2]).''',
    __new__=gateway.interp2app(descr__new__),
    __hash__=None,
    __reduce__=gateway.interp2app(descr__reduce__),
    start=slicewprop('w_start'),
    stop=slicewprop('w_stop'),
    step=slicewprop('w_step'),
)
slice_typedef.acceptable_as_base_class = False
slice_typedef.registermethods(globals())
Exemple #16
0
                                          ' one of the sets.)')
frozenset_union                 = SMM('union', 2,
                                      doc='Return the union of two sets as a'
                                          ' new set.\n\n(i.e. all elements'
                                          ' that are in either set.)')
frozenset_reduce                = SMM('__reduce__',1,
                                      doc='Return state information for'
                                          ' pickling.')

register_all(vars(), globals())

def descr__frozenset__new__(space, w_frozensettype, w_iterable=NoneNotWrapped):
    from pypy.objspace.std.setobject import W_FrozensetObject
    from pypy.objspace.std.setobject import _is_frozenset_exact
    if (space.is_w(w_frozensettype, space.w_frozenset) and
        _is_frozenset_exact(w_iterable)):
        return w_iterable
    w_obj = space.allocate_instance(W_FrozensetObject, w_frozensettype)
    W_FrozensetObject.__init__(w_obj, space, None)

    return w_obj

frozenset_typedef = StdTypeDef("frozenset",
    __doc__ = """frozenset(iterable) --> frozenset object

Build an immutable unordered collection.""",
    __new__ = newmethod(descr__frozenset__new__),
    )

frozenset_typedef.registermethods(globals())
Exemple #17
0
            raise OperationError(space.w_ValueError, space.wrap(
                "non-hexadecimal number found in fromhex() arg at position %d" % i))

        top = _hex_digit_to_int(hexstring[i])
        if top == -1:
            raise OperationError(space.w_ValueError, space.wrap(
                "non-hexadecimal number found in fromhex() arg at position %d" % i))
        bot = _hex_digit_to_int(hexstring[i+1])
        if bot == -1:
            raise OperationError(space.w_ValueError, space.wrap(
                "non-hexadecimal number found in fromhex() arg at position %d" % (i+1,)))
        data.append(chr(top*16 + bot))

    # in CPython bytearray.fromhex is a staticmethod, so
    # we ignore w_type and always return a bytearray
    return new_bytearray(space, space.w_bytearray, data)

# ____________________________________________________________

bytearray_typedef = StdTypeDef("bytearray",
    __doc__ = '''bytearray() -> an empty bytearray
bytearray(sequence) -> bytearray initialized from sequence\'s items

If the argument is a bytearray, the return value is the same object.''',
    __new__ = gateway.interp2app(descr__new__),
    __hash__ = None,
    __reduce__ = gateway.interp2app(descr_bytearray__reduce__),
    fromhex = gateway.interp2app(descr_fromhex, as_classmethod=True)
    )
bytearray_typedef.registermethods(globals())
Exemple #18
0
        b = space.bigint_w(self)
        b = b.lshift(3).or_(rbigint.fromint(tag))
        return space.newlong_from_rbigint(b)

    def unwrap(w_self, space):  #YYYYYY
        return w_self.longval()

    def int(self, space):
        raise NotImplementedError


long_typedef = StdTypeDef(
    "long",
    __doc__='''long(x[, base]) -> integer

Convert a string or number to a long integer, if possible.  A floating
point argument will be truncated towards zero (this does not include a
string representation of a floating point number!)  When converting a
string, use the optional base.  It is an error to supply a base when
converting a non-string.''',
    __new__=interp2app(descr__new__),
    conjugate=interp2app(descr_conjugate),
    numerator=typedef.GetSetProperty(descr_get_numerator),
    denominator=typedef.GetSetProperty(descr_get_denominator),
    real=typedef.GetSetProperty(descr_get_real),
    imag=typedef.GetSetProperty(descr_get_imag),
    bit_length=interp2app(bit_length),
    __int__=interpindirect2app(W_AbstractLongObject.int),
)
long_typedef.registermethods(globals())
Exemple #19
0
                             space.wrap("__abstractmethods__"))
    w_type.set_abstract(False)


def descr___subclasses__(space, w_type):
    """Return the list of immediate subclasses."""
    w_type = _check(space, w_type)
    return space.newlist(w_type.get_subclasses())


# ____________________________________________________________

type_typedef = StdTypeDef(
    "type",
    __new__=gateway.interp2app(descr__new__),
    __name__=GetSetProperty(descr_get__name__, descr_set__name__),
    __bases__=GetSetProperty(descr_get__bases__, descr_set__bases__),
    __base__=GetSetProperty(descr__base),
    __mro__=GetSetProperty(descr_get__mro__),
    __dict__=GetSetProperty(descr_get_dict),
    __doc__=GetSetProperty(descr__doc),
    mro=gateway.interp2app(descr_mro),
    __flags__=GetSetProperty(descr__flags),
    __module__=GetSetProperty(descr_get__module, descr_set__module),
    __abstractmethods__=GetSetProperty(descr_get___abstractmethods__,
                                       descr_set___abstractmethods__,
                                       descr_del___abstractmethods__),
    __subclasses__=gateway.interp2app(descr___subclasses__),
    __weakref__=weakref_descr,
)
Exemple #20
0
    """
    from pypy.objspace.std.iterobject import W_ReverseSeqIterObject

    assert isinstance(w_self, W_ReverseSeqIterObject)
    from pypy.interpreter.mixedmodule import MixedModule

    w_mod = space.getbuiltinmodule("_pickle_support")
    mod = space.interp_w(MixedModule, w_mod)
    new_inst = mod.get("reverseseqiter_new")
    tup = [w_self.w_seq, space.wrap(w_self.index)]
    return space.newtuple([new_inst, space.newtuple(tup)])


# ____________________________________________________________
iter_typedef = StdTypeDef(
    "sequenceiterator",
    __doc__="""iter(collection) -> iterator
iter(callable, sentinel) -> iterator

Get an iterator from an object.  In the first form, the argument must
supply its own iterator, or be a sequence.
In the second form, the callable is called until it returns the sentinel.""",
    __reduce__=gateway.interp2app(descr_seqiter__reduce__),
)
iter_typedef.acceptable_as_base_class = False

reverse_iter_typedef = StdTypeDef(
    "reversesequenceiterator", __reduce__=gateway.interp2app(descr_reverseseqiter__reduce__)
)
reverse_iter_typedef.acceptable_as_base_class = False
Exemple #21
0
                 ' itself and another.')
set_reduce = SMM('__reduce__',
                 1,
                 doc='Return state information for'
                 ' pickling.')

register_all(vars(), globals())


def descr__new__(space, w_settype, __args__):
    from pypy.objspace.std.setobject import W_SetObject
    w_obj = space.allocate_instance(W_SetObject, w_settype)
    W_SetObject.__init__(w_obj, space, None)
    return w_obj


set_typedef = StdTypeDef(
    "set",
    __doc__="""set(iterable) --> set object

Build an unordered collection.""",
    __new__=newmethod(
        descr__new__,
        unwrap_spec=[gateway.ObjSpace, gateway.W_Root, gateway.Arguments]),
    __hash__=no_hash_descr,
)

set_typedef.registermethods(globals())

setiter_typedef = StdTypeDef("setiterator")
Exemple #22
0

def descr_typecode(space, self):
    return space.wrap(self.typecode)


class W_ArrayBase(W_Object):
    @staticmethod
    def register(typeorder):
        typeorder[W_ArrayBase] = []


W_ArrayBase.typedef = StdTypeDef(
    'array',
    __new__=interp2app(w_array),
    __module__='array',
    itemsize=GetSetProperty(descr_itemsize),
    typecode=GetSetProperty(descr_typecode),
    __weakref__=make_weakref_descr(W_ArrayBase),
)
W_ArrayBase.typedef.registermethods(globals())


class TypeCode(object):
    def __init__(self, itemtype, unwrap, canoverflow=False, signed=False):
        self.itemtype = itemtype
        self.bytes = rffi.sizeof(itemtype)
        #self.arraytype = lltype.GcArray(itemtype)
        self.arraytype = lltype.Array(itemtype, hints={'nolength': True})
        self.unwrap = unwrap
        self.signed = signed
        self.canoverflow = canoverflow
Exemple #23
0
                space.wrap(
                    "non-hexadecimal number found in fromhex() arg at position %d"
                    % i))
        bot = _hex_digit_to_int(hexstring[i + 1])
        if bot == -1:
            raise OperationError(
                space.w_ValueError,
                space.wrap(
                    "non-hexadecimal number found in fromhex() arg at position %d"
                    % (i + 1, )))
        data.append(chr(top * 16 + bot))

    # in CPython bytearray.fromhex is a staticmethod, so
    # we ignore w_type and always return a bytearray
    return new_bytearray(space, space.w_bytearray, data)


# ____________________________________________________________

bytearray_typedef = StdTypeDef(
    "bytearray",
    __doc__='''bytearray() -> an empty bytearray
bytearray(sequence) -> bytearray initialized from sequence\'s items

If the argument is a bytearray, the return value is the same object.''',
    __new__=gateway.interp2app(descr__new__),
    __hash__=None,
    __reduce__=gateway.interp2app(descr_bytearray__reduce__),
    fromhex=gateway.interp2app(descr_fromhex, as_classmethod=True))
bytearray_typedef.registermethods(globals())
Exemple #24
0
from pypy.interpreter import gateway
from pypy.objspace.std.stdtypedef import StdTypeDef
from pypy.objspace.std.inttype import int_typedef

def descr__new__(space, w_booltype, w_obj=None):
    space.w_bool.check_user_subclass(w_booltype)
    if space.is_true(w_obj):
        return space.w_True
    else:
        return space.w_False

# ____________________________________________________________

bool_typedef = StdTypeDef("bool", int_typedef,
    __doc__ = '''bool(x) -> bool

Returns True when the argument x is true, False otherwise.
The builtins True and False are the only two instances of the class bool.
The class bool is a subclass of the class int, and cannot be subclassed.''',
    __new__ = gateway.interp2app(descr__new__),
    )
bool_typedef.acceptable_as_base_class = False
Exemple #25
0
    return (space.float_w(space.float(w_complex)), 0.0)


def complexwprop(name):
    def fget(space, w_obj):
        from pypy.objspace.std.complexobject import W_ComplexObject
        if not isinstance(w_obj, W_ComplexObject):
            raise OperationError(space.w_TypeError,
                                 space.wrap("descriptor is for 'complex'"))
        return space.newfloat(getattr(w_obj, name))
    return GetSetProperty(fget)

def descr___getnewargs__(space,  w_self):
    from pypy.objspace.std.complexobject import W_ComplexObject
    assert isinstance(w_self, W_ComplexObject)
    return space.newtuple([space.newfloat(w_self.realval),
                           space.newfloat(w_self.imagval)])

complex_typedef = StdTypeDef("complex",
    __doc__ = """complex(real[, imag]) -> complex number

Create a complex number from a real part and an optional imaginary part.
This is equivalent to (real + imag*1j) where imag defaults to 0.""",
    __new__ = interp2app(descr__new__),
    __getnewargs__ = interp2app(descr___getnewargs__),
    real = complexwprop('realval'),
    imag = complexwprop('imagval'),
    )

complex_typedef.registermethods(globals())
Exemple #26
0
def descr__new__(space, w_dicttype, __args__):
    from pypy.objspace.std.dictmultiobject import W_DictMultiObject
    w_obj = W_DictMultiObject.allocate_and_init_instance(space, w_dicttype)
    return w_obj

# ____________________________________________________________

dict_typedef = StdTypeDef("dict",
    __doc__ = '''dict() -> new empty dictionary.
dict(mapping) -> new dictionary initialized from a mapping object\'s
    (key, value) pairs.
dict(seq) -> new dictionary initialized as if via:
    d = {}
    for k, v in seq:
        d[k] = v
dict(**kwargs) -> new dictionary initialized with the name=value pairs
    in the keyword argument list.  For example:  dict(one=1, two=2)''',
    __new__ = gateway.interp2app(descr__new__),
    __hash__ = None,
    __repr__ = gateway.interp2app(descr_repr),
    fromkeys = gateway.interp2app(descr_fromkeys, as_classmethod=True),
    )
dict_typedef.registermethods(globals())

# ____________________________________________________________

def descr_dictiter__reduce__(w_self, space):
    """
    This is a slightly special case of pickling.
    Since iteration over a dict is a bit hairy,
Exemple #27
0
def descr__new__(space, w_dicttype, __args__):
    from pypy.objspace.std.dictmultiobject import W_DictMultiObject
    w_obj = W_DictMultiObject.allocate_and_init_instance(space, w_dicttype)
    return w_obj


# ____________________________________________________________

dict_typedef = StdTypeDef(
    "dict",
    __doc__='''dict() -> new empty dictionary.
dict(mapping) -> new dictionary initialized from a mapping object\'s
    (key, value) pairs.
dict(seq) -> new dictionary initialized as if via:
    d = {}
    for k, v in seq:
        d[k] = v
dict(**kwargs) -> new dictionary initialized with the name=value pairs
    in the keyword argument list.  For example:  dict(one=1, two=2)''',
    __new__=gateway.interp2app(descr__new__),
    __hash__=None,
    __repr__=gateway.interp2app(descr_repr),
    fromkeys=gateway.interp2app(descr_fromkeys, as_classmethod=True),
)
dict_typedef.registermethods(globals())

# ____________________________________________________________


def descr_dictiter__reduce__(w_self, space):
    """
    This is a slightly special case of pickling.
Exemple #28
0
register_all(vars(), globals())

# ____________________________________________________________


@unwrap_spec(w_object=WrappedDefault(""))
def descr__new__(space, w_stringtype, w_object):
    # NB. the default value of w_object is really a *wrapped* empty string:
    #     there is gateway magic at work
    from pypy.objspace.std.stringobject import W_StringObject
    w_obj = space.str(w_object)
    if space.is_w(w_stringtype, space.w_str):
        return w_obj  # XXX might be reworked when space.str() typechecks
    value = space.str_w(w_obj)
    w_obj = space.allocate_instance(W_StringObject, w_stringtype)
    W_StringObject.__init__(w_obj, value)
    return w_obj


# ____________________________________________________________

str_typedef = StdTypeDef("str",
                         basestring_typedef,
                         __new__=interp2app(descr__new__),
                         __doc__='''str(object) -> string

Return a nice string representation of the object.
If the argument is a string, the return value is the same object.''')

str_typedef.registermethods(globals())
Exemple #29
0
    while i < length and s[i].isspace():
        i += 1
    if i != length:
        raise OperationError(space.w_ValueError,
                             space.wrap("invalid hex string"))
    w_float = space.wrap(sign * value)
    return space.call_function(w_cls, w_float)

def descr_get_real(space, w_obj):
    return space.float(w_obj)

def descr_get_imag(space, w_obj):
    return space.wrap(0.0)

# ____________________________________________________________

float_typedef = StdTypeDef("float",
    __doc__ = '''float(x) -> floating point number

Convert a string or number to a floating point number, if possible.''',
    __new__ = gateway.interp2app(descr__new__),
    __getformat__ = gateway.interp2app(descr___getformat__,
                                       as_classmethod=True),
    fromhex = gateway.interp2app(descr_fromhex,
                                 as_classmethod=True),
    conjugate = gateway.interp2app(descr_conjugate),
    real = typedef.GetSetProperty(descr_get_real),
    imag = typedef.GetSetProperty(descr_get_imag),
)
float_typedef.registermethods(globals())
Exemple #30
0
    if space.is_true(space.gt(space.wrap(w_self.index), w_length)):
        w_len = space.wrap(0)
        w_self.w_seq = None
    else:
        w_len = space.wrap(index)
    if space.is_true(space.lt(w_len, space.wrap(0))):
        w_len = space.wrap(0)
    return w_len


# ____________________________________________________________
iter_typedef = StdTypeDef(
    "sequenceiterator",
    __doc__='''iter(collection) -> iterator
iter(callable, sentinel) -> iterator

Get an iterator from an object.  In the first form, the argument must
supply its own iterator, or be a sequence.
In the second form, the callable is called until it returns the sentinel.''',
    __reduce__=gateway.interp2app(descr_seqiter__reduce__),
    __length_hint__=gateway.interp2app(descr_seqiter__length_hint__),
)
iter_typedef.acceptable_as_base_class = False

reverse_iter_typedef = StdTypeDef(
    "reversesequenceiterator",
    __reduce__=gateway.interp2app(descr_reverseseqiter__reduce__),
    __length_hint__=gateway.interp2app(descr_reverseseqiter__length_hint__),
)
reverse_iter_typedef.acceptable_as_base_class = False
Exemple #31
0
        return one == two

    def immutable_unique_id(self, space):
        if self.user_overridden_class:
            return None
        from rpython.rlib.longlong2float import float2longlong
        from pypy.objspace.std.model import IDTAG_FLOAT as tag
        val = float2longlong(space.float_w(self))
        b = rbigint.fromrarith_int(val)
        b = b.lshift(3).or_(rbigint.fromint(tag))
        return space.newlong_from_rbigint(b)

    def int(self, space):
        raise NotImplementedError


float_typedef = StdTypeDef(
    "float",
    __doc__='''float(x) -> floating point number

Convert a string or number to a floating point number, if possible.''',
    __new__=interp2app(descr__new__),
    __getformat__=interp2app(descr___getformat__, as_classmethod=True),
    fromhex=interp2app(descr_fromhex, as_classmethod=True),
    conjugate=interp2app(descr_conjugate),
    real=typedef.GetSetProperty(descr_get_real),
    imag=typedef.GetSetProperty(descr_get_imag),
    __int__=interpindirect2app(W_AbstractFloatObject.int),
)
float_typedef.registermethods(globals())
Exemple #32
0
                                          ' one of the sets.)')
frozenset_union                 = SMM('union', 2,
                                      doc='Return the union of two sets as a'
                                          ' new set.\n\n(i.e. all elements'
                                          ' that are in either set.)')
frozenset_reduce                = SMM('__reduce__',1,
                                      doc='Return state information for'
                                          ' pickling.')

register_all(vars(), globals())

def descr__frozenset__new__(space, w_frozensettype, w_iterable=NoneNotWrapped):
    from pypy.objspace.std.setobject import W_FrozensetObject
    from pypy.objspace.std.setobject import _is_frozenset_exact
    if _is_frozenset_exact(w_iterable):
        return w_iterable
    w_obj = space.allocate_instance(W_FrozensetObject, w_frozensettype)
    W_FrozensetObject.__init__(w_obj, space, None)

    return w_obj

frozenset_typedef = StdTypeDef("frozenset",
    __doc__ = """frozenset(iterable) --> frozenset object

Build an immutable unordered collection.""",
    __new__ = newmethod(descr__frozenset__new__),
    )

frozenset_typedef.custom_hash = True
frozenset_typedef.registermethods(globals())
        w_obj = space.allocate_instance(W_RopeObject, w_stringtype)
        W_RopeObject.__init__(w_obj, rope.LiteralStringNode(value))
        return w_obj
    else:
        w_obj = space.allocate_instance(W_StringObject, w_stringtype)
        W_StringObject.__init__(w_obj, value)
        return w_obj


# ____________________________________________________________

str_typedef = StdTypeDef(
    "str",
    basestring_typedef,
    __new__=gateway.interp2app(descr__new__),
    __doc__="""str(object) -> string

Return a nice string representation of the object.
If the argument is a string, the return value is the same object.""",
)

str_typedef.registermethods(globals())

# ____________________________________________________________

# Helpers for several string implementations


@specialize.argtype(0)
def stringendswith(u_self, suffix, start, end):
    begin = end - len(suffix)
Exemple #34
0
def descr_get_imag(space, w_obj):
    return space.newlong(0)

def bit_length(space, w_obj):
    bigint = space.bigint_w(w_obj)
    try:
        return space.wrap(bigint.bit_length())
    except OverflowError:
        raise OperationError(space.w_OverflowError,
                             space.wrap("too many digits in integer"))

# ____________________________________________________________

long_typedef = StdTypeDef("long",
    __doc__ = '''long(x[, base]) -> integer

Convert a string or number to a long integer, if possible.  A floating
point argument will be truncated towards zero (this does not include a
string representation of a floating point number!)  When converting a
string, use the optional base.  It is an error to supply a base when
converting a non-string.''',
    __new__ = gateway.interp2app(descr__new__),
    conjugate = gateway.interp2app(descr_conjugate),
    numerator = typedef.GetSetProperty(descr_get_numerator),
    denominator = typedef.GetSetProperty(descr_get_denominator),
    real = typedef.GetSetProperty(descr_get_real),
    imag = typedef.GetSetProperty(descr_get_imag),
    bit_length = gateway.interp2app(bit_length),
)
long_typedef.registermethods(globals())
Exemple #35
0
def complexwprop(name):
    def fget(space, w_obj):
        from pypy.objspace.std.complexobject import W_ComplexObject
        if not isinstance(w_obj, W_ComplexObject):
            raise OperationError(space.w_TypeError,
                                 space.wrap("descriptor is for 'complex'"))
        return space.newfloat(getattr(w_obj, name))

    return GetSetProperty(fget)


def descr___getnewargs__(space, w_self):
    from pypy.objspace.std.complexobject import W_ComplexObject
    assert isinstance(w_self, W_ComplexObject)
    return space.newtuple([space.newcomplex(w_self.realval, w_self.imagval)])


complex_typedef = StdTypeDef(
    "complex",
    __doc__="""complex(real[, imag]) -> complex number
        
Create a complex number from a real part and an optional imaginary part.
This is equivalent to (real + imag*1j) where imag defaults to 0.""",
    __new__=newmethod(descr__new__),
    __getnewargs__=newmethod(descr___getnewargs__),
    real=complexwprop('realval'),
    imag=complexwprop('imagval'),
)

complex_typedef.registermethods(globals())
Exemple #36
0
from pypy.interpreter.gateway import interp2app, unwrap_spec, WrappedDefault
from pypy.objspace.std.stdtypedef import StdTypeDef
from pypy.objspace.std.inttype import int_typedef

@unwrap_spec(w_obj = WrappedDefault(False))
def descr__new__(space, w_booltype, w_obj):
    space.w_bool.check_user_subclass(w_booltype)
    if space.is_true(w_obj):
        return space.w_True
    else:
        return space.w_False

# ____________________________________________________________

bool_typedef = StdTypeDef("bool", int_typedef,
    __doc__ = '''bool(x) -> bool

Returns True when the argument x is true, False otherwise.
The builtins True and False are the only two instances of the class bool.
The class bool is a subclass of the class int, and cannot be subclassed.''',
    __new__ = interp2app(descr__new__),
    )
bool_typedef.acceptable_as_base_class = False
Exemple #37
0
from pypy.objspace.std.stdtypedef import StdTypeDef

# ____________________________________________________________

none_typedef = StdTypeDef("NoneType", )
none_typedef.acceptable_as_base_class = False