Ejemplo n.º 1
0
class str_methods:
    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)
Ejemplo n.º 2
0
                                      doc='Report whether this set contains'
                                          ' another set.')
frozenset_symmetric_difference  = SMM('symmetric_difference', 2,
                                      doc='Return the symmetric difference of'
                                          ' two sets as a new set.\n\n(i.e.'
                                          ' all elements that are in exactly'
                                          ' 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
Ejemplo n.º 3
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)
Ejemplo n.º 4
0

def mro_blockinglist(candidate, orderlists):
    for lst in orderlists:
        if candidate in lst[1:]:
            return lst
    return None # good candidate

def mro_error(space, orderlists):
    cycle = []
    candidate = orderlists[-1][0]
    if candidate in orderlists[-1][1:]:
        # explicit error message for this specific case
        raise operationerrfmt(space.w_TypeError,
                              "duplicate base class '%s'",
                              candidate.getname(space,"?"))
    while candidate not in cycle:
        cycle.append(candidate)
        nextblockinglist = mro_blockinglist(candidate, orderlists)
        candidate = nextblockinglist[0]
    del cycle[:cycle.index(candidate)]
    cycle.append(candidate)
    cycle.reverse()
    names = [cls.getname(space, "?") for cls in cycle]
    raise OperationError(space.w_TypeError,
        space.wrap("cycle among base classes: " + ' < '.join(names)))

# ____________________________________________________________

register_all(vars())
Ejemplo n.º 5
0
                                      doc='Report whether this set contains'
                                          ' another set.')
frozenset_symmetric_difference  = SMM('symmetric_difference', 2,
                                      doc='Return the symmetric difference of'
                                          ' two sets as a new set.\n\n(i.e.'
                                          ' all elements that are in exactly'
                                          ' 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.""",
Ejemplo n.º 6
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)
Ejemplo n.º 7
0
app = gateway.applevel(""" 
    import math
    def possint(f):
        ff = math.floor(f)
        if f == ff:
            return int(ff)
        return f

    def repr__Complex(f):
        if not f.real:
            return repr(possint(f.imag))+'j'
        imag = f.imag
        sign = ((imag >= 0) and '+') or ''
        return '('+repr(possint(f.real)) + sign + repr(possint(f.imag))+'j)'

    def str__Complex(f):
        if not f.real:
            return str(possint(f.imag))+'j'
        imag = f.imag
        sign = ((imag >= 0) and '+') or ''
        return '('+str(possint(f.real)) + sign + str(possint(f.imag))+'j)'

""", filename=__file__) 

repr__Complex = app.interphook('repr__Complex') 
str__Complex = app.interphook('str__Complex') 

from pypy.objspace.std import complextype
register_all(vars(), complextype)
Ejemplo n.º 8
0
    def __init__(w_self, space, iteratorimplementation, itertype):
        w_self.space = space
        w_self.iteratorimplementation = iteratorimplementation
        w_self.itertype = itertype

registerimplementation(W_DictMultiIterObject)

def iter__DictMultiIterObject(space, w_dictiter):
    return w_dictiter

def next__DictMultiIterObject(space, w_dictiter):
    iteratorimplementation = w_dictiter.iteratorimplementation
    w_key, w_value = iteratorimplementation.next()
    if w_key is not None:
        itertype = w_dictiter.itertype
        if itertype == KEYSITER:
            return w_key
        elif itertype == VALUESITER:
            return w_value
        elif itertype == ITEMSITER:
            return space.newtuple([w_key, w_value])
        else:
            assert 0, "should be unreachable"
    raise OperationError(space.w_StopIteration, space.w_None)

# ____________________________________________________________

from pypy.objspace.std import dicttype
register_all(vars(), dicttype)
Ejemplo n.º 9
0
from pypy.objspace.std.objspace import W_Object, register_all


class W_ObjectObject(W_Object):
    """Instances of this class are what the user can directly see with an
    'object()' call."""
    from pypy.objspace.std.objecttype import object_typedef as typedef


