예제 #1
0
파일: tupletype.py 프로젝트: Debug-Orz/Sypy
                  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())
예제 #2
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())
예제 #3
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())
예제 #4
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())
예제 #5
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())
예제 #6
0
파일: slicetype.py 프로젝트: njues/Sypy

# ____________________________________________________________


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())
예제 #7
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())
예제 #8
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")
예제 #9
0
파일: complextype.py 프로젝트: charred/pypy
    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())
예제 #10
0
파일: dicttype.py 프로젝트: purepython/pypy
    "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,
    we do the following:
    - create a clone of the dict iterator
    - run it to the original position
    - collect all remaining elements into a list
    At unpickling time, we just use that list
    and create an iterator on it.
    This is of course not the standard way.
예제 #11
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())
예제 #12
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())
예제 #13
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())
예제 #14
0
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,
    we do the following:
    - create a clone of the dict iterator
    - run it to the original position
    - collect all remaining elements into a list
    At unpickling time, we just use that list
    and create an iterator on it.
    This is of course not the standard way.
예제 #15
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())
예제 #16
0
파일: stringtype.py 프로젝트: sota/pypy-old
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())
예제 #17
0
        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)
    if begin < start:
        return False
    for i in range(len(suffix)):
        if u_self[begin + i] != suffix[i]:
            return False
    return True
예제 #18
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())
예제 #19
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())
예제 #20
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())
예제 #21
0
파일: unicodetype.py 프로젝트: njues/Sypy
                                                  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())