Пример #1
0
 def __init__(self, getset, w_type):
     self.getset = getset
     self.name = rffi.charp2str(getset.c_name)
     self.w_type = w_type
     doc = set = get = None
     if doc:
         doc = rffi.charp2str(getset.c_doc)
     if getset.c_get:
         get = GettersAndSetters.getter.im_func
     if getset.c_set:
         set = GettersAndSetters.setter.im_func
     GetSetProperty.__init__(self, get, set, None, doc, cls=None, use_closure=True, tag="cpyext_1")
Пример #2
0
 def __init__(self, member, w_type):
     self.member = member
     self.name = rffi.charp2str(member.c_name)
     self.w_type = w_type
     flags = rffi.cast(lltype.Signed, member.c_flags)
     doc = set = None
     if member.c_doc:
         doc = rffi.charp2str(member.c_doc)
     get = GettersAndSetters.member_getter.im_func
     del_ = GettersAndSetters.member_delete.im_func
     if not (flags & structmemberdefs.READONLY):
         set = GettersAndSetters.member_setter.im_func
     GetSetProperty.__init__(self, get, set, del_, doc, cls=None, use_closure=True, tag="cpyext_2")
Пример #3
0
        return space.wrap(exc)

    descr_new_base_exception.func_name = 'descr_new_' + cls.__name__
    return interp2app(descr_new_base_exception)


W_BaseException.typedef = TypeDef(
    'exceptions.BaseException',
    __doc__=W_BaseException.__doc__,
    __new__=_new(W_BaseException),
    __init__=interp2app(W_BaseException.descr_init),
    __str__=interp2app(W_BaseException.descr_str),
    __unicode__=interp2app(W_BaseException.descr_unicode),
    __repr__=interp2app(W_BaseException.descr_repr),
    __dict__=GetSetProperty(descr_get_dict,
                            descr_set_dict,
                            descr_del_dict,
                            cls=W_BaseException),
    __getitem__=interp2app(W_BaseException.descr_getitem),
    __reduce__=interp2app(W_BaseException.descr_reduce),
    __setstate__=interp2app(W_BaseException.descr_setstate),
    message=GetSetProperty(W_BaseException.descr_message_get,
                           W_BaseException.descr_message_set,
                           W_BaseException.descr_message_del),
    args=GetSetProperty(W_BaseException.descr_getargs,
                        W_BaseException.descr_setargs),
)


def _new_exception(name, base, docstring, **kwargs):
    # Create a subclass W_Exc of the class 'base'.  Note that there is
    # hackery going on on the typedef of W_Exc: when we make further
Пример #4
0
the value for this attribute is one of None (no newline read yet),
'\r', '\n', '\r\n' or a tuple containing all the newline types seen.