# ____________________________________________________________

register_all(vars())
Ejemplo n.º 10
0
             chars.append(table[ord(char)])
    return W_StringObject(''.join(chars))

def str_decode__String_ANY_ANY(space, w_string, w_encoding=None, w_errors=None):
    from pypy.objspace.std.unicodetype import _get_encoding_and_errors, \
        unicode_from_string, decode_object
    encoding, errors = _get_encoding_and_errors(space, w_encoding, w_errors)
    if encoding is None and errors is None:
        return unicode_from_string(space, w_string)
    return decode_object(space, w_string, encoding, errors)

def str_encode__String_ANY_ANY(space, w_string, w_encoding=None, w_errors=None):
    from pypy.objspace.std.unicodetype import _get_encoding_and_errors, \
        encode_object
    encoding, errors = _get_encoding_and_errors(space, w_encoding, w_errors)
    return encode_object(space, w_string, encoding, errors)

# CPython's logic for deciding if  ""%values  is
# an error (1 value, 0 %-formatters) or not
# (values is of a mapping type)
def mod__String_ANY(space, w_format, w_values):
    return mod_format(space, w_format, w_values, do_unicode=False)

def buffer__String(space, w_string):
    from pypy.interpreter.buffer import StringBuffer
    return space.wrap(StringBuffer(w_string._value))

# register all methods
from pypy.objspace.std import stringtype
register_all(vars(), stringtype)
Ejemplo n.º 11
0
app = gateway.applevel(""" 
    import math
    def possint(f):
        ff = math.floor(f)
        if f == ff:
            return int(ff)
        return f

    def repr__Complex(f):
        if not f.real:
            return repr(possint(f.imag))+'j'
        imag = f.imag
        sign = ((imag >= 0) and '+') or ''
        return '('+repr(possint(f.real)) + sign + repr(possint(f.imag))+'j)'

    def str__Complex(f):
        if not f.real:
            return str(possint(f.imag))+'j'
        imag = f.imag
        sign = ((imag >= 0) and '+') or ''
        return '('+str(possint(f.real)) + sign + str(possint(f.imag))+'j)'

""", filename=__file__) 

repr__Complex = app.interphook('repr__Complex') 
str__Complex = app.interphook('str__Complex') 

from pypy.objspace.std import complextype
register_all(vars(), complextype)
Ejemplo n.º 12
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)
Ejemplo n.º 13
0
    return space.wrap(''.join(result))
        

def mod__Unicode_ANY(space, w_format, w_values):
    return mod_format(space, w_format, w_values, do_unicode=True)

def buffer__Unicode(space, w_unicode):
    from pypy.rlib.rstruct.unichar import pack_unichar
    charlist = []
    for unich in w_unicode._value:
        pack_unichar(unich, charlist)
    from pypy.interpreter.buffer import StringBuffer
    return space.wrap(StringBuffer(''.join(charlist)))

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:
    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
Ejemplo n.º 14
0
    encoding, errors = _get_encoding_and_errors(space, w_encoding, w_errors)
    if encoding is None and errors is None:
        return unicode_from_string(space, w_string)
    return decode_object(space, w_string, encoding, errors)


def str_encode__String_ANY_ANY(space, w_string, w_encoding=None, w_errors=None):
    from pypy.objspace.std.unicodetype import _get_encoding_and_errors, encode_object

    encoding, errors = _get_encoding_and_errors(space, w_encoding, w_errors)
    return encode_object(space, w_string, encoding, errors)


# CPython's logic for deciding if  ""%values  is
# an error (1 value, 0 %-formatters) or not
# (values is of a mapping type)
def mod__String_ANY(space, w_format, w_values):
    return mod_format(space, w_format, w_values, do_unicode=False)


def buffer__String(space, w_string):
    from pypy.interpreter.buffer import StringBuffer

    return space.wrap(StringBuffer(w_string._value))


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

register_all(vars(), stringtype)