Example #1
0
    def errors_get_w(self, space):
        return space.w_None

    def newlines_get_w(self, space):
        return space.w_None


W_TextIOBase.typedef = TypeDef(
    '_io._TextIOBase',
    W_IOBase.typedef,
    __new__=generic_new_descr(W_TextIOBase),
    read=interp2app(W_TextIOBase.read_w),
    readline=interp2app(W_TextIOBase.readline_w),
    write=interp2app(W_TextIOBase.write_w),
    detach=interp2app(W_TextIOBase.detach_w),
    encoding=interp_attrproperty_w("w_encoding", W_TextIOBase),
    newlines=GetSetProperty(W_TextIOBase.newlines_get_w),
    errors=GetSetProperty(W_TextIOBase.errors_get_w),
)


def _determine_encoding(space, encoding):
    if encoding is not None:
        return space.newtext(encoding)

    try:
        w_locale = space.call_method(space.builtin, '__import__',
                                     space.newtext('locale'))
        w_encoding = space.call_method(w_locale, 'getpreferredencoding')
    except OperationError as e:
        # getpreferredencoding() may also raise ImportError
Example #2
0
            space.w_TypeError,
            space.wrap("Trying to set readonly attribute %s on property" %
                       (attr, )))

    setattr.unwrap_spec = ['self', ObjSpace, str, W_Root]


W_Property.typedef = TypeDef(
    'property',
    __doc__=
    '''property(fget=None, fset=None, fdel=None, doc=None) -> property attribute

fget is a function to be used for getting an attribute value, and likewise
fset is a function for setting, and fdel a function for deleting, an
attribute.  Typical use is to define a managed attribute x:
class C(object):
    def getx(self): return self.__x
    def setx(self, value): self.__x = value
    def delx(self): del self.__x
    x = property(getx, setx, delx, "I am the 'x' property.")''',
    __new__=interp2app(W_Property.new.im_func),
    __get__=interp2app(W_Property.get),
    __set__=interp2app(W_Property.set),
    __delete__=interp2app(W_Property.delete),
    __getattribute__=interp2app(W_Property.getattribute),
    __setattr__=interp2app(W_Property.setattr),
    fdel=interp_attrproperty_w('w_fdel', W_Property),
    fget=interp_attrproperty_w('w_fget', W_Property),
    fset=interp_attrproperty_w('w_fset', W_Property),
)
Example #3
0
when opened for writing or appending; it will be truncated when
opened for writing.  Add a 'b' to the mode for binary files.
Add a '+' to the mode to allow simultaneous reading and writing.
If the buffering argument is given, 0 means unbuffered, 1 means line
buffered, and larger numbers specify the buffer size.
Add a 'U' to mode to open the file for input with universal newline
support.  Any line ending in the input file will be seen as a '\n'
in Python.  Also, a file so opened gains the attribute 'newlines';
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__),
    writelines = interp2app(W_File.file_writelines),
Example #4
0
W_SRE_Pattern.typedef = TypeDef(
    'SRE_Pattern',
    __new__      = interp2app(SRE_Pattern__new__),
    __copy__     = interp2app(W_SRE_Pattern.cannot_copy_w),
    __deepcopy__ = interp2app(W_SRE_Pattern.cannot_copy_w),
    __weakref__  = make_weakref_descr(W_SRE_Pattern),
    findall      = interp2app(W_SRE_Pattern.findall_w),
    finditer     = interp2app(W_SRE_Pattern.finditer_w),
    match        = interp2app(W_SRE_Pattern.match_w),
    scanner      = interp2app(W_SRE_Pattern.finditer_w),    # reuse finditer()
    search       = interp2app(W_SRE_Pattern.search_w),
    split        = interp2app(W_SRE_Pattern.split_w),
    sub          = interp2app(W_SRE_Pattern.sub_w),
    subn         = interp2app(W_SRE_Pattern.subn_w),
    flags        = interp_attrproperty('flags', W_SRE_Pattern),
    groupindex   = interp_attrproperty_w('w_groupindex', W_SRE_Pattern),
    groups       = interp_attrproperty('num_groups', W_SRE_Pattern),
    pattern      = interp_attrproperty_w('w_pattern', W_SRE_Pattern),
)

# ____________________________________________________________
#
# SRE_Match class

class W_SRE_Match(Wrappable):
    flatten_cache = None

    def __init__(self, srepat, ctx):
        self.space = srepat.space
        self.srepat = srepat
        self.ctx = ctx
Example #5
0
    if asking_for_bound:
        return space.wrap(Method(space, w_function, w_obj, w_cls))
    else:
        return w_function

def cclassmethod_descr_get(space, w_function, w_obj, w_cls=None):
    if not w_cls:
        w_cls = space.type(w_obj)
    return space.wrap(Method(space, w_function, w_cls, space.w_None))


W_PyCFunctionObject.typedef = TypeDef(
    'builtin_function_or_method',
    __call__ = interp2app(cfunction_descr_call),
    __doc__ = GetSetProperty(W_PyCFunctionObject.get_doc),
    __module__ = interp_attrproperty_w('w_module', cls=W_PyCFunctionObject),
    __name__ = interp_attrproperty('name', cls=W_PyCFunctionObject),
    )
W_PyCFunctionObject.typedef.acceptable_as_base_class = False

W_PyCMethodObject.typedef = TypeDef(
    'method',
    __get__ = interp2app(cmethod_descr_get),
    __call__ = interp2app(cmethod_descr_call),
    __name__ = interp_attrproperty('name', cls=W_PyCMethodObject),
    __objclass__ = interp_attrproperty_w('w_objclass', cls=W_PyCMethodObject),
    __repr__ = interp2app(W_PyCMethodObject.descr_method_repr),
    )
W_PyCMethodObject.typedef.acceptable_as_base_class = False