Note:  open() is an alias for file().
""",
    __new__=interp2app(descr_file__new__),
    fdopen=interp2app(descr_file_fdopen, as_classmethod=True),
    name=interp_attrproperty_w('w_name', cls=W_File, doc="file name"),
    mode=interp_attrproperty('mode',
                             cls=W_File,
                             doc="file mode ('r', 'U', 'w', 'a', "
                             "possibly with 'b' or '+' added)"),
    encoding=interp_attrproperty('encoding', cls=W_File),
    errors=interp_attrproperty('errors', cls=W_File),
    closed=GetSetProperty(descr_file_closed,
                          cls=W_File,
                          doc="True if the file is closed"),
    newlines=GetSetProperty(descr_file_newlines,
                            cls=W_File,
                            doc="end-of-line convention used in this file"),
    softspace=GetSetProperty(descr_file_softspace,
                             descr_file_setsoftspace,
                             cls=W_File,
                             doc="Support for 'print'."),
    __repr__=interp2app(W_File.file__repr__),
    readinto=interp2app(W_File.file_readinto),
    writelines=interp2app(W_File.file_writelines),
    __exit__=interp2app(W_File.file__exit__),
    __weakref__=make_weakref_descr(W_File),
    **dict([(name, interp2app(getattr(W_File, 'file_' + name)))
            for name in W_File._exposed_method_names]))
Пример #5
0
    specialname = "__%s__" % (op,)
    rspecialname = "__r%s__" % (op,)
    func, rfunc = make_binary_instance_method(op)
    # fool the gateway logic by giving it a real unbound method
    meth = new.instancemethod(func, None, W_InstanceObject)
    rawdict[specialname] = interp2app(meth)
    rmeth = new.instancemethod(rfunc, None, W_InstanceObject)
    rawdict[rspecialname] = interp2app(rmeth)


def descr_del_dict(space, w_inst):
    # use setdict to raise the error
    w_inst.setdict(space, space.w_None)


dict_descr = GetSetProperty(descr_get_dict, descr_set_dict, descr_del_dict)
dict_descr.name = "__dict__"

W_InstanceObject.typedef = TypeDef(
    "instance",
    __new__=interp2app(descr_instance_new),
    __getattribute__=interp2app(W_InstanceObject.descr_getattribute),
    __setattr__=interp2app(W_InstanceObject.descr_setattr),
    __delattr__=interp2app(W_InstanceObject.descr_delattr),
    __repr__=interp2app(W_InstanceObject.descr_repr),
    __str__=interp2app(W_InstanceObject.descr_str),
    __unicode__=interp2app(W_InstanceObject.descr_unicode),
    __format__=interp2app(W_InstanceObject.descr_format),
    __len__=interp2app(W_InstanceObject.descr_len),
    __getitem__=interp2app(W_InstanceObject.descr_getitem),
    __setitem__=interp2app(W_InstanceObject.descr_setitem),
Пример #6
0

W_SRE_Match.typedef = TypeDef(
    'SRE_Match',
    __copy__=interp2app(W_SRE_Match.cannot_copy_w),
    __deepcopy__=interp2app(W_SRE_Match.cannot_copy_w),
    group=interp2app(W_SRE_Match.group_w),
    groups=interp2app(W_SRE_Match.groups_w),
    groupdict=interp2app(W_SRE_Match.groupdict_w),
    start=interp2app(W_SRE_Match.start_w),
    end=interp2app(W_SRE_Match.end_w),
    span=interp2app(W_SRE_Match.span_w),
    expand=interp2app(W_SRE_Match.expand_w),
    #
    re=interp_attrproperty_w('srepat', W_SRE_Match),
    string=GetSetProperty(W_SRE_Match.fget_string),
    pos=GetSetProperty(W_SRE_Match.fget_pos),
    endpos=GetSetProperty(W_SRE_Match.fget_endpos),
    lastgroup=GetSetProperty(W_SRE_Match.fget_lastgroup),
    lastindex=GetSetProperty(W_SRE_Match.fget_lastindex),
    regs=GetSetProperty(W_SRE_Match.fget_regs),
)
W_SRE_Match.typedef.acceptable_as_base_class = False

# ____________________________________________________________
#
# SRE_Scanner class
# This is mostly an internal class in CPython.
# Our version is also directly iterable, to make finditer() easier.

Пример #7
0
    def line_buffering_get_w(self, space):
        return space.w_False

    def newlines_get_w(self, space):
        if self.w_decoder is None:
            return space.w_None
        return space.getattr(self.w_decoder, space.newtext("newlines"))


W_StringIO.typedef = TypeDef(
    '_io.StringIO',
    W_TextIOBase.typedef,
    __new__=generic_new_descr(W_StringIO),
    __init__=interp2app(W_StringIO.descr_init),
    __getstate__=interp2app(W_StringIO.descr_getstate),
    __setstate__=interp2app(W_StringIO.descr_setstate),
    write=interp2app(W_StringIO.write_w),
    read=interp2app(W_StringIO.read_w),
    readline=interp2app(W_StringIO.readline_w),
    seek=interp2app(W_StringIO.seek_w),
    truncate=interp2app(W_StringIO.truncate_w),
    getvalue=interp2app(W_StringIO.getvalue_w),
    readable=interp2app(W_StringIO.readable_w),
    writable=interp2app(W_StringIO.writable_w),
    seekable=interp2app(W_StringIO.seekable_w),
    close=interp2app(W_StringIO.close_w),
    closed=GetSetProperty(W_StringIO.closed_get_w),
    line_buffering=GetSetProperty(W_StringIO.line_buffering_get_w),
    newlines=GetSetProperty(W_StringIO.newlines_get_w),
)
Пример #8
0
    next=interp2app(W_IOBase.next_w),
    close=interp2app(W_IOBase.close_w),
    flush=interp2app(W_IOBase.flush_w),
    seek=interp2app(W_IOBase.seek_w),
    tell=interp2app(W_IOBase.tell_w),
    truncate=interp2app(W_IOBase.truncate_w),
    fileno=interp2app(W_IOBase.fileno_w),
    isatty=interp2app(W_IOBase.isatty_w),
    readable=interp2app(W_IOBase.readable_w),
    writable=interp2app(W_IOBase.writable_w),
    seekable=interp2app(W_IOBase.seekable_w),
    _checkReadable=interp2app(check_readable_w),
    _checkWritable=interp2app(check_writable_w),
    _checkSeekable=interp2app(check_seekable_w),
    _checkClosed=interp2app(W_IOBase.check_closed_w),
    closed=GetSetProperty(W_IOBase.closed_get_w),
    __dict__=GetSetProperty(descr_get_dict, descr_set_dict, cls=W_IOBase),
    __weakref__=make_weakref_descr(W_IOBase),
    readline=interp2app(W_IOBase.readline_w),
    readlines=interp2app(W_IOBase.readlines_w),
    writelines=interp2app(W_IOBase.writelines_w),
)


class W_RawIOBase(W_IOBase):
    # ________________________________________________________________
    # Abstract read methods, based on readinto()

    def read_w(self, space, w_size=None):
        size = convert_size(space, w_size)
        if size < 0:
Пример #9
0
    def descr_call(self, space, __args__):
        return space.call_args(self.w_function, __args__)

    def descr_repr(self, space):
        return self.getrepr(
            space, u'<instancemethod %s>' % (self.w_function.getname(space), ))


InstanceMethod.typedef = TypeDef(
    "instancemethod",
    __new__=interp2app(InstanceMethod.descr_new),
    __call__=interp2app(InstanceMethod.descr_call, descrmismatch='__call__'),
    __get__=interp2app(InstanceMethod.descr_get),
    __repr__=interp2app(InstanceMethod.descr_repr, descrmismatch='__repr__'),
    __func__=interp_attrproperty_w('w_function', cls=InstanceMethod),
    __name__=GetSetProperty(InstanceMethod.fget_name, cls=InstanceMethod),
    __module__=GetSetProperty(InstanceMethod.fget_module, cls=InstanceMethod),
    __doc__=GetSetProperty(InstanceMethod.fget_docstring, cls=InstanceMethod),
)
InstanceMethod.typedef.acceptable_as_base_class = False


@cpython_api([PyObject], rffi.INT_real, error=CANNOT_FAIL)
def PyInstanceMethod_Check(space, w_o):
    """Return true if o is an instance method object (has type
    PyInstanceMethod_Type).  The parameter must not be NULL."""
    return space.isinstance_w(w_o, space.gettypeobject(InstanceMethod.typedef))


@cpython_api([PyObject], PyObject)
def PyInstanceMethod_New(space, w_func):
Пример #10
0
            with rffi.scoped_alloc_buffer(digest_size) as buf:
                ropenssl.EVP_DigestFinal(ctx, buf.raw, None)
                return buf.str(digest_size)
        finally:
            ropenssl.EVP_MD_CTX_free(ctx)


W_Hash.typedef = TypeDef(
    'HASH',
    __repr__=interp2app(W_Hash.descr_repr),
    update=interp2app(W_Hash.update),
    copy=interp2app(W_Hash.copy),
    digest=interp2app(W_Hash.digest),
    hexdigest=interp2app(W_Hash.hexdigest),
    #
    digest_size=GetSetProperty(W_Hash.get_digest_size),
    digestsize=GetSetProperty(W_Hash.get_digest_size),
    block_size=GetSetProperty(W_Hash.get_block_size),
    name=GetSetProperty(W_Hash.get_name),
)
W_Hash.typedef.acceptable_as_base_class = False


@unwrap_spec(name='text', string='bufferstr')
def new(space, name, string=''):
    w_hash = W_Hash(space, name)
    w_hash.update(space, string)
    return w_hash


# shortcut functions
Пример #11
0
def complexwprop(name):
    def fget(space, w_obj):
        if not isinstance(w_obj, W_ComplexObject):
            raise oefmt(space.w_TypeError, "descriptor is for 'complex'")
        return space.newfloat(getattr(w_obj, name))
    return GetSetProperty(fget)
Пример #12
0
    def descr_setitem(self, space, w_item, w_value):
        raise OperationError(space.w_KeyError, space.wrap("Unknown flag"))

    def eq(self, space, w_other):
        if not isinstance(w_other, W_FlagsObject):
            return False
        return self.flags == w_other.flags

    def descr_eq(self, space, w_other):
        return space.wrap(self.eq(space, w_other))

    def descr_ne(self, space, w_other):
        return space.wrap(not self.eq(space, w_other))


W_FlagsObject.typedef = TypeDef(
    "numpy.flagsobj",
    __new__=interp2app(W_FlagsObject.descr__new__.im_func),
    __getitem__=interp2app(W_FlagsObject.descr_getitem),
    __setitem__=interp2app(W_FlagsObject.descr_setitem),
    __eq__=interp2app(W_FlagsObject.descr_eq),
    __ne__=interp2app(W_FlagsObject.descr_ne),
    contiguous=GetSetProperty(W_FlagsObject.descr_get_contiguous),
    c_contiguous=GetSetProperty(W_FlagsObject.descr_get_contiguous),
    f_contiguous=GetSetProperty(W_FlagsObject.descr_get_fortran),
    fortran=GetSetProperty(W_FlagsObject.descr_get_fortran),
    writeable=GetSetProperty(W_FlagsObject.descr_get_writeable),
    fnc=GetSetProperty(W_FlagsObject.descr_get_fnc),
    forc=GetSetProperty(W_FlagsObject.descr_get_forc),
)
Пример #13
0
                        "maxevents must be greater than 0, not %d", maxevents)

        with lltype.scoped_alloc(rffi.CArray(epoll_event), maxevents) as evs:
            nfds = epoll_wait(self.epfd, evs, maxevents, int(timeout))
            if nfds < 0:
                raise exception_from_saved_errno(space, space.w_IOError)

            elist_w = [None] * nfds
            for i in xrange(nfds):
                event = evs[i]
                elist_w[i] = space.newtuple([
                    space.newint(event.c_data.c_fd),
                    space.newint(event.c_events)
                ])
            return space.newlist(elist_w)


W_Epoll.typedef = TypeDef(
    "select.epoll",
    __new__=interp2app(W_Epoll.descr__new__.im_func),
    fromfd=interp2app(W_Epoll.descr_fromfd.im_func, as_classmethod=True),
    closed=GetSetProperty(W_Epoll.descr_get_closed),
    fileno=interp2app(W_Epoll.descr_fileno),
    close=interp2app(W_Epoll.descr_close),
    register=interp2app(W_Epoll.descr_register),
    unregister=interp2app(W_Epoll.descr_unregister),
    modify=interp2app(W_Epoll.descr_modify),
    poll=interp2app(W_Epoll.descr_poll),
)
W_Epoll.typedef.acceptable_as_base_class = False
Пример #14
0
    try:
        handle = create_semaphore(space, name, value, maxvalue)
    except OSError, e:
        raise wrap_oserror(space, e)

    self = space.allocate_instance(W_SemLock, w_subtype)
    self.__init__(handle, kind, maxvalue)

    return space.wrap(self)


W_SemLock.typedef = TypeDef(
    "SemLock",
    __new__=interp2app(descr_new),
    kind=GetSetProperty(W_SemLock.kind_get),
    maxvalue=GetSetProperty(W_SemLock.maxvalue_get),
    handle=GetSetProperty(W_SemLock.handle_get),
    _count=interp2app(W_SemLock.get_count),
    _is_mine=interp2app(W_SemLock.is_mine),
    _is_zero=interp2app(W_SemLock.is_zero),
    _get_value=interp2app(W_SemLock.get_value),
    acquire=interp2app(W_SemLock.acquire),
    release=interp2app(W_SemLock.release),
    _rebuild=interp2app(W_SemLock.rebuild.im_func, as_classmethod=True),
    _after_fork=interp2app(W_SemLock.after_fork),
    __enter__=interp2app(W_SemLock.enter),
    __exit__=interp2app(W_SemLock.exit),
    SEM_VALUE_MAX=SEM_VALUE_MAX,
)
Пример #15
0
        pos = space.int_w(w_pos)
        if pos < 0:
            raise oefmt(space.w_ValueError,
                        "position value cannot be negative")
        self.seek(pos)
        if not space.is_w(w_dict, space.w_None):
            space.call_method(self.getdict(space), "update", w_dict)

W_BytesIO.typedef = TypeDef(
    '_io.BytesIO', W_BufferedIOBase.typedef,
    __new__ = generic_new_descr(W_BytesIO),
    __init__  = interp2app(W_BytesIO.descr_init),

    read = interp2app(W_BytesIO.read_w),
    read1 = interp2app(W_BytesIO.read1_w),
    readline = interp2app(W_BytesIO.readline_w),
    readinto = interp2app(W_BytesIO.readinto_w),
    write = interp2app(W_BytesIO.write_w),
    truncate = interp2app(W_BytesIO.truncate_w),
    getvalue = interp2app(W_BytesIO.getvalue_w),
    seek = interp2app(W_BytesIO.seek_w),
    tell = interp2app(W_BytesIO.tell_w),
    readable = interp2app(W_BytesIO.readable_w),
    writable = interp2app(W_BytesIO.writable_w),
    seekable = interp2app(W_BytesIO.seekable_w),
    close = interp2app(W_BytesIO.close_w),
    closed = GetSetProperty(W_BytesIO.closed_get_w),
    __getstate__ = interp2app(W_BytesIO.getstate_w),
    __setstate__ = interp2app(W_BytesIO.setstate_w),
    )
Пример #16
0
                      new_shape, calc_dtype,
                      res_dtype, w_lhs, w_rhs, out)
        w_lhs.add_invalidates(space, w_res)
        w_rhs.add_invalidates(space, w_res)
        if out:
            w_res.get_concrete()
        return w_res


W_Ufunc.typedef = TypeDef("ufunc",
    __module__ = "numpypy",

    __call__ = interp2app(W_Ufunc.descr_call),
    __repr__ = interp2app(W_Ufunc.descr_repr),

    identity = GetSetProperty(W_Ufunc.descr_get_identity),
    nin = interp_attrproperty("argcount", cls=W_Ufunc),

    reduce = interp2app(W_Ufunc.descr_reduce),
)


def find_binop_result_dtype(space, dt1, dt2, promote_to_float=False,
    promote_bools=False, int_only=False):
    # dt1.num should be <= dt2.num
    if dt1.num > dt2.num:
        dt1, dt2 = dt2, dt1
    if int_only and (not dt1.is_int_type() or not dt2.is_int_type()):
        raise OperationError(space.w_TypeError, space.wrap("Unsupported types"))
    # Some operations promote op(bool, bool) to return int8, rather than bool
    if promote_bools and (dt1.kind == dt2.kind == interp_dtype.BOOLLTR):
Пример #17
0

W_Dtype.typedef = TypeDef(
    "dtype",
    __module__="numpypy",
    __new__=interp2app(descr__new__),
    __str__=interp2app(W_Dtype.descr_str),
    __repr__=interp2app(W_Dtype.descr_repr),
    __eq__=interp2app(W_Dtype.descr_eq),
    __ne__=interp2app(W_Dtype.descr_ne),
    __getitem__=interp2app(W_Dtype.descr_getitem),
    num=interp_attrproperty("num", cls=W_Dtype),
    kind=interp_attrproperty("kind", cls=W_Dtype),
    char=interp_attrproperty("char", cls=W_Dtype),
    type=interp_attrproperty_w("w_box_type", cls=W_Dtype),
    byteorder=GetSetProperty(W_Dtype.descr_get_byteorder),
    itemsize=GetSetProperty(W_Dtype.descr_get_itemsize),
    alignment=GetSetProperty(W_Dtype.descr_get_alignment),
    shape=GetSetProperty(W_Dtype.descr_get_shape),
    name=interp_attrproperty('name', cls=W_Dtype),
    fields=GetSetProperty(W_Dtype.descr_get_fields),
    names=GetSetProperty(W_Dtype.descr_get_names),
)
W_Dtype.typedef.acceptable_as_base_class = False

if sys.byteorder == 'little':
    byteorder_prefix = '<'
    nonnative_byteorder_prefix = '>'
else:
    byteorder_prefix = '>'
    nonnative_byteorder_prefix = '<'
Пример #18
0
GeneratorIterator.typedef = TypeDef(
    "generator",
    __repr__=interp2app(GeneratorIterator.descr__repr__),
    __reduce__=interp2app(GeneratorIterator.descr__reduce__),
    __setstate__=interp2app(GeneratorIterator.descr__setstate__),
    next=interp2app(GeneratorIterator.descr_next, descrmismatch='next'),
    send=interp2app(GeneratorIterator.descr_send, descrmismatch='send'),
    throw=interp2app(GeneratorIterator.descr_throw, descrmismatch='throw'),
    close=interp2app(GeneratorIterator.descr_close, descrmismatch='close'),
    __iter__=interp2app(GeneratorIterator.descr__iter__,
                        descrmismatch='__iter__'),
    gi_running=interp_attrproperty('running',
                                   cls=GeneratorIterator,
                                   wrapfn="newbool"),
    gi_frame=GetSetProperty(GeneratorIterator.descr_gi_frame),
    gi_code=GetSetProperty(GeneratorIterator.descr_gi_code),
    __name__=GetSetProperty(GeneratorIterator.descr__name__),
    __weakref__=make_weakref_descr(GeneratorIterator),
)
assert not GeneratorIterator.typedef.acceptable_as_base_class  # no __new__


def get_printable_location_genentry(bytecode):
    return '%s <generator>' % (bytecode.get_repr(), )


generatorentry_driver = jit.JitDriver(
    greens=['pycode'],
    reds=['gen', 'w_arg', 'operr'],
    get_printable_location=get_printable_location_genentry,
Пример #19
0
bind(addr) -- bind the socket to a local address
close() -- close the socket
connect(addr) -- connect the socket to a remote address
connect_ex(addr) -- connect, return an error code instead of an exception
dup() -- return a new socket object identical to the current one [*]
fileno() -- return underlying file descriptor
getpeername() -- return remote address [*]
getsockname() -- return local address
getsockopt(level, optname[, buflen]) -- get socket options
gettimeout() -- return timeout or None
listen(n) -- start listening for incoming connections
makefile([mode, [bufsize]]) -- return a file object for the socket [*]
recv(buflen[, flags]) -- receive data
recvfrom(buflen[, flags]) -- receive data and sender's address
sendall(data[, flags]) -- send all data
send(data[, flags]) -- send data, may not send all of it
sendto(data[, flags], addr) -- send data to a given address
setblocking(0 | 1) -- set or clear the blocking I/O flag
setsockopt(level, optname, value) -- set socket options
settimeout(None | float) -- set or clear the timeout
shutdown(how) -- shut down traffic in one or both directions

 [*] not available on all platforms!""",
    __new__ = descr_socket_new,
    __weakref__ = make_weakref_descr(W_Socket),
    type = GetSetProperty(W_Socket.get_type_w),
    proto = GetSetProperty(W_Socket.get_proto_w),
    family = GetSetProperty(W_Socket.get_family_w),
    ** socketmethods
    )
