Example #1
0
class str_methods:
    from pypy.objspace.std import stringtype
    W_RopeUnicodeObject = W_RopeUnicodeObject
    from pypy.objspace.std.ropeobject import W_RopeObject

    def str_strip__Rope_RopeUnicode(space, w_self, w_chars):
        return space.call_method(unicode_from_string(space, w_self), 'strip',
                                 w_chars)

    def str_lstrip__Rope_RopeUnicode(space, w_self, w_chars):
        return space.call_method(unicode_from_string(space, w_self), 'lstrip',
                                 w_chars)

    def str_rstrip__Rope_RopeUnicode(space, w_self, w_chars):
        return space.call_method(unicode_from_string(space, w_self), 'rstrip',
                                 w_chars)

    def str_count__Rope_RopeUnicode_ANY_ANY(space, w_self, w_substr, w_start,
                                            w_end):
        return space.call_method(unicode_from_string(space, w_self), 'count',
                                 w_substr, w_start, w_end)

    def str_find__Rope_RopeUnicode_ANY_ANY(space, w_self, w_substr, w_start,
                                           w_end):
        return space.call_method(unicode_from_string(space, w_self), 'find',
                                 w_substr, w_start, w_end)

    def str_rfind__Rope_RopeUnicode_ANY_ANY(space, w_self, w_substr, w_start,
                                            w_end):
        return space.call_method(unicode_from_string(space, w_self), 'rfind',
                                 w_substr, w_start, w_end)

    def str_index__Rope_RopeUnicode_ANY_ANY(space, w_self, w_substr, w_start,
                                            w_end):
        return space.call_method(unicode_from_string(space, w_self), 'index',
                                 w_substr, w_start, w_end)

    def str_rindex__Rope_RopeUnicode_ANY_ANY(space, w_self, w_substr, w_start,
                                             w_end):
        return space.call_method(unicode_from_string(space, w_self), 'rindex',
                                 w_substr, w_start, w_end)

    def str_replace__Rope_RopeUnicode_RopeUnicode_ANY(space, w_self, w_old,
                                                      w_new, w_maxsplit):
        return space.call_method(unicode_from_string(space, w_self), 'replace',
                                 w_old, w_new, w_maxsplit)

    def str_split__Rope_RopeUnicode_ANY(space, w_self, w_delim, w_maxsplit):
        return space.call_method(unicode_from_string(space, w_self), 'split',
                                 w_delim, w_maxsplit)

    def str_rsplit__Rope_RopeUnicode_ANY(space, w_self, w_delim, w_maxsplit):
        return space.call_method(unicode_from_string(space, w_self), 'rsplit',
                                 w_delim, w_maxsplit)

    register_all(vars(), stringtype)
Example #2
0
                del currently_in_repr[set_id]
            except:
                pass
""", filename=__file__)

setrepr = app.interphook("setrepr")

def repr__Set(space, w_set):
    ec = space.getexecutioncontext()
    w_currently_in_repr = ec._py_repr
    if w_currently_in_repr is None:
        w_currently_in_repr = ec._py_repr = space.newdict()
    return setrepr(space, w_currently_in_repr, w_set)

repr__Frozenset = repr__Set

app = gateway.applevel("""
    def reduce__Set(s):
        dict = getattr(s,'__dict__', None)
        return (s.__class__, (tuple(s),), dict)