W_PyCClassMethodObject.typedef = TypeDef(
Example #6
0
W_SRE_Pattern.typedef = TypeDef(
    'SRE_Pattern',
    __new__=interp2app(SRE_Pattern__new__),
    __copy__=interp2app(W_SRE_Pattern.cannot_copy_w),
    __deepcopy__=interp2app(W_SRE_Pattern.cannot_copy_w),
    __weakref__=make_weakref_descr(W_SRE_Pattern),
    findall=interp2app(W_SRE_Pattern.findall_w),
    finditer=interp2app(W_SRE_Pattern.finditer_w),
    match=interp2app(W_SRE_Pattern.match_w),
    scanner=interp2app(W_SRE_Pattern.finditer_w),  # reuse finditer()
    search=interp2app(W_SRE_Pattern.search_w),
    split=interp2app(W_SRE_Pattern.split_w),
    sub=interp2app(W_SRE_Pattern.sub_w),
    subn=interp2app(W_SRE_Pattern.subn_w),
    flags=interp_attrproperty('flags', W_SRE_Pattern),
    groupindex=interp_attrproperty_w('w_groupindex', W_SRE_Pattern),
    groups=interp_attrproperty('num_groups', W_SRE_Pattern),
    pattern=interp_attrproperty_w('w_pattern', W_SRE_Pattern),
)

# ____________________________________________________________
#
# SRE_Match class


class W_SRE_Match(Wrappable):
    flatten_cache = None

    def __init__(self, srepat, ctx):
        self.space = srepat.space
        self.srepat = srepat
Example #7
0
W_Property.typedef = TypeDef(
    'property',
    __doc__ = '''property(fget=None, fset=None, fdel=None, doc=None) -> property attribute

fget is a function to be used for getting an attribute value, and likewise
fset is a function for setting, and fdel a function for deleting, an
attribute.  Typical use is to define a managed attribute x:
class C(object):
    def getx(self): return self.__x
    def setx(self, value): self.__x = value
    def delx(self): del self.__x
    x = property(getx, setx, delx, "I am the 'x' property.")''',
    __new__ = generic_new_descr(W_Property),
    __init__ = interp2app(W_Property.init),
    __get__ = interp2app(W_Property.get),
    __set__ = interp2app(W_Property.set),
    __delete__ = interp2app(W_Property.delete),
    fdel = interp_attrproperty_w('w_fdel', W_Property),
    fget = interp_attrproperty_w('w_fget', W_Property),
    fset = interp_attrproperty_w('w_fset', W_Property),
    getter = interp2app(W_Property.getter),
    setter = interp2app(W_Property.setter),
    deleter = interp2app(W_Property.deleter),
)
# This allows there to be a __doc__ of the property type and a __doc__
# descriptor for the instances.
W_Property.typedef.rawdict['__doc__'] = interp_attrproperty_w('w_doc',
                                                              W_Property)

Example #8
0
when opened for writing or appending; it will be truncated when
opened for writing.  Add a 'b' to the mode for binary files.
Add a '+' to the mode to allow simultaneous reading and writing.
If the buffering argument is given, 0 means unbuffered, 1 means line
buffered, and larger numbers specify the buffer size.
Add a 'U' to mode to open the file for input with universal newline
support.  Any line ending in the input file will be seen as a '\n'
in Python.  Also, a file so opened gains the attribute 'newlines';
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)",
                             wrapfn="newtext"),
    encoding=interp_attrproperty('encoding',
                                 cls=W_File,
                                 wrapfn="newtext_or_none"),
    errors=interp_attrproperty('errors', cls=W_File, wrapfn="newtext_or_none"),
    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"),
Example #9
0
    w_strict=None,
):
    """
    csv_writer = csv.writer(fileobj [, dialect='excel']
                            [optional keyword args])
    for row in sequence:
        csv_writer.writerow(row)

    [or]

    csv_writer = csv.writer(fileobj [, dialect='excel']
                            [optional keyword args])
    csv_writer.writerows(rows)

    The \"fileobj\" argument can be any object that supports the file API."""
    dialect = _build_dialect(space, w_dialect, w_delimiter, w_doublequote,
                             w_escapechar, w_lineterminator, w_quotechar,
                             w_quoting, w_skipinitialspace, w_strict)
    return W_Writer(space, dialect, w_fileobj)


W_Writer.typedef = TypeDef('_csv.writer',
                           dialect=interp_attrproperty_w('dialect', W_Writer),
                           writerow=interp2app(W_Writer.writerow),
                           writerows=interp2app(W_Writer.writerows),
                           __doc__="""CSV writer

Writer objects are responsible for generating tabular data
in CSV format from sequence input.""")
W_Writer.typedef.acceptable_as_base_class = False
Example #10
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),
)
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):
    """Return a new instance method object, with func being any
    callable object func is the function that will be called when the
Example #11
0
            status = roci.OCIAttrGet(self.handle, roci.OCI_HTYPE_SPOOL,
                                     rffi.cast(roci.dvoidp, valueptr),
                                     lltype.nullptr(roci.Ptr(roci.ub4).TO),
                                     oci_attr_code,
                                     self.environment.errorHandle)
            return space.wrap(valueptr[0])
        finally:
            lltype.free(valueptr, flavor='raw')

    return GetSetProperty(fget, cls=W_SessionPool)


W_SessionPool.typedef = TypeDef(
    "SessionPool",
    __new__=interp2app(W_SessionPool.descr_new.im_func),
    acquire=interp2app(W_SessionPool.acquire),
    release=interp2app(W_SessionPool.release),
    drop=interp2app(W_SessionPool.drop),
    username=interp_attrproperty_w('w_username', W_SessionPool),
    password=interp_attrproperty_w('w_password', W_SessionPool),
    tnsentry=interp_attrproperty_w('w_tnsentry', W_SessionPool),
    min=interp_attrproperty('minSessions', W_SessionPool),
    max=interp_attrproperty('maxSessions', W_SessionPool),
    increment=interp_attrproperty('sessionIncrement', W_SessionPool),
    homogeneous=interp_attrproperty('homogeneous', W_SessionPool),
    opened=computedProperty(roci.OCI_ATTR_SPOOL_OPEN_COUNT, roci.ub4),
    busy=computedProperty(roci.OCI_ATTR_SPOOL_BUSY_COUNT, roci.ub4),
    timeout=computedProperty(roci.OCI_ATTR_SPOOL_TIMEOUT, roci.ub4),
    getmode=computedProperty(roci.OCI_ATTR_SPOOL_GETMODE, roci.ub1),
)
Example #12
0
            else:
                pos = line.find(self.readnl[0], start, end)
                if pos >= 0:
                    return -1, pos - start
                return -1, size


W_TextIOBase.typedef = TypeDef(
    '_io._TextIOBase', W_IOBase.typedef,
    __new__ = generic_new_descr(W_TextIOBase),

    read = interp2app(W_TextIOBase.read_w),
    readline = interp2app(W_TextIOBase.readline_w),
    write = interp2app(W_TextIOBase.write_w),
    detach = interp2app(W_TextIOBase.detach_w),
    encoding = interp_attrproperty_w("w_encoding", W_TextIOBase),
    newlines = GetSetProperty(W_TextIOBase.newlines_get_w),
    errors = GetSetProperty(W_TextIOBase.errors_get_w),
)


def _determine_encoding(space, encoding):
    if encoding is not None:
        return space.wrap(encoding)

    try:
        w_locale = space.call_method(space.builtin, '__import__',
                                     space.wrap('locale'))
        w_encoding = space.call_method(w_locale, 'getpreferredencoding')
    except OperationError as e:
        # getpreferredencoding() may also raise ImportError
Example #13
0
    getattribute.unwrap_spec = ["self", ObjSpace, str]

    def setattr(self, space, attr, w_value):
        raise OperationError(space.w_TypeError, space.wrap("Trying to set readonly attribute %s on property" % (attr,)))

    setattr.unwrap_spec = ["self", ObjSpace, str, W_Root]


W_Property.typedef = TypeDef(
    "property",
    __doc__="""property(fget=None, fset=None, fdel=None, doc=None) -> property attribute