Пример #20
0
        flag >>= 1

        if self.w_decoder and not space.is_w(self.w_decoder, space.w_None):
            w_state = space.newtuple([w_buffer, space.newint(flag)])
            space.call_method(self.w_decoder, "setstate", w_state)


W_IncrementalNewlineDecoder.typedef = TypeDef(
    '_io.IncrementalNewlineDecoder',
    __new__=generic_new_descr(W_IncrementalNewlineDecoder),
    __init__=interp2app(W_IncrementalNewlineDecoder.descr_init),
    decode=interp2app(W_IncrementalNewlineDecoder.decode_w),
    reset=interp2app(W_IncrementalNewlineDecoder.reset_w),
    getstate=interp2app(W_IncrementalNewlineDecoder.getstate_w),
    setstate=interp2app(W_IncrementalNewlineDecoder.setstate_w),
    newlines=GetSetProperty(W_IncrementalNewlineDecoder.newlines_get_w),
)


class W_TextIOBase(W_IOBase):
    w_encoding = None

    def __init__(self, space):
        W_IOBase.__init__(self, space)

    def read_w(self, space, w_size=None):
        self._unsupportedoperation(space, "read")

    def readline_w(self, space, w_limit=None):
        self._unsupportedoperation(space, "readline")
Пример #21
0
                            w_event.filter = evt.c_filter
                            w_event.flags = evt.c_flags
                            w_event.fflags = evt.c_fflags
                            w_event.data = evt.c_data
                            w_event.udata = evt.c_udata

                            elist_w[i] = w_event

                    return space.newlist(elist_w)