""", filename=__file__)

set_reduce__Set = app.interphook('reduce__Set')
frozenset_reduce__Frozenset = app.interphook('reduce__Set')

from pypy.objspace.std import frozensettype
from pypy.objspace.std import settype

register_all(vars(), settype, frozensettype)
Example #3
0
    if right:
        while rpos > lpos and u_self[rpos - 1] in u_chars:
            rpos -= 1
        assert rpos >= 0

    return new_bytearray(space, space.w_bytearray, u_self[lpos:rpos])

# __________________________________________________________
# Buffer interface

class BytearrayBuffer(RWBuffer):
    def __init__(self, data):
        self.data = data

    def getlength(self):
        return len(self.data)

    def getitem(self, index):
        return self.data[index]

    def setitem(self, index, char):
        self.data[index] = char

def buffer__Bytearray(space, self):
    b = BytearrayBuffer(self.data)
    return space.wrap(b)

from pypy.objspace.std import bytearraytype
register_all(vars(), bytearraytype)
Example #4
0
        return space.w_True
    if space.eq_w(w_slice1.w_start, w_slice2.w_start) and \
        space.eq_w(w_slice1.w_stop, w_slice2.w_stop) and \
        space.eq_w(w_slice1.w_step, w_slice2.w_step):
        return space.w_True
    else:
        return space.w_False

def lt__Slice_Slice(space, w_slice1, w_slice2):
    if space.is_w(w_slice1, w_slice2):
        return space.w_False   # see comments in eq__Slice_Slice()
    if space.eq_w(w_slice1.w_start, w_slice2.w_start):
        if space.eq_w(w_slice1.w_stop, w_slice2.w_stop):
            return space.lt(w_slice1.w_step, w_slice2.w_step)
        else:
            return space.lt(w_slice1.w_stop, w_slice2.w_stop)
    else:
        return space.lt(w_slice1.w_start, w_slice2.w_start)

# indices impl

def slice_indices__Slice_ANY(space, w_slice, w_length):
    length = space.getindex_w(w_length, space.w_OverflowError)
    start, stop, step = w_slice.indices3(space, length)
    return space.newtuple([space.wrap(start), space.wrap(stop),
                           space.wrap(step)])

# register all methods
from pypy.objspace.std import slicetype
register_all(vars(), slicetype)
Example #5
0
        w_frozen = space.w_False
    else:
        w_frozen = space.w_True
    w_tup = space.newtuple(items_w)
    return tuple_to_set(space, w_tup, w_frozen)
register(TYPE_SET + TYPE_FROZENSET, unmarshal_set_frozenset)

# dispatching for all not directly dispatched types
def marshal_w__ANY(space, w_obj, m):
    w_type = space.type(w_obj)
    for name, func in handled_by_any:
        w_t = space.builtin.get(name)
        if space.is_true(space.issubtype(w_type, w_t)):
            func(space, w_obj, m)
            return

    # any unknown object implementing the buffer protocol is
    # accepted and encoded as a plain string
    try:
        s = space.bufferstr_w(w_obj)
    except OperationError, e:
        if not e.match(space, space.w_TypeError):
            raise
    else:
        m.atom_str(TYPE_STRING, s)
        return

    raise_exception(space, "unmarshallable object")

register_all(vars())
Example #6
0
                    doc='L.count(value) -> integer -- return number of'
                        ' occurrences of value')
list_reverse  = SMM('reverse',1,
                    doc='L.reverse() -- reverse *IN PLACE*')
list_sort     = SMM('sort',   4, defaults=(None, None, False), argnames=['cmp', 'key', 'reverse'],
                    doc='L.sort(cmp=None, key=None, reverse=False) -- stable'
                        ' sort *IN PLACE*;\ncmp(x, y) -> -1, 0, 1')
list_reversed = SMM('__reversed__', 1,
                    doc='L.__reversed__() -- return a reverse iterator over'
                        ' 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__):
    if space.config.objspace.std.withmultilist:
        from pypy.objspace.std.listmultiobject import W_ListMultiObject
        w_obj = space.allocate_instance(W_ListMultiObject, w_listtype)
        W_ListMultiObject.__init__(w_obj, space)
    else:
        from pypy.objspace.std.listobject import W_ListObject
        w_obj = space.allocate_instance(W_ListObject, w_listtype)
        W_ListObject.__init__(w_obj, [])
    return w_obj

# ____________________________________________________________
Example #7
0
# ____________________________________________________________

def delegate_buf2str(space, w_strbuf):
    w_strbuf.force()
    return w_strbuf.w_str

def delegate_buf2unicode(space, w_strbuf):
    w_strbuf.force()
    return delegate_String2Unicode(space, w_strbuf.w_str)

def len__StringBuffer(space, w_self):
    return space.wrap(w_self.length)

def add__StringBuffer_String(space, w_self, w_other):
    if w_self.builder.getlength() != w_self.length:
        builder = StringBuilder()
        builder.append(w_self.force())
    else:
        builder = w_self.builder
    builder.append(w_other._value)
    return W_StringBufferObject(builder)

def str__StringBuffer(space, w_self):
    # you cannot get subclasses of W_StringBufferObject here
    assert type(w_self) is W_StringBufferObject
    return w_self

from pypy.objspace.std import stringtype
register_all(vars(), stringtype)
Example #8
0
                       filename=__file__)

setrepr = app.interphook("setrepr")


def repr__Set(space, w_set):
    ec = space.getexecutioncontext()
    w_currently_in_repr = ec._py_repr
    if w_currently_in_repr is None:
        w_currently_in_repr = ec._py_repr = space.newdict()
    return setrepr(space, w_currently_in_repr, w_set)


repr__Frozenset = repr__Set

app = gateway.applevel("""
    def reduce__Set(s):
        dict = getattr(s,'__dict__', None)
        return (s.__class__, (tuple(s),), dict)