fget is a function to be used for getting an attribute value, and likewise
fset is a function for setting, and fdel a function for deleting, an
attribute.  Typical use is to define a managed attribute x:
class C(object):
    def getx(self): return self.__x
    def setx(self, value): self.__x = value
    def delx(self): del self.__x
    x = property(getx, setx, delx, "I am the 'x' property.")""",
    __new__=interp2app(W_Property.new.im_func),
    __get__=interp2app(W_Property.get),
    __set__=interp2app(W_Property.set),
    __delete__=interp2app(W_Property.delete),
    __getattribute__=interp2app(W_Property.getattribute),
    __setattr__=interp2app(W_Property.setattr),
    fdel=interp_attrproperty_w("w_fdel", W_Property),
    fget=interp_attrproperty_w("w_fget", W_Property),
    fset=interp_attrproperty_w("w_fset", W_Property),
)
Example #14
0
        w_shape = args_w[0]

        # shape in W_ArrayInstance-speak is somewhat different from what
        # e.g. numpy thinks of it: self.shape contains the info (itemcode,
        # size, etc.) of a single entry; length is user-facing shape
        self.length = space.int_w(space.getitem(w_shape, space.newint(0)))


W_LowLevelView.typedef = TypeDef(
    'LowLevelView',
    __repr__=interp2app(W_LowLevelView.descr_repr),
    __setitem__=interp2app(W_LowLevelView.descr_setitem),
    __getitem__=interp2app(W_LowLevelView.descr_getitem),
    __len__=interp2app(W_LowLevelView.getlength),
    buffer=GetSetProperty(W_LowLevelView.getbuffer),
    shape=interp_attrproperty_w('shape', W_LowLevelView),
    free=interp2app(W_LowLevelView.free),
    byptr=interp2app(W_LowLevelView.byptr),
    itemaddress=interp2app(W_LowLevelView.descr_itemaddress),
    reshape=interp2app(W_LowLevelView.reshape),
)
W_LowLevelView.typedef.acceptable_as_base_class = False


class W_ArrayOfInstances(W_Root):
    _attrs_ = ['converter', 'baseaddress', 'clssize', 'length']
    _immutable_fields_ = ['converter', 'baseaddress', 'clssize']

    def __init__(self, space, clsdecl, address, length, dimensions):
        from pypy.module._cppyy import converter
        name = clsdecl.name
Example #15
0
    def __repr__(self):
        return '<Field %s %s>' % (self.name, self.w_ffitype.name)


@unwrap_spec(name='text')
def descr_new_field(space, w_type, name, w_ffitype):
    w_ffitype = space.interp_w(W_FFIType, w_ffitype)
    return W_Field(name, w_ffitype)


W_Field.typedef = TypeDef(
    'Field',
    __new__=interp2app(descr_new_field),
    name=interp_attrproperty('name', W_Field, wrapfn="newtext_or_none"),
    ffitype=interp_attrproperty_w('w_ffitype', W_Field),
    offset=interp_attrproperty('offset', W_Field, wrapfn="newint"),
)

# ==============================================================================


class FFIStructOwner(object):
    """
    The only job of this class is to stay outside of the reference cycle
    W__StructDescr -> W_FFIType -> W__StructDescr and free the ffistruct
    """
    def __init__(self, ffistruct):
        self.ffistruct = ffistruct

    @must_be_light_finalizer
Example #16
0
            status = roci.OCIAttrGet(
                self.handle, roci.OCI_HTYPE_SPOOL,
                rffi.cast(roci.dvoidp, valueptr),
                lltype.nullptr(roci.Ptr(roci.ub4).TO),
                oci_attr_code,
                self.environment.errorHandle)
            return space.wrap(valueptr[0])
        finally:
            lltype.free(valueptr, flavor='raw')
    return GetSetProperty(fget, cls=W_SessionPool)

W_SessionPool.typedef = TypeDef(
    "SessionPool",
    __new__ = interp2app(W_SessionPool.descr_new.im_func),
    acquire = interp2app(W_SessionPool.acquire),
    release = interp2app(W_SessionPool.release),
    drop = interp2app(W_SessionPool.drop),

    username = interp_attrproperty_w('w_username', W_SessionPool),
    password = interp_attrproperty_w('w_password', W_SessionPool),
    tnsentry = interp_attrproperty_w('w_tnsentry', W_SessionPool),
    min = interp_attrproperty('minSessions', W_SessionPool),
    max = interp_attrproperty('maxSessions', W_SessionPool),
    increment = interp_attrproperty('sessionIncrement', W_SessionPool),
    homogeneous = interp_attrproperty('homogeneous', W_SessionPool),
    opened = computedProperty(roci.OCI_ATTR_SPOOL_OPEN_COUNT, roci.ub4),
    busy = computedProperty(roci.OCI_ATTR_SPOOL_BUSY_COUNT, roci.ub4),
    timeout = computedProperty(roci.OCI_ATTR_SPOOL_TIMEOUT, roci.ub4),
    getmode = computedProperty(roci.OCI_ATTR_SPOOL_GETMODE, roci.ub1),
    )
Example #17
0
    getarg=interp2app(WrappedOp.descr_getarg),
    setarg=interp2app(WrappedOp.descr_setarg),
    result=GetSetProperty(WrappedOp.descr_getresult,
                          WrappedOp.descr_setresult),
    offset=interp_attrproperty("offset", cls=WrappedOp),
)
WrappedOp.acceptable_as_base_class = False

DebugMergePoint.typedef = TypeDef(
    'DebugMergePoint',
    WrappedOp.typedef,
    __new__=interp2app(descr_new_dmp),
    __doc__=DebugMergePoint.__doc__,
    greenkey=interp_attrproperty_w(
        "w_greenkey",
        cls=DebugMergePoint,
        doc="Representation of place where the loop was compiled. "
        "In the case of the main interpreter loop, it's a triplet "
        "(code, ofs, is_profiled)"),
    pycode=GetSetProperty(DebugMergePoint.get_pycode),
    bytecode_no=GetSetProperty(DebugMergePoint.get_bytecode_no,
                               doc="offset in the bytecode"),
    call_depth=interp_attrproperty("call_depth",
                                   cls=DebugMergePoint,
                                   doc="Depth of calls within this loop"),
    call_id=interp_attrproperty(
        "call_id",
        cls=DebugMergePoint,
        doc="Number of applevel function traced in this loop"),
    jitdriver_name=GetSetProperty(
        DebugMergePoint.get_jitdriver_name,
        doc="Name of the jitdriver 'pypyjit' in the case "
Example #18
0
        if not space.exception_match(w_exc_type, self.w_ExpectedException):
            self.report_error(space.text_w(space.repr(w_exc_type)))
        self.w_value = w_exc_value   # for the 'value' app-level attribute
        return space.w_True     # suppress the exception

    def report_error(self, got):
        space = self.space
        raise oefmt(space.w_AssertionError,
                    "raises() expected %s, but got %s",
                    space.text_w(space.repr(self.w_ExpectedException)),
                    got)

W_RaisesContextManager.typedef = typedef.TypeDef("RaisesContextManager",
    __enter__ = gateway.interp2app_temp(W_RaisesContextManager.enter),
    __exit__ = gateway.interp2app_temp(W_RaisesContextManager.exit),
    value = typedef.interp_attrproperty_w('w_value', cls=W_RaisesContextManager)
    )

def pypyraises(space, w_ExpectedException, w_expr=None, __args__=None):
    """A built-in function providing the equivalent of py.test.raises()."""
    if w_expr is None:
        return W_RaisesContextManager(space, w_ExpectedException)
    args_w, kwds_w = __args__.unpack()
    if space.isinstance_w(w_expr, space.w_text):
        if args_w:
            raise oefmt(space.w_TypeError,
                        "raises() takes no argument after a string expression")
        expr = space.unwrap(w_expr)
        source = py.code.Source(expr)
        frame = space.getexecutioncontext().gettopframe()
        w_locals = frame.getdictscope()
Example #19
0
        for i in range(len(value)):
            ll_buffer[start + i] = value[i]

    def buffer_w(self, space, flags):
        return RawBufferView(
            RawFFIBuffer(self), self.shape.itemcode, self.shape.size)


W_ArrayInstance.typedef = TypeDef(
    'ArrayInstance',
    __repr__    = interp2app(W_ArrayInstance.descr_repr),
    __setitem__ = interp2app(W_ArrayInstance.descr_setitem),
    __getitem__ = interp2app(W_ArrayInstance.descr_getitem),
    __len__     = interp2app(W_ArrayInstance.getlength),
    buffer      = GetSetProperty(W_ArrayInstance.getbuffer),
    shape       = interp_attrproperty_w('shape', W_ArrayInstance),
    free        = interp2app(W_ArrayInstance.free),
    byptr       = interp2app(W_ArrayInstance.byptr),
    itemaddress = interp2app(W_ArrayInstance.descr_itemaddress),
)
W_ArrayInstance.typedef.acceptable_as_base_class = False


class W_ArrayInstanceAutoFree(W_ArrayInstance):
    def __init__(self, space, shape, length):
        W_ArrayInstance.__init__(self, space, shape, length, 0)

    @rgc.must_be_light_finalizer
    def __del__(self):
        if self.ll_buffer:
            self._free()
Example #20
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),
    __len__ = interp2app(W_Dtype.descr_len),

    __reduce__ = interp2app(W_Dtype.descr_reduce),
    __setstate__ = interp2app(W_Dtype.descr_setstate),

    type = interp_attrproperty_w("w_box_type", cls=W_Dtype),
    kind = interp_attrproperty("kind", cls=W_Dtype),
    char = interp_attrproperty("char", cls=W_Dtype),
    num = interp_attrproperty("num", cls=W_Dtype),
    byteorder = interp_attrproperty("byteorder", cls=W_Dtype),
    itemsize = GetSetProperty(W_Dtype.descr_get_itemsize),
    alignment = GetSetProperty(W_Dtype.descr_get_alignment),

    subdtype = GetSetProperty(W_Dtype.descr_get_subdtype),
    str = GetSetProperty(W_Dtype.descr_get_str),
    name = interp_attrproperty("name", cls=W_Dtype),
    base = GetSetProperty(W_Dtype.descr_get_base),
    shape = GetSetProperty(W_Dtype.descr_get_shape),
    isnative = GetSetProperty(W_Dtype.descr_get_isnative),
    fields = GetSetProperty(W_Dtype.descr_get_fields),
    names = GetSetProperty(W_Dtype.descr_get_names),
Example #21
0
W_Cursor.typedef = TypeDef(
    'Cursor',
    execute = interp2app(W_Cursor.execute),
    executemany = interp2app(W_Cursor.executemany),
    prepare = interp2app(W_Cursor.prepare),
    fetchone = interp2app(W_Cursor.fetchone),
    fetchmany = interp2app(W_Cursor.fetchmany),
    fetchall = interp2app(W_Cursor.fetchall),
    close = interp2app(W_Cursor.close),
    bindnames = interp2app(W_Cursor.bindnames),
    callfunc = interp2app(W_Cursor.callfunc),
    callproc = interp2app(W_Cursor.callproc),
    var = interp2app(W_Cursor.var),
    arrayvar = interp2app(W_Cursor.arrayvar),
    setinputsizes = interp2app(W_Cursor.setinputsizes),
    setoutputsize = interp2app(W_Cursor.setoutputsize),

    __iter__ = interp2app(W_Cursor.descr_iter),
    next = interp2app(W_Cursor.descr_next),

    arraysize = GetSetProperty(W_Cursor.arraysize_get,
                               W_Cursor.arraysize_set),
    bindarraysize = GetSetProperty(W_Cursor.bindarraysize_get,
                                   W_Cursor.bindarraysize_set),
    rowcount = interp_attrproperty('rowCount', W_Cursor),
    statement = interp_attrproperty_w('w_statement', W_Cursor),
    bindvars = GetSetProperty(W_Cursor.bindvars_get),
    fetchvars = GetSetProperty(W_Cursor.fetchvars_get),
    description = GetSetProperty(W_Cursor.getDescription),
)
Example #22
0
        self.start = space.int_w(w_value)

    def get_char_ord(self, p):
        raise NotImplementedError


getset_start = GetSetProperty(W_State.fget_start,
                              W_State.fset_start,
                              cls=W_State)
getset_string_position = GetSetProperty(W_State.fget_string_position,
                                        W_State.fset_string_position,
                                        cls=W_State)

W_State.typedef = TypeDef(
    "W_State",
    string=interp_attrproperty_w("w_string", W_State),
    start=getset_start,
    end=interp_attrproperty("end", W_State),
    string_position=getset_string_position,
    pos=interp_attrproperty("pos", W_State),
    lastindex=interp_attrproperty("lastindex", W_State),
    reset=interp2app(W_State.w_reset),
    create_regs=interp2app(W_State.w_create_regs),
)


class W_StringState(W_State):
    if THREE_VERSIONS_OF_CORE:
        rsre.insert_sre_methods(locals(), 'str')

    def unwrap_object(self):
Example #23
0
        w_dialect,
        w_delimiter,
        w_doublequote,
        w_escapechar,
        w_lineterminator,
        w_quotechar,
        w_quoting,
        w_skipinitialspace,
        w_strict,
    )
    return W_Reader(space, dialect, w_iter)


W_Reader.typedef = TypeDef(
    "_csv.reader",
    dialect=interp_attrproperty_w("dialect", W_Reader),
    line_num=interp_attrproperty("line_num", W_Reader),
    __iter__=interp2app(W_Reader.iter_w),
    __next__=interp2app(W_Reader.next_w),
    __doc__="""CSV reader