W_Kqueue.typedef = TypeDef(
    "select.kqueue",
    __new__=interp2app(W_Kqueue.descr__new__.im_func),
    fromfd=interp2app(W_Kqueue.descr_fromfd.im_func, as_classmethod=True),
    closed=GetSetProperty(W_Kqueue.descr_get_closed),
    fileno=interp2app(W_Kqueue.descr_fileno),
    close=interp2app(W_Kqueue.descr_close),
    control=interp2app(W_Kqueue.descr_control),
)
W_Kqueue.typedef.acceptable_as_base_class = False


class W_Kevent(W_Root):
    def __init__(self, space):
        self.ident = rffi.cast(kevent.c_ident, 0)
        self.filter = rffi.cast(kevent.c_filter, 0)
        self.flags = rffi.cast(kevent.c_flags, 0)
        self.fflags = rffi.cast(kevent.c_fflags, 0)
        self.data = rffi.cast(kevent.c_data, 0)
        self.udata = lltype.nullptr(rffi.VOIDP.TO)
Пример #22
0
            self._truncate(space.r_longlong_w(w_size))
        except OSError, e:
            raise wrap_oserror(space, e, exception_name='w_IOError')

        return w_size


W_FileIO.typedef = TypeDef(
    '_io.FileIO',
    W_RawIOBase.typedef,
    __new__=interp2app(W_FileIO.descr_new.im_func),
    __init__=interp2app(W_FileIO.descr_init),
    __repr__=interp2app(W_FileIO.repr_w),
    seek=interp2app(W_FileIO.seek_w),
    tell=interp2app(W_FileIO.tell_w),
    write=interp2app(W_FileIO.write_w),
    read=interp2app(W_FileIO.read_w),
    readinto=interp2app(W_FileIO.readinto_w),
    readall=interp2app(W_FileIO.readall_w),
    truncate=interp2app(W_FileIO.truncate_w),
    close=interp2app(W_FileIO.close_w),
    readable=interp2app(W_FileIO.readable_w),
    writable=interp2app(W_FileIO.writable_w),
    seekable=interp2app(W_FileIO.seekable_w),
    fileno=interp2app(W_FileIO.fileno_w),
    isatty=interp2app(W_FileIO.isatty_w),
    name=interp_member_w('w_name', cls=W_FileIO),
    closefd=interp_attrproperty('closefd', cls=W_FileIO),
    mode=GetSetProperty(W_FileIO.descr_get_mode),
)
Пример #23
0
    @unwrap_spec(attr='text')
    def descr_fieldaddress(self, space, attr):
        i = self.shape.getindex(space, attr)
        ptr = rffi.ptradd(self.ll_buffer, self.shape.ll_positions[i])
        return space.newint(rffi.cast(lltype.Unsigned, ptr))

    def getrawsize(self):
        return self.shape.size