""",
                       filename=__file__)

set_reduce__Set = app.interphook('reduce__Set')
frozenset_reduce__Frozenset = app.interphook('reduce__Set')

from pypy.objspace.std import frozensettype
from pypy.objspace.std import settype

register_all(vars(), settype, frozensettype)
Example #9
0
        elif self.typecode == "u":
            r = space.repr(array_tounicode__Array(space, self))
            s = "array('%s', %s)" % (self.typecode, space.str_w(r))
            return space.wrap(s)
        else:
            r = space.repr(array_tolist__Array(space, self))
            s = "array('%s', %s)" % (self.typecode, space.str_w(r))
            return space.wrap(s)

    mytype.w_class = W_Array

    # Annotator seems to mess up if the names are not unique
    name = 'ArrayType' + mytype.typecode
    W_Array.__name__ = 'W_' + name
    import re
    for n, f in locals().items():
        new, n = re.subn('_Array_', '_%s_' % name, n)
        if n > 0:
            f.__name__ = new

    from pypy.objspace.std.sliceobject import W_SliceObject
    from pypy.objspace.std.listobject import W_ListObject
    from pypy.objspace.std.unicodeobject import W_UnicodeObject
    register_all(locals(), globals())


for mytype in types.values():
    make_array(mytype)

register_all(locals(), globals())
Example #10
0
        mult += 82520 + z + z
    x += 97531
    return intmask(x)


def getnewargs__Tuple(space, w_tuple):
    return space.newtuple([space.newtuple(w_tuple.wrappeditems)])


def tuple_count__Tuple_ANY(space, w_tuple, w_obj):
    count = 0
    for w_item in w_tuple.wrappeditems:
        if space.eq_w(w_item, w_obj):
            count += 1
    return space.wrap(count)


def tuple_index__Tuple_ANY_ANY_ANY(space, w_tuple, w_obj, w_start, w_stop):
    length = len(w_tuple.wrappeditems)
    start, stop = slicetype.unwrap_start_stop(space, length, w_start, w_stop)
    for i in range(start, min(stop, length)):
        w_item = w_tuple.wrappeditems[i]
        if space.eq_w(w_item, w_obj):
            return space.wrap(i)
    raise OperationError(space.w_ValueError,
                         space.wrap("tuple.index(x): x not in tuple"))


from pypy.objspace.std import tupletype
register_all(vars(), tupletype)
Example #11
0
    return new_bytearray(space, space.w_bytearray, u_self[lpos:rpos])


# __________________________________________________________
# Buffer interface


class BytearrayBuffer(RWBuffer):
    def __init__(self, data):
        self.data = data

    def getlength(self):
        return len(self.data)

    def getitem(self, index):
        return self.data[index]

    def setitem(self, index, char):
        self.data[index] = char


def buffer__Bytearray(space, self):
    b = BytearrayBuffer(self.data)
    return space.wrap(b)


from pypy.objspace.std import bytearraytype

register_all(vars(), bytearraytype)
Example #12
0
repr__DictViewValues = repr__DictViewKeys

def and__DictViewKeys_DictViewKeys(space, w_dictview, w_otherview):
    w_set = space.call_function(space.w_set, w_dictview)
    space.call_method(w_set, "intersection_update", w_otherview)
    return w_set
and__DictViewKeys_settypedef = and__DictViewKeys_DictViewKeys
and__DictViewItems_DictViewItems = and__DictViewKeys_DictViewKeys
and__DictViewItems_settypedef = and__DictViewKeys_DictViewKeys

def or__DictViewKeys_DictViewKeys(space, w_dictview, w_otherview):
    w_set = space.call_function(space.w_set, w_dictview)
    space.call_method(w_set, "update", w_otherview)
    return w_set
or__DictViewKeys_settypedef = or__DictViewKeys_DictViewKeys
or__DictViewItems_DictViewItems = or__DictViewKeys_DictViewKeys
or__DictViewItems_settypedef = or__DictViewKeys_DictViewKeys

def xor__DictViewKeys_DictViewKeys(space, w_dictview, w_otherview):
    w_set = space.call_function(space.w_set, w_dictview)
    space.call_method(w_set, "symmetric_difference_update", w_otherview)
    return w_set
xor__DictViewKeys_settypedef = xor__DictViewKeys_DictViewKeys
xor__DictViewItems_DictViewItems = xor__DictViewKeys_DictViewKeys
xor__DictViewItems_settypedef = xor__DictViewKeys_DictViewKeys

# ____________________________________________________________

from pypy.objspace.std import dicttype
register_all(vars(), dicttype)
Example #13
0
        return space.w_True
    else:
        return space.w_False


def lt__Slice_Slice(space, w_slice1, w_slice2):
    if space.is_w(w_slice1, w_slice2):
        return space.w_False  # see comments in eq__Slice_Slice()
    if space.eq_w(w_slice1.w_start, w_slice2.w_start):
        if space.eq_w(w_slice1.w_stop, w_slice2.w_stop):
            return space.lt(w_slice1.w_step, w_slice2.w_step)
        else:
            return space.lt(w_slice1.w_stop, w_slice2.w_stop)
    else:
        return space.lt(w_slice1.w_start, w_slice2.w_start)


# indices impl


def slice_indices__Slice_ANY(space, w_slice, w_length):
    length = space.getindex_w(w_length, space.w_OverflowError)
    start, stop, step = w_slice.indices3(space, length)
    return space.newtuple([space.wrap(start), space.wrap(stop), space.wrap(step)])


# register all methods
from pypy.objspace.std import slicetype

register_all(vars(), slicetype)
Example #14
0
    else:
        w_den = w_exp
    # Try to return int.
    return space.newtuple([space.int(w_num), space.int(w_den)])


def float_is_integer__Float(space, w_float):
    v = w_float.floatval
    if not rfloat.isfinite(v):
        return space.w_False
    return space.wrap(math.floor(v) == v)


from pypy.objspace.std import floattype

register_all(vars(), floattype)


# pow delegation for negative 2nd arg
def pow_neg__Long_Long_None(space, w_int1, w_int2, thirdarg):
    w_float1 = delegate_Long2Float(space, w_int1)
    w_float2 = delegate_Long2Float(space, w_int2)
    return pow__Float_Float_ANY(space, w_float1, w_float2, thirdarg)


model.MM.pow.register(pow_neg__Long_Long_None,
                      W_LongObject,
                      W_LongObject,
                      W_NoneObject,
                      order=1)
Example #15
0
def str_format(x):
    return format_float(x, 'g', DTSF_STR_PRECISION)


def repr__Complex(space, w_complex):
    if w_complex.realval == 0 and copysign(1., w_complex.realval) == 1.:
        return space.wrap(repr_format(w_complex.imagval) + 'j')
    sign = (copysign(1., w_complex.imagval) == 1.
            or isnan(w_complex.imagval)) and '+' or ''
    return space.wrap('(' + repr_format(w_complex.realval) + sign +
                      repr_format(w_complex.imagval) + 'j)')


def str__Complex(space, w_complex):
    if w_complex.realval == 0 and copysign(1., w_complex.realval) == 1.:
        return space.wrap(str_format(w_complex.imagval) + 'j')
    sign = (copysign(1., w_complex.imagval) == 1.
            or isnan(w_complex.imagval)) and '+' or ''
    return space.wrap('(' + str_format(w_complex.realval) + sign +
                      str_format(w_complex.imagval) + 'j)')


def format__Complex_ANY(space, w_complex, w_format_spec):
    return newformat.run_formatter(space, w_format_spec, "format_complex",
                                   w_complex)


from pypy.objspace.std import complextype

register_all(vars(), complextype)
Example #16
0
def unicode_format__Unicode(space, w_unicode, __args__):
    return newformat.format_method(space, w_unicode, __args__, True)

def format__Unicode_ANY(space, w_unicode, w_format_spec):
    if not space.isinstance_w(w_format_spec, space.w_unicode):
        w_format_spec = space.call_function(space.w_unicode, w_format_spec)
    from pypy.objspace.std.unicodetype import unicode_from_object
    w_unicode = unicode_from_object(space, w_unicode)
    spec = space.unicode_w(w_format_spec)
    formatter = newformat.unicode_formatter(space, spec)
    return formatter.format_string(space.unicode_w(w_unicode))


from pypy.objspace.std import unicodetype
register_all(vars(), unicodetype)

# str.strip(unicode) needs to convert self to unicode and call unicode.strip we
# use the following magic to register strip_string_unicode as a String
# multimethod.

# XXX couldn't string and unicode _share_ the multimethods that make up their
# methods?

class str_methods:
    from pypy.objspace.std import stringtype
    W_UnicodeObject = W_UnicodeObject
    from pypy.objspace.std.stringobject import W_StringObject
    from pypy.objspace.std.ropeobject import W_RopeObject
    def str_strip__String_Unicode(space, w_self, w_chars):
        from pypy.objspace.std.unicodetype import unicode_from_string
Example #17
0
repr__DictViewValues = repr__DictViewKeys

def and__DictViewKeys_DictViewKeys(space, w_dictview, w_otherview):
    w_set = space.call_function(space.w_set, w_dictview)
    space.call_method(w_set, "intersection_update", w_otherview)
    return w_set
and__DictViewKeys_settypedef = and__DictViewKeys_DictViewKeys
and__DictViewItems_DictViewItems = and__DictViewKeys_DictViewKeys
and__DictViewItems_settypedef = and__DictViewKeys_DictViewKeys

def or__DictViewKeys_DictViewKeys(space, w_dictview, w_otherview):
    w_set = space.call_function(space.w_set, w_dictview)
    space.call_method(w_set, "update", w_otherview)
    return w_set
or__DictViewKeys_settypedef = or__DictViewKeys_DictViewKeys
or__DictViewItems_DictViewItems = or__DictViewKeys_DictViewKeys
or__DictViewItems_settypedef = or__DictViewKeys_DictViewKeys

def xor__DictViewKeys_DictViewKeys(space, w_dictview, w_otherview):
    w_set = space.call_function(space.w_set, w_dictview)
    space.call_method(w_set, "symmetric_difference_update", w_otherview)
    return w_set
xor__DictViewKeys_settypedef = xor__DictViewKeys_DictViewKeys
xor__DictViewItems_DictViewItems = xor__DictViewKeys_DictViewKeys
xor__DictViewItems_settypedef = xor__DictViewKeys_DictViewKeys

# ____________________________________________________________

from pypy.objspace.std import dicttype
register_all(vars(), dicttype)
Example #18
0
        # perform the sort
        sorter.sort()

        # reverse again
        if has_reverse:
            sorter.list.reverse()

    finally:
        # unwrap each item if needed
        if has_key:
            for i in range(sorter.listlength):
                w_obj = sorter.list[i]
                if isinstance(w_obj, KeyContainer):
                    sorter.list[i] = w_obj.w_item

        # check if the user mucked with the list during the sort
        mucked = len(w_list.wrappeditems) > 0

        # put the items back into the list
        w_list.wrappeditems = sorter.list

    if mucked:
        raise OperationError(space.w_ValueError,
                             space.wrap("list modified during sort"))

    return space.w_None


from pypy.objspace.std import listtype
register_all(vars(), listtype)
Example #19
0
        else:
            str = "".join([s[start + i * step] for i in range(sl)])
    return wrapstr(space, str)


def getslice__StringSlice_ANY_ANY(space, w_str, w_start, w_stop):
    length = w_str.stop - w_str.start
    start, stop = normalize_simple_slice(space, length, w_start, w_stop)
    sl = stop - start
    if sl == 0:
        return W_StringObject.EMPTY
    else:
        s = w_str.str
        start = w_str.start + start
        stop = w_str.start + stop
        return W_StringSliceObject(s, start, stop)


def len__StringSlice(space, w_str):
    return space.wrap(w_str.stop - w_str.start)


def str__StringSlice(space, w_str):
    if type(w_str) is W_StringSliceObject:
        return w_str
    return W_StringSliceObject(w_str.str, w_str.start, w_str.stop)


from pypy.objspace.std import stringtype
register_all(vars(), stringtype)
Example #20
0
    return space.newtuple([space.newtuple(w_tuple.wrappeditems)])

def tuple_count__Tuple_ANY(space, w_tuple, w_obj):
    count = 0
    for w_item in w_tuple.wrappeditems:
        if space.eq_w(w_item, w_obj):
            count += 1
    return space.wrap(count)

def tuple_index__Tuple_ANY_ANY_ANY(space, w_tuple, w_obj, w_start, w_stop):
    start = slicetype._Eval_SliceIndex(space, w_start)
    stop = slicetype._Eval_SliceIndex(space, w_stop)
    length = len(w_tuple.wrappeditems)
    if start < 0:
        start += length
        if start < 0:
            start = 0
    if stop < 0:
        stop += length
        if stop < 0:
            stop = 0
    for i in range(start, min(stop, length)):
        w_item = w_tuple.wrappeditems[i]
        if space.eq_w(w_item, w_obj):
            return space.wrap(i)
    raise OperationError(space.w_ValueError,
                         space.wrap("tuple.index(x): x not in tuple"))

from pypy.objspace.std import tupletype
register_all(vars(), tupletype)
Example #21
0
        return "nan"
    else:
        return formatd(x, code, precision)

def repr_format(x):
    return format_float(x, 'r', 0)
def str_format(x):
    return format_float(x, 'g', DTSF_STR_PRECISION)

def repr__Complex(space, w_complex):
    if w_complex.realval == 0 and copysign(1., w_complex.realval) == 1.:
        return space.wrap(repr_format(w_complex.imagval) + 'j')
    sign = (copysign(1., w_complex.imagval) == 1. or
            isnan(w_complex.imagval)) and '+' or ''
    return space.wrap('(' + repr_format(w_complex.realval)
                      + sign + repr_format(w_complex.imagval) + 'j)')

def str__Complex(space, w_complex):
    if w_complex.realval == 0 and copysign(1., w_complex.realval) == 1.:
        return space.wrap(str_format(w_complex.imagval) + 'j')
    sign = (copysign(1., w_complex.imagval) == 1. or
            isnan(w_complex.imagval)) and '+' or ''
    return space.wrap('(' + str_format(w_complex.realval)
                      + sign + str_format(w_complex.imagval) + 'j)')

def format__Complex_ANY(space, w_complex, w_format_spec):
    return newformat.run_formatter(space, w_format_spec, "format_complex", w_complex)

from pypy.objspace.std import complextype
register_all(vars(), complextype)
Example #22
0
    w_exp = space.lshift(w_den, w_exp)
    if exp > 0:
        w_num = space.mul(w_num, w_exp)
    else:
        w_den = w_exp
    # Try to return int.
    return space.newtuple([space.int(w_num), space.int(w_den)])

def float_is_integer__Float(space, w_float):
    v = w_float.floatval
    if not rfloat.isfinite(v):
        return space.w_False
    return space.wrap(math.floor(v) == v)

from pypy.objspace.std import floattype
register_all(vars(), floattype)

# pow delegation for negative 2nd arg
def pow_neg__Long_Long_None(space, w_int1, w_int2, thirdarg):
    w_float1 = delegate_Long2Float(space, w_int1)
    w_float2 = delegate_Long2Float(space, w_int2)
    return pow__Float_Float_ANY(space, w_float1, w_float2, thirdarg)

model.MM.pow.register(pow_neg__Long_Long_None, W_LongObject, W_LongObject,
                      W_NoneObject, order=1)

def pow_neg__Int_Int_None(space, w_int1, w_int2, thirdarg):
    w_float1 = delegate_Int2Float(space, w_int1)
    w_float2 = delegate_Int2Float(space, w_int2)
    return pow__Float_Float_ANY(space, w_float1, w_float2, thirdarg)
Example #23
0
def delegate_Bool2SmallInt(space, w_bool):
    from pypy.objspace.std.smallintobject import W_SmallIntObject
    return W_SmallIntObject(int(w_bool.boolval))  # cannot overflow


def nonzero__Bool(space, w_bool):
    return w_bool


def repr__Bool(space, w_bool):
    a = w_bool.boolval
    res = str(a) + " Symbolic:" + str(w_bool.is_symbolic())
    return space.wrap(res)


def and__Bool_Bool(space, w_bool1, w_bool2):
    return space.newbool(w_bool1.boolval & w_bool2.boolval)


def or__Bool_Bool(space, w_bool1, w_bool2):
    return space.newbool(w_bool1.boolval | w_bool2.boolval)


def xor__Bool_Bool(space, w_bool1, w_bool2):
    return space.newbool(w_bool1.boolval ^ w_bool2.boolval)


str__Bool = repr__Bool

register_all(vars())
Example #24
0
            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__=newmethod(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())
Example #25
0
        elif self.typecode == "u":
            r = space.repr(array_tounicode__Array(space, self))
            s = "array('%s', %s)" % (self.typecode, space.str_w(r))
            return space.wrap(s)
        else:
            r = space.repr(array_tolist__Array(space, self))
            s = "array('%s', %s)" % (self.typecode, space.str_w(r))
            return space.wrap(s)

    mytype.w_class = W_Array

    # Annotator seems to mess up if the names are not unique
    name = 'ArrayType' + mytype.typecode
    W_Array.__name__ = 'W_' + name
    import re
    for n, f in locals().items():
        new, n = re.subn('_Array_', '_%s_' % name, n)
        if n > 0:
            f.__name__ = new

    from pypy.objspace.std.sliceobject import W_SliceObject
    from pypy.objspace.std.listobject import W_ListObject
    from pypy.objspace.std.unicodeobject import W_UnicodeObject
    register_all(locals(), globals())


for mytype in types.values():
    make_array(mytype)

register_all(locals(), globals())
Example #26
0
        # perform the sort
        sorter.sort()

        # reverse again
        if has_reverse:
            sorter.list.reverse()

    finally:
        # unwrap each item if needed
        if has_key:
            for i in range(sorter.listlength):
                w_obj = sorter.list[i]
                if isinstance(w_obj, KeyContainer):
                    sorter.list[i] = w_obj.w_item

        # check if the user mucked with the list during the sort
        mucked = w_list.length() > 0

        # put the items back into the list
        w_list.__init__(space, sorter.list)

    if mucked:
        raise OperationError(space.w_ValueError,
                             space.wrap("list modified during sort"))

    return space.w_None


from pypy.objspace.std import listtype
register_all(vars(), listtype)