Reader objects are responsible for reading and parsing tabular data
in CSV format.""",
)
W_Reader.typedef.acceptable_as_base_class = False

# ____________________________________________________________


class FieldLimit:
    limit = 128 * 1024  # max parsed field size
Example #24
0

W_Range.typedef = TypeDef("range",
    __new__          = interp2app(W_Range.descr_new.im_func),
    __repr__         = interp2app(W_Range.descr_repr),
    __getitem__      = interp2app(W_Range.descr_getitem),
    __iter__         = interp2app(W_Range.descr_iter),
    __len__          = interp2app(W_Range.descr_len),
    __reversed__     = interp2app(W_Range.descr_reversed),
    __reduce__       = interp2app(W_Range.descr_reduce),
    __contains__     = interp2app(W_Range.descr_contains),
    __eq__           = interp2app(W_Range.descr_eq),
    __hash__         = interp2app(W_Range.descr_hash),
    count            = interp2app(W_Range.descr_count),
    index            = interp2app(W_Range.descr_index),
    start            = interp_attrproperty_w('w_start', cls=W_Range),
    stop             = interp_attrproperty_w('w_stop', cls=W_Range),
    step             = interp_attrproperty_w('w_step', cls=W_Range),
)
W_Range.typedef.acceptable_as_base_class = False


class W_AbstractRangeIterator(W_Root):

    def descr_iter(self, space):
        return self

    def descr_len(self, space):
        raise NotImplementedError

    def descr_next(self, space):
Example #25
0
    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),
    offset = interp_attrproperty("offset", cls=WrappedOp),
)
WrappedOp.acceptable_as_base_class = False

DebugMergePoint.typedef = TypeDef(
    'DebugMergePoint', WrappedOp.typedef,
    __new__ = interp2app(descr_new_dmp),
    __doc__ = DebugMergePoint.__doc__,
    greenkey = interp_attrproperty_w("w_greenkey", cls=DebugMergePoint,
               doc="Representation of place where the loop was compiled. "
                    "In the case of the main interpreter loop, it's a triplet "
                    "(code, ofs, is_profiled)"),
    pycode = GetSetProperty(DebugMergePoint.get_pycode),
    bytecode_no = GetSetProperty(DebugMergePoint.get_bytecode_no,
                                 doc="offset in the bytecode"),
    call_depth = interp_attrproperty("call_depth", cls=DebugMergePoint,
                                     doc="Depth of calls within this loop"),
    call_id = interp_attrproperty("call_id", cls=DebugMergePoint,
                     doc="Number of applevel function traced in this loop"),
    jitdriver_name = GetSetProperty(DebugMergePoint.get_jitdriver_name,
                     doc="Name of the jitdriver 'pypyjit' in the case "
                                    "of the main interpreter loop"),
)
DebugMergePoint.acceptable_as_base_class = False

Example #26
0
        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:
            self._free()
Example #27
0
        # XXX kill me?  This is mostly to make tests happy, raising
        # a TypeError instead of an AttributeError and using "readonly"
        # instead of "read-only" in the error message :-/
        raise OperationError(space.w_TypeError, space.wrap(
            "Trying to set readonly attribute %s on property" % (attr,)))
    setattr.unwrap_spec = ['self', ObjSpace, str, W_Root]

W_Property.typedef = TypeDef(
    'property',
    __doc__ = '''property(fget=None, fset=None, fdel=None, doc=None) -> property attribute

fget is a function to be used for getting an attribute value, and likewise
fset is a function for setting, and fdel a function for deleting, an
attribute.  Typical use is to define a managed attribute x:
class C(object):
    def getx(self): return self.__x
    def setx(self, value): self.__x = value
    def delx(self): del self.__x
    x = property(getx, setx, delx, "I am the 'x' property.")''',
    __new__ = interp2app(W_Property.new.im_func),
    __get__ = interp2app(W_Property.get),
    __set__ = interp2app(W_Property.set),
    __delete__ = interp2app(W_Property.delete),
    __getattribute__ = interp2app(W_Property.getattribute),
    __setattr__ = interp2app(W_Property.setattr),
    fdel = interp_attrproperty_w('w_fdel', W_Property),
    fget = interp_attrproperty_w('w_fget', W_Property),
    fset = interp_attrproperty_w('w_fset', W_Property),
)

Example #28
0
            if fmax == 0:
                fmax = 1  # special case to let "int x:1" receive "1"
        else:
            is_signed = False
            fmin = r_longlong(0)
            fmax = r_longlong((r_ulonglong(1) << self.bitsize) - 1)
        if value < fmin or value > fmax:
            raise oefmt(
                space.w_OverflowError,
                "value %d outside the range allowed by the bit field "
                "width: %d <= x <= %d", value, fmin, fmax)
        rawmask = ((r_ulonglong(1) << self.bitsize) - 1) << self.bitshift
        rawvalue = r_ulonglong(value) << self.bitshift
        rawfielddata = misc.read_raw_unsigned_data(cdata, ctype.size)
        rawfielddata = (rawfielddata & ~rawmask) | (rawvalue & rawmask)
        if is_signed:
            misc.write_raw_signed_data(cdata, rawfielddata, ctype.size)
        else:
            misc.write_raw_unsigned_data(cdata, rawfielddata, ctype.size)


W_CField.typedef = TypeDef(
    '_cffi_backend.CField',
    type=interp_attrproperty_w('ctype', W_CField),
    offset=interp_attrproperty('offset', W_CField, wrapfn="newint"),
    bitshift=interp_attrproperty('bitshift', W_CField, wrapfn="newint"),
    bitsize=interp_attrproperty('bitsize', W_CField, wrapfn="newint"),
    flags=interp_attrproperty('flags', W_CField, wrapfn="newint"),
)
W_CField.typedef.acceptable_as_base_class = False
Example #29
0
    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),
    call_id = interp_attrproperty("call_id", cls=DebugMergePoint),
    jitdriver_name = GetSetProperty(DebugMergePoint.get_jitdriver_name),
)
DebugMergePoint.acceptable_as_base_class = False


Example #30
0
                              W_PyCFunctionObject.fset_module,
                              W_PyCFunctionObject.fdel_module),
    __name__=interp_attrproperty('name',
                                 cls=W_PyCFunctionObject,
                                 wrapfn="newtext_or_none"),
)
W_PyCFunctionObject.typedef.acceptable_as_base_class = False

W_PyCMethodObject.typedef = TypeDef(
    'method_descriptor',
    __get__=interp2app(cmethod_descr_get),
    __call__=interp2app(W_PyCMethodObject.descr_call),
    __name__=interp_attrproperty('name',
                                 cls=W_PyCMethodObject,
                                 wrapfn="newtext_or_none"),
    __objclass__=interp_attrproperty_w('w_objclass', cls=W_PyCMethodObject),
    __repr__=interp2app(W_PyCMethodObject.descr_method_repr),
)
W_PyCMethodObject.typedef.acceptable_as_base_class = False

W_PyCClassMethodObject.typedef = TypeDef(
    'classmethod',
    __get__=interp2app(cclassmethod_descr_get),
    __call__=interp2app(W_PyCClassMethodObject.descr_call),
    __name__=interp_attrproperty('name',
                                 cls=W_PyCClassMethodObject,
                                 wrapfn="newtext_or_none"),
    __objclass__=interp_attrproperty_w('w_objclass',
                                       cls=W_PyCClassMethodObject),
    __repr__=interp2app(W_PyCClassMethodObject.descr_method_repr),
)
Example #31
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)
Example #32
0
    except OperationError as e:
        if not e.match(space, space.w_AttributeError):
            raise
        w_type = w_objtype

    if space.issubtype_w(w_type, w_starttype):
        return w_type
    raise oefmt(space.w_TypeError,
                "super(type, obj): obj must be an instance or subtype of type")

W_Super.typedef = TypeDef(
    'super',
    __new__          = generic_new_descr(W_Super),
    __init__         = interp2app(W_Super.descr_init),
    __repr__         = interp2app(W_Super.descr_repr),
    __thisclass__    = interp_attrproperty_w("w_starttype", W_Super),
    __self__         = interp_attrproperty_w("w_self", W_Super),
    __self_class__   = interp_attrproperty_w("w_objtype", W_Super),
    __getattribute__ = interp2app(W_Super.getattribute),
    __get__          = interp2app(W_Super.get),
    __doc__          =     """\