W_StructureInstance.typedef = TypeDef(
    'StructureInstance',
    __repr__=interp2app(W_StructureInstance.descr_repr),
    __getattr__=interp2app(W_StructureInstance.getattr),
    __setattr__=interp2app(W_StructureInstance.setattr),
    buffer=GetSetProperty(W_StructureInstance.getbuffer),
    free=interp2app(W_StructureInstance.free),
    shape=interp_attrproperty_w('shape', W_StructureInstance),
    byptr=interp2app(W_StructureInstance.byptr),
    fieldaddress=interp2app(W_StructureInstance.descr_fieldaddress),
)
W_StructureInstance.typedef.acceptable_as_base_class = False


class W_StructureInstanceAutoFree(W_StructureInstance):
    def __init__(self, space, shape):
        W_StructureInstance.__init__(self, space, shape, 0)

    @rgc.must_be_light_finalizer
    def __del__(self):
        if self.ll_buffer:
Пример #24
0
    @unwrap_spec(w_timeout=WrappedDefault(0.0))
    def poll(self, space, w_timeout):
        self._check_readable(space)
        if space.is_w(w_timeout, space.w_None):
            timeout = -1.0  # block forever
        else:
            timeout = space.float_w(w_timeout)
            if timeout < 0.0:
                timeout = 0.0
        return space.newbool(self.do_poll(space, timeout))


W_BaseConnection.typedef = TypeDef(
    'BaseConnection',
    __repr__=interpindirect2app(W_BaseConnection.descr_repr),
    closed=GetSetProperty(W_BaseConnection.closed_get),
    readable=GetSetProperty(W_BaseConnection.readable_get),
    writable=GetSetProperty(W_BaseConnection.writable_get),
    send_bytes=interp2app(W_BaseConnection.send_bytes),
    recv_bytes=interp2app(W_BaseConnection.recv_bytes),
    recv_bytes_into=interp2app(W_BaseConnection.recv_bytes_into),
    send=interp2app(W_BaseConnection.send),
    recv=interp2app(W_BaseConnection.recv),
    poll=interp2app(W_BaseConnection.poll),
    close=interp2app(W_BaseConnection.close),
)


class W_FileConnection(W_BaseConnection):
    INVALID_HANDLE_VALUE = -1
    fd = INVALID_HANDLE_VALUE
Пример #25
0
    except RZlibError as e:
        # in this case, CPython raises the direct exception coming
        # from the zlib module: let's do the same
        raise zlib_error(space, e.msg)

    prefix = name[len(filename):]
    if prefix.startswith(os.path.sep) or prefix.startswith(ZIPSEP):
        prefix = prefix[1:]
    if prefix and not prefix.endswith(ZIPSEP) and not prefix.endswith(
            os.path.sep):
        prefix += ZIPSEP
    w_result = W_ZipImporter(space, name, filename, zip_file, prefix)
    zip_cache.set(filename, w_result)
    return w_result


W_ZipImporter.typedef = TypeDef(
    'zipimporter',
    __new__=interp2app(descr_new_zipimporter),
    find_module=interp2app(W_ZipImporter.find_module),
    get_data=interp2app(W_ZipImporter.get_data),
    get_code=interp2app(W_ZipImporter.get_code),
    get_source=interp2app(W_ZipImporter.get_source),
    get_filename=interp2app(W_ZipImporter.get_filename),
    is_package=interp2app(W_ZipImporter.is_package),
    load_module=interp2app(W_ZipImporter.load_module),
    find_loader=interp2app(W_ZipImporter.find_loader),
    archive=GetSetProperty(W_ZipImporter.getarchive),
    prefix=GetSetProperty(W_ZipImporter.getprefix),
)
Пример #26
0
    __sub__ = interp2app(W_FloatObject.descr_sub),
    __rsub__ = interp2app(W_FloatObject.descr_rsub),
    __mul__ = interp2app(W_FloatObject.descr_mul),
    __rmul__ = interp2app(W_FloatObject.descr_rmul),
    __truediv__ = interp2app(W_FloatObject.descr_div),
    __rtruediv__ = interp2app(W_FloatObject.descr_rdiv),
    __floordiv__ = interp2app(W_FloatObject.descr_floordiv),
    __rfloordiv__ = interp2app(W_FloatObject.descr_rfloordiv),
    __mod__ = interp2app(W_FloatObject.descr_mod),
    __rmod__ = interp2app(W_FloatObject.descr_rmod),
    __divmod__ = interp2app(W_FloatObject.descr_divmod),
    __rdivmod__ = interp2app(W_FloatObject.descr_rdivmod),
    __pow__ = interp2app(W_FloatObject.descr_pow),
    __rpow__ = interp2app(W_FloatObject.descr_rpow),

    real = GetSetProperty(W_FloatObject.descr_get_real),
    imag = GetSetProperty(W_FloatObject.descr_get_imag),
    conjugate = interp2app(W_FloatObject.descr_conjugate),
    is_integer = interp2app(W_FloatObject.descr_is_integer),
    as_integer_ratio = interp2app(W_FloatObject.descr_as_integer_ratio),
    hex = interp2app(W_FloatObject.descr_hex),
)