super(type) -> unbound super object
super(type, obj) -> bound super object; requires isinstance(obj, type)
super(type, type2) -> bound super object; requires issubclass(type2, type)

Typical use to call a cooperative superclass method:

class C(B):
    def meth(self, arg):
        super(C, self).meth(arg)"""
)
Example #33
0
            raise
        w_type = w_objtype

    if space.issubtype_w(w_type, w_starttype):
        return w_type
    raise oefmt(
        space.w_TypeError,
        "super(type, obj): obj must be an instance or subtype of type")


W_Super.typedef = TypeDef(
    'super',
    __new__=generic_new_descr(W_Super),
    __init__=interp2app(W_Super.descr_init),
    __repr__=interp2app(W_Super.descr_repr),
    __thisclass__=interp_attrproperty_w("w_starttype", W_Super),
    __self__=interp_attrproperty_w("w_self", W_Super),
    __self_class__=interp_attrproperty_w("w_objtype", W_Super),
    __getattribute__=interp2app(W_Super.getattribute),
    __get__=interp2app(W_Super.get),
    __doc__="""\
super(type) -> unbound super object
super(type, obj) -> bound super object; requires isinstance(obj, type)
super(type, type2) -> bound super object; requires issubclass(type2, type)

Typical use to call a cooperative superclass method:

class C(B):
    def meth(self, arg):
        super(C, self).meth(arg)""")
Example #34
0
    of input for each iteration, such as a file object or a list.  The
    optional \"dialect\" parameter is discussed below.  The function
    also accepts optional keyword arguments which override settings
    provided by the dialect.

    The returned object is an iterator.  Each iteration returns a row
    of the CSV file (which can span multiple input lines)"""
    w_iter = space.iter(w_iterator)
    dialect = _build_dialect(space, w_dialect, w_delimiter, w_doublequote,
                             w_escapechar, w_lineterminator, w_quotechar,
                             w_quoting, w_skipinitialspace, w_strict)
    return W_Reader(space, dialect, w_iter)

W_Reader.typedef = TypeDef(
        '_csv.reader',
        dialect = interp_attrproperty_w('dialect', W_Reader),
        line_num = interp_attrproperty('line_num', W_Reader),
        __iter__ = interp2app(W_Reader.iter_w),
        next = interp2app(W_Reader.next_w),
        __doc__ = """CSV reader

Reader objects are responsible for reading and parsing tabular data
in CSV format.""")
W_Reader.typedef.acceptable_as_base_class = False

# ____________________________________________________________

class FieldLimit:
    limit = 128 * 1024   # max parsed field size
field_limit = FieldLimit()
Example #35
0
        return space.call_function(w_type, w_getter, w_setter, w_deleter, w_doc)


W_Property.typedef = TypeDef(
    "property",
    __doc__="""property(fget=None, fset=None, fdel=None, doc=None) -> property attribute

fget is a function to be used for getting an attribute value, and likewise
fset is a function for setting, and fdel a function for deleting, an
attribute.  Typical use is to define a managed attribute x:
class C(object):
    def getx(self): return self.__x
    def setx(self, value): self.__x = value
    def delx(self): del self.__x
    x = property(getx, setx, delx, "I am the 'x' property.")""",
    __new__=generic_new_descr(W_Property),
    __init__=interp2app(W_Property.init),
    __get__=interp2app(W_Property.get),
    __set__=interp2app(W_Property.set),
    __delete__=interp2app(W_Property.delete),
    fdel=interp_attrproperty_w("w_fdel", W_Property),
    fget=interp_attrproperty_w("w_fget", W_Property),
    fset=interp_attrproperty_w("w_fset", W_Property),
    getter=interp2app(W_Property.getter),
    setter=interp2app(W_Property.setter),
    deleter=interp2app(W_Property.deleter),
)
# This allows there to be a __doc__ of the property type and a __doc__
# descriptor for the instances.
W_Property.typedef.rawdict["__doc__"] = interp_attrproperty_w("w_doc", W_Property)
Example #36
0
        self.readable = True

        self._init(space)
        self._reader_reset_buf()
        self.state = STATE_OK