def _hash_float(space, v):
    if not isfinite(v):
        if math.isinf(v):
            return HASH_INF if v > 0 else -HASH_INF
        return HASH_NAN

    m, e = math.frexp(v)
Пример #27
0
 __ge__=interp2app(W_ArrayBase.descr_ge),
 __getitem__=interp2app(W_ArrayBase.descr_getitem),
 __getslice__=interp2app(W_ArrayBase.descr_getslice),
 __setitem__=interp2app(W_ArrayBase.descr_setitem),
 __setslice__=interp2app(W_ArrayBase.descr_setslice),
 __delitem__=interp2app(W_ArrayBase.descr_delitem),
 __delslice__=interp2app(W_ArrayBase.descr_delslice),
 __iter__=interp2app(W_ArrayBase.descr_iter),
 __add__=interpindirect2app(W_ArrayBase.descr_add),
 __iadd__=interpindirect2app(W_ArrayBase.descr_inplace_add),
 __mul__=interpindirect2app(W_ArrayBase.descr_mul),
 __imul__=interpindirect2app(W_ArrayBase.descr_inplace_mul),
 __radd__=interp2app(W_ArrayBase.descr_radd),
 __rmul__=interp2app(W_ArrayBase.descr_rmul),
 __repr__=interp2app(W_ArrayBase.descr_repr),
 itemsize=GetSetProperty(descr_itemsize),
 typecode=GetSetProperty(descr_typecode),
 __weakref__=make_weakref_descr(W_ArrayBase),
 append=interpindirect2app(W_ArrayBase.descr_append),
 extend=interp2app(W_ArrayBase.descr_extend),
 count=interpindirect2app(W_ArrayBase.descr_count),
 index=interpindirect2app(W_ArrayBase.descr_index),
 reverse=interpindirect2app(W_ArrayBase.descr_reverse),
 remove=interpindirect2app(W_ArrayBase.descr_remove),
 pop=interpindirect2app(W_ArrayBase.descr_pop),
 insert=interpindirect2app(W_ArrayBase.descr_insert),
 tolist=interp2app(W_ArrayBase.descr_tolist),
 fromlist=interp2app(W_ArrayBase.descr_fromlist),
 tostring=interp2app(W_ArrayBase.descr_tostring),
 fromstring=interp2app(W_ArrayBase.descr_fromstring),
 tofile=interp2app(W_ArrayBase.descr_tofile),
Пример #28
0
    specialname = "__%s__" % (op, )
    rspecialname = "__r%s__" % (op, )
    func, rfunc = make_binary_instance_method(op)
    # fool the gateway logic by giving it a real unbound method
    meth = new.instancemethod(func, None, W_InstanceObject)
    rawdict[specialname] = interp2app(meth)
    rmeth = new.instancemethod(rfunc, None, W_InstanceObject)
    rawdict[rspecialname] = interp2app(rmeth)


def descr_del_dict(space, w_inst):
    # use setdict to raise the error
    w_inst.setdict(space, space.w_None)


dict_descr = GetSetProperty(descr_get_dict, descr_set_dict, descr_del_dict)
dict_descr.name = '__dict__'