W_BufferedReader.typedef = TypeDef(
    'BufferedReader', W_BufferedIOBase.typedef,
    __new__ = generic_new_descr(W_BufferedReader),
    __init__  = interp2app(W_BufferedReader.descr_init),
    __module__ = "_io",

    read = interp2app(W_BufferedReader.read_w),
    peek = interp2app(W_BufferedReader.peek_w),
    read1 = interp2app(W_BufferedReader.read1_w),
    raw = interp_attrproperty_w("w_raw", cls=W_BufferedReader),

    # from the mixin class
    __repr__ = interp2app(W_BufferedReader.repr_w),
    readable = interp2app(W_BufferedReader.readable_w),
    writable = interp2app(W_BufferedReader.writable_w),
    seekable = interp2app(W_BufferedReader.seekable_w),
    seek = interp2app(W_BufferedReader.seek_w),
    tell = interp2app(W_BufferedReader.tell_w),
    close = interp2app(W_BufferedReader.close_w),
    flush = interp2app(W_BufferedReader.simple_flush_w), # Not flush_w!
    detach = interp2app(W_BufferedReader.detach_w),
    truncate = interp2app(W_BufferedReader.truncate_w),
    fileno = interp2app(W_BufferedReader.fileno_w),
    isatty = interp2app(W_BufferedReader.isatty_w),
    closed = GetSetProperty(W_BufferedReader.closed_get_w),
Example #37
0
    of input for each iteration, such as a file object or a list.  The
    optional \"dialect\" parameter is discussed below.  The function
    also accepts optional keyword arguments which override settings
    provided by the dialect.

    The returned object is an iterator.  Each iteration returns a row
    of the CSV file (which can span multiple input lines)"""
    w_iter = space.iter(w_iterator)
    dialect = _build_dialect(space, w_dialect, w_delimiter, w_doublequote,
                             w_escapechar, w_lineterminator, w_quotechar,
                             w_quoting, w_skipinitialspace, w_strict)
    return W_Reader(space, dialect, w_iter)

W_Reader.typedef = TypeDef(
        '_csv.reader',
        dialect = interp_attrproperty_w('dialect', W_Reader),
        line_num = interp_attrproperty('line_num', W_Reader),
        __iter__ = interp2app(W_Reader.iter_w),
        __next__ = interp2app(W_Reader.next_w),
        __doc__ = """CSV reader

Reader objects are responsible for reading and parsing tabular data
in CSV format.""")
W_Reader.typedef.acceptable_as_base_class = False

# ____________________________________________________________

class FieldLimit:
    limit = 128 * 1024   # max parsed field size
field_limit = FieldLimit()
Example #38
0
            try:
                status = roci.OCIErrorGet(
                    handle, 1, lltype.nullptr(roci.oratext.TO), codeptr,
                    textbuf, BUFSIZE, handleType)
                if status != roci.OCI_SUCCESS:
                    raise OperationError(
                        get(space).w_InternalError,
                        space.wrap("No Oracle error?"))

                self.code = codeptr[0]
                self.w_message = config.w_string(space, textbuf)
            finally:
                lltype.free(codeptr, flavor='raw')
                rffi.keep_buffer_alive_until_here(textbuf, text)

            if config.WITH_UNICODE:
                # XXX remove double zeros at the end
                pass

    def desc_str(self):
        return self.w_message

W_Error.typedef = TypeDef(
    'Error',
    __str__ = interp2app(W_Error.desc_str),
    code = interp_attrproperty('code', W_Error),
    message = interp_attrproperty_w('w_message', W_Error))


Example #39
0
W_Property.typedef = TypeDef(
    'property',
    __doc__=
    '''property(fget=None, fset=None, fdel=None, doc=None) -> property attribute

fget is a function to be used for getting an attribute value, and likewise
fset is a function for setting, and fdel a function for deleting, an
attribute.  Typical use is to define a managed attribute x:
class C(object):
    def getx(self): return self.__x
    def setx(self, value): self.__x = value
    def delx(self): del self.__x
    x = property(getx, setx, delx, "I am the 'x' property.")''',
    __new__=generic_new_descr(W_Property),
    __init__=interp2app(W_Property.init),
    __get__=interp2app(W_Property.get),
    __set__=interp2app(W_Property.set),
    __delete__=interp2app(W_Property.delete),
    fdel=interp_attrproperty_w('w_fdel', W_Property),
    fget=interp_attrproperty_w('w_fget', W_Property),
    fset=interp_attrproperty_w('w_fset', W_Property),
    getter=interp2app(W_Property.getter),
    setter=interp2app(W_Property.setter),
    deleter=interp2app(W_Property.deleter),
)
# This allows there to be a __doc__ of the property type and a __doc__
# descriptor for the instances.
W_Property.typedef.rawdict['__doc__'] = interp_attrproperty_w(
    'w_doc', W_Property)
Example #40
0
    def fget_string_position(space, self):
        return space.wrap(self.string_position)

    def fset_string_position(space, self, w_value):
        self.start = space.int_w(w_value)

    def get_char_ord(self, p):
        raise NotImplementedError

getset_start = GetSetProperty(W_State.fget_start, W_State.fset_start, cls=W_State)
getset_string_position = GetSetProperty(W_State.fget_string_position,
                                     W_State.fset_string_position, cls=W_State)

W_State.typedef = TypeDef("W_State",
    string = interp_attrproperty_w("w_string", W_State),
    start = getset_start,
    end = interp_attrproperty("end", W_State),
    string_position = getset_string_position,
    pos = interp_attrproperty("pos", W_State),
    lastindex = interp_attrproperty("lastindex", W_State),
    reset = interp2app(W_State.w_reset),
    create_regs = interp2app(W_State.w_create_regs),
)


class W_StringState(W_State):
    if THREE_VERSIONS_OF_CORE:
        rsre.insert_sre_methods(locals(), 'str')

    def unwrap_object(self):
Example #41
0
        compatVar = VT_String(cursor, cursor.arraySize, MAX_STRING_CHARS)

        # call stored procedure
        cursor._call(space, "dbms_utility.db_version",
                     None, space.newlist([space.wrap(versionVar),
                                          space.wrap(compatVar)]))

        # retrieve value
        self.w_version = versionVar.getValue(space, 0)
        return self.w_version

W_Connection.typedef = TypeDef(
    "Connection",
    __new__ = interp2app(W_Connection.descr_new.im_func,
                         unwrap_spec=W_Connection.descr_new.unwrap_spec),
    username = interp_attrproperty_w('w_username', W_Connection),
    password = interp_attrproperty_w('w_password', W_Connection),
    tnsentry = interp_attrproperty_w('w_tnsentry', W_Connection),

    close = interp2app(W_Connection.close),
    commit = interp2app(W_Connection.commit),
    rollback = interp2app(W_Connection.rollback),

    cursor = interp2app(W_Connection.newCursor),

    encoding = GetSetProperty(W_Connection.get_encoding),
    nationalencoding = GetSetProperty(W_Connection.get_nationalencoding),
    maxBytesPerCharacter = GetSetProperty(W_Connection.get_maxbytespercharacter),
    version = GetSetProperty(W_Connection.get_version),
    )
Example #42
0
        return space.wrap(Method(space, w_function, w_obj, w_cls))
    else:
        return w_function


def cclassmethod_descr_get(space, w_function, w_obj, w_cls=None):
    if not w_cls:
        w_cls = space.type(w_obj)
    return space.wrap(Method(space, w_function, w_cls, space.w_None))


W_PyCFunctionObject.typedef = TypeDef(
    'builtin_function_or_method',
    __call__=interp2app(cfunction_descr_call),
    __doc__=GetSetProperty(W_PyCFunctionObject.get_doc),
    __module__=interp_attrproperty_w('w_module', cls=W_PyCFunctionObject),
    __name__=interp_attrproperty('name', cls=W_PyCFunctionObject),
)
W_PyCFunctionObject.typedef.acceptable_as_base_class = False

W_PyCMethodObject.typedef = TypeDef(
    'method',
    __get__=interp2app(cmethod_descr_get),
    __call__=interp2app(cmethod_descr_call),
    __name__=interp_attrproperty('name', cls=W_PyCMethodObject),
    __objclass__=interp_attrproperty_w('w_objclass', cls=W_PyCMethodObject),
    __repr__=interp2app(W_PyCMethodObject.descr_method_repr),
)
W_PyCMethodObject.typedef.acceptable_as_base_class = False

W_PyCClassMethodObject.typedef = TypeDef(
Example #43
0
        return space.newlist(self.fetchVariables)


W_Cursor.typedef = TypeDef(
    'Cursor',
    execute=interp2app(W_Cursor.execute),
    executemany=interp2app(W_Cursor.executemany),
    prepare=interp2app(W_Cursor.prepare),
    fetchone=interp2app(W_Cursor.fetchone),
    fetchmany=interp2app(W_Cursor.fetchmany),
    fetchall=interp2app(W_Cursor.fetchall),
    close=interp2app(W_Cursor.close),
    bindnames=interp2app(W_Cursor.bindnames),
    callfunc=interp2app(W_Cursor.callfunc),
    callproc=interp2app(W_Cursor.callproc),
    var=interp2app(W_Cursor.var),
    arrayvar=interp2app(W_Cursor.arrayvar),
    setinputsizes=interp2app(W_Cursor.setinputsizes),
    setoutputsize=interp2app(W_Cursor.setoutputsize),
    __iter__=interp2app(W_Cursor.descr_iter),
    next=interp2app(W_Cursor.descr_next),
    arraysize=GetSetProperty(W_Cursor.arraysize_get, W_Cursor.arraysize_set),
    bindarraysize=GetSetProperty(W_Cursor.bindarraysize_get,
                                 W_Cursor.bindarraysize_set),
    rowcount=interp_attrproperty('rowCount', W_Cursor),
    statement=interp_attrproperty_w('w_statement', W_Cursor),
    bindvars=GetSetProperty(W_Cursor.bindvars_get),
    fetchvars=GetSetProperty(W_Cursor.fetchvars_get),
    description=GetSetProperty(W_Cursor.getDescription),
)
Example #44
0
W_SRE_Pattern.typedef = TypeDef(
    'SRE_Pattern',
    __new__=interp2app(SRE_Pattern__new__),
    __copy__=interp2app(W_SRE_Pattern.cannot_copy_w),
    __deepcopy__=interp2app(W_SRE_Pattern.cannot_copy_w),
    __weakref__=make_weakref_descr(W_SRE_Pattern),
    findall=interp2app(W_SRE_Pattern.findall_w),
    finditer=interp2app(W_SRE_Pattern.finditer_w),
    match=interp2app(W_SRE_Pattern.match_w),
    scanner=interp2app(W_SRE_Pattern.finditer_w),  # reuse finditer()
    search=interp2app(W_SRE_Pattern.search_w),
    split=interp2app(W_SRE_Pattern.split_w),
    sub=interp2app(W_SRE_Pattern.sub_w),
    subn=interp2app(W_SRE_Pattern.subn_w),
    flags=interp_attrproperty('flags', W_SRE_Pattern, wrapfn="newint"),
    groupindex=interp_attrproperty_w('w_groupindex', W_SRE_Pattern),
    groups=interp_attrproperty('num_groups', W_SRE_Pattern, wrapfn="newint"),
    pattern=interp_attrproperty_w('w_pattern', W_SRE_Pattern),
)
W_SRE_Pattern.typedef.acceptable_as_base_class = False

# ____________________________________________________________
#
# SRE_Match class


class W_SRE_Match(W_Root):
    flatten_cache = None

    def __init__(self, srepat, ctx):
        self.space = srepat.space
Example #45
0
                  w_strict           = None,
                  ):
    """
    csv_writer = csv.writer(fileobj [, dialect='excel']
                            [optional keyword args])
    for row in sequence:
        csv_writer.writerow(row)

    [or]

    csv_writer = csv.writer(fileobj [, dialect='excel']
                            [optional keyword args])
    csv_writer.writerows(rows)

    The \"fileobj\" argument can be any object that supports the file API."""
    dialect = _build_dialect(space, w_dialect, w_delimiter, w_doublequote,
                             w_escapechar, w_lineterminator, w_quotechar,
                             w_quoting, w_skipinitialspace, w_strict)
    return W_Writer(space, dialect, w_fileobj)

W_Writer.typedef = TypeDef(
        '_csv.writer',
        dialect = interp_attrproperty_w('dialect', W_Writer),
        writerow = interp2app(W_Writer.writerow),
        writerows = interp2app(W_Writer.writerows),
        __doc__ = """CSV writer

Writer objects are responsible for generating tabular data
in CSV format from sequence input.""")
W_Writer.typedef.acceptable_as_base_class = False
Example #46
0
        # allocate version and compatibility variables
        versionVar = VT_String(cursor, cursor.arraySize, MAX_STRING_CHARS)
        compatVar = VT_String(cursor, cursor.arraySize, MAX_STRING_CHARS)

        # call stored procedure
        cursor._call(
            space, "dbms_utility.db_version", None,
            space.newlist([space.wrap(versionVar),
                           space.wrap(compatVar)]))

        # retrieve value
        self.w_version = versionVar.getValue(space, 0)
        return self.w_version


W_Connection.typedef = TypeDef(
    "Connection",
    __new__=interp2app(W_Connection.descr_new.im_func),
    username=interp_attrproperty_w('w_username', W_Connection),
    password=interp_attrproperty_w('w_password', W_Connection),
    tnsentry=interp_attrproperty_w('w_tnsentry', W_Connection),
    close=interp2app(W_Connection.close),
    commit=interp2app(W_Connection.commit),
    rollback=interp2app(W_Connection.rollback),
    cursor=interp2app(W_Connection.newCursor),
    encoding=GetSetProperty(W_Connection.get_encoding),
    nationalencoding=GetSetProperty(W_Connection.get_nationalencoding),
    maxBytesPerCharacter=GetSetProperty(W_Connection.get_maxbytespercharacter),
    version=GetSetProperty(W_Connection.get_version),
)
Example #47
0
    raise operationerrfmt(space.w_TypeError, msg, w_dtype)


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),
    __len__=interp2app(W_Dtype.descr_len),
    __reduce__=interp2app(W_Dtype.descr_reduce),
    __setstate__=interp2app(W_Dtype.descr_setstate),
    type=interp_attrproperty_w("w_box_type", cls=W_Dtype),
    kind=interp_attrproperty("kind", cls=W_Dtype),
    char=interp_attrproperty("char", cls=W_Dtype),
    num=interp_attrproperty("num", cls=W_Dtype),
    byteorder=interp_attrproperty("byteorder", cls=W_Dtype),
    itemsize=GetSetProperty(W_Dtype.descr_get_itemsize),
    alignment=GetSetProperty(W_Dtype.descr_get_alignment),
    subdtype=GetSetProperty(W_Dtype.descr_get_subdtype),
    str=GetSetProperty(W_Dtype.descr_get_str),
    name=interp_attrproperty("name", cls=W_Dtype),
    base=GetSetProperty(W_Dtype.descr_get_base),
    shape=GetSetProperty(W_Dtype.descr_get_shape),
    isnative=GetSetProperty(W_Dtype.descr_get_isnative),
    fields=GetSetProperty(W_Dtype.descr_get_fields),
    names=GetSetProperty(W_Dtype.descr_get_names),
)
Example #48
0
        self.readable = True

        self._init(space)
        self._reader_reset_buf()
        self.state = STATE_OK

W_BufferedReader.typedef = TypeDef(
    'BufferedReader', W_BufferedIOBase.typedef,
    __new__ = generic_new_descr(W_BufferedReader),
    __init__  = interp2app(W_BufferedReader.descr_init),
    __module__ = "_io",

    read = interp2app(W_BufferedReader.read_w),
    peek = interp2app(W_BufferedReader.peek_w),
    read1 = interp2app(W_BufferedReader.read1_w),
    raw = interp_attrproperty_w("w_raw", cls=W_BufferedReader),

    # from the mixin class
    __repr__ = interp2app(W_BufferedReader.repr_w),
    readable = interp2app(W_BufferedReader.readable_w),
    writable = interp2app(W_BufferedReader.writable_w),
    seekable = interp2app(W_BufferedReader.seekable_w),
    seek = interp2app(W_BufferedReader.seek_w),
    tell = interp2app(W_BufferedReader.tell_w),
    close = interp2app(W_BufferedReader.close_w),
    flush = interp2app(W_BufferedReader.simple_flush_w), # Not flush_w!
    detach = interp2app(W_BufferedReader.detach_w),
    truncate = interp2app(W_BufferedReader.truncate_w),
    fileno = interp2app(W_BufferedReader.fileno_w),
    isatty = interp2app(W_BufferedReader.isatty_w),
    closed = GetSetProperty(W_BufferedReader.closed_get_w),
Example #49
0
                    raise
                w_type = w_objtype
            if not space.is_true(space.issubtype(w_type, w_starttype)):
                raise OperationError(space.w_TypeError,
                    space.wrap("super(type, obj): "
                               "obj must be an instance or subtype of type"))
    # XXX the details of how allocate_instance() should be used are not
    # really well defined
    w_result = space.allocate_instance(W_Super, w_subtype)
    W_Super.__init__(w_result, space, w_starttype, w_type, w_obj_or_type)
    return w_result

W_Super.typedef = TypeDef(
    'super',
    __new__          = interp2app(descr_new_super),
    __thisclass__    = interp_attrproperty_w("w_starttype", W_Super),
    __getattribute__ = interp2app(W_Super.getattribute),
    __get__          = interp2app(W_Super.get),
    __doc__          =     """super(type) -> unbound super object
super(type, obj) -> bound super object; requires isinstance(obj, type)
super(type, type2) -> bound super object; requires issubclass(type2, type)

Typical use to call a cooperative superclass method:

class C(B):
    def meth(self, arg):
        super(C, self).meth(arg)"""
)


class W_Property(W_Root):