W_InstanceObject.typedef = TypeDef(
    "instance",
    __new__=interp2app(descr_instance_new),
    __getattribute__=interp2app(W_InstanceObject.descr_getattribute),
    __setattr__=interp2app(W_InstanceObject.descr_setattr),
    __delattr__=interp2app(W_InstanceObject.descr_delattr),
    __repr__=interp2app(W_InstanceObject.descr_repr),
    __str__=interp2app(W_InstanceObject.descr_str),
    __unicode__=interp2app(W_InstanceObject.descr_unicode),
    __format__=interp2app(W_InstanceObject.descr_format),
    __len__=interp2app(W_InstanceObject.descr_len),
    __getitem__=interp2app(W_InstanceObject.descr_getitem),
    __setitem__=interp2app(W_InstanceObject.descr_setitem),
Пример #29
0
    def __init__(self, space, x=1):
        self.space = space
        self.x = x

    def multiply(self, w_y):
        space = self.space
        y = space.int_w(w_y)
        return space.wrap(self.x * y)

    def fget_x(space, self):
        return space.wrap(self.x)

    def fset_x(space, self, w_value):
        self.x = space.int_w(w_value)


def mytype_new(space, w_subtype, x):
    return space.wrap(W_MyType(space, x))


mytype_new.unwrap_spec = [ObjSpace, W_Root, int]

getset_x = GetSetProperty(W_MyType.fget_x, W_MyType.fset_x, cls=W_MyType)

W_MyType.typedef = TypeDef(
    'MyType',
    __new__=interp2app(mytype_new),
    x=getset_x,
    multiply=interp2app(W_MyType.multiply),
)
Пример #30
0
                # failed, forget w_dict and propagate the exception
                del self.dicts[ident]
                raise
            # ready
            space.threadlocals.atthreadexit(space, finish_thread, self)
        return w_dict

    def descr_local__new__(space, w_subtype, __args__):
        local = space.allocate_instance(Local, w_subtype)
        Local.__init__(local, space, __args__)
        return space.wrap(local)

    def descr_local__init__(self, space):
        # No arguments allowed
        pass


Local.typedef = TypeDef(
    "thread._local",
    __doc__="Thread-local data",
    __new__=interp2app(Local.descr_local__new__.im_func),
    __init__=interp2app(Local.descr_local__init__),
    __dict__=GetSetProperty(descr_get_dict, cls=Local),
)


def finish_thread(w_obj):
    assert isinstance(w_obj, Local)
    ident = thread.get_ident()
    del w_obj.dicts[ident]
Пример #31
0
Detach() - Returns the integer Win32 handle, detaching it from the object

Properties:
handle - The integer Win32 handle.

Operations:
__bool__ - Handles with an open object return true, otherwise false.
__int__ - Converting a handle to an integer returns the Win32 handle.
__cmp__ - Handle objects are compared using the handle value.""",
    __new__=descr_HKEY_new,
    __repr__=interp2app(W_HKEY.descr_repr),
    __int__=interp2app(W_HKEY.descr_int),
    __bool__=interp2app(W_HKEY.descr_bool),
    __enter__=interp2app(W_HKEY.descr__enter__),
    __exit__=interp2app(W_HKEY.descr__exit__),
    handle=GetSetProperty(W_HKEY.descr_handle_get),
    Close=interp2app(W_HKEY.Close),
    Detach=interp2app(W_HKEY.Detach),
)


def hkey_w(w_hkey, space):
    if space.is_w(w_hkey, space.w_None):
        raise oefmt(space.w_TypeError,
                    "None is not a valid HKEY in this context")
    elif isinstance(w_hkey, W_HKEY):
        return w_hkey.hkey
    elif space.isinstance_w(w_hkey, space.w_int):
        if space.is_true(space.lt(w_hkey, space.newint(0))):
            return rffi.cast(rwinreg.HKEY, space.int_w(w_hkey))
        return rffi.cast(rwinreg.HKEY, space.uint_w(w_hkey))
Пример #32
0
        return space.w_None
    return space.newtext(dialect.escapechar)


def _get_quotechar(space, dialect):
    if dialect.quotechar == '\0':
        return space.w_None
    return space.newtext(dialect.quotechar)


W_Dialect.typedef = TypeDef(
    '_csv.Dialect',
    __new__=interp2app(W_Dialect___new__),
    delimiter=interp_attrproperty('delimiter', W_Dialect, wrapfn='newtext'),
    doublequote=interp_attrproperty('doublequote', W_Dialect,
                                    wrapfn='newbool'),
    escapechar=GetSetProperty(_get_escapechar, cls=W_Dialect),
    lineterminator=interp_attrproperty('lineterminator',
                                       W_Dialect,
                                       wrapfn='newtext'),
    quotechar=GetSetProperty(_get_quotechar, cls=W_Dialect),
    quoting=interp_attrproperty('quoting', W_Dialect, wrapfn='newint'),
    skipinitialspace=interp_attrproperty('skipinitialspace',
                                         W_Dialect,
                                         wrapfn='newbool'),
    strict=interp_attrproperty('strict', W_Dialect, wrapfn='newbool'),
    __doc__="""CSV dialect

The Dialect type records CSV parsing and generation options.
""")
Пример #33
0
@jit.unroll_safe
def issubtypedef(a, b):
    from pypy.objspace.std.objecttype import object_typedef
    if b is object_typedef:
        return True
    while a is not b:
        if a is None:
            return False
        a = a.base
    return True

def descr_del_dict(space, w_obj): # blame CPython for the existence of this one
    w_obj.setdict(space, space.newdict())

std_dict_descr = GetSetProperty(descr_get_dict, descr_set_dict, descr_del_dict)
std_dict_descr.name = '__dict__'

def newmethod(descr_new, unwrap_spec=None):
    "NOT_RPYTHON: initialization-time only."
    # this is turned into a static method by the constructor of W_TypeObject.
    return gateway.interp2app(descr_new, unwrap_spec=unwrap_spec)

# ____________________________________________________________
#
# All the code below fishes from the multimethod registration tables
# the descriptors to put into the W_TypeObjects.
#

class TypeCache(SpaceCache):
    def build(cache, typedef):
Пример #34
0
        raise OperationError(space.w_AttributeError, space.wrap("This DebugMergePoint doesn't belong to the main Python JitDriver"))

    def get_bytecode_no(self, space):
        if self.jd_name == pypyjitdriver.name:
            return space.getitem(self.w_greenkey, space.wrap(1))
        raise OperationError(space.w_AttributeError, space.wrap("This DebugMergePoint doesn't belong to the main Python JitDriver"))

    def get_jitdriver_name(self, space):
        return space.wrap(self.jd_name)

WrappedOp.typedef = TypeDef(
    'ResOperation',
    __doc__ = WrappedOp.__doc__,
    __new__ = interp2app(descr_new_resop),
    __repr__ = interp2app(WrappedOp.descr_repr),
    num = GetSetProperty(WrappedOp.descr_num),
    name = GetSetProperty(WrappedOp.descr_name),
    getarg = interp2app(WrappedOp.descr_getarg),
    setarg = interp2app(WrappedOp.descr_setarg),
    result = GetSetProperty(WrappedOp.descr_getresult,
                            WrappedOp.descr_setresult)
)
WrappedOp.acceptable_as_base_class = False

DebugMergePoint.typedef = TypeDef(
    'DebugMergePoint', WrappedOp.typedef,
    __new__ = interp2app(descr_new_dmp),
    greenkey = interp_attrproperty_w("w_greenkey", cls=DebugMergePoint),
    pycode = GetSetProperty(DebugMergePoint.get_pycode),
    bytecode_no = GetSetProperty(DebugMergePoint.get_bytecode_no),
    call_depth = interp_attrproperty("call_depth", cls=DebugMergePoint),