@ExposedNew public static PyObject float_new( PyNewWrapper new_, boolean init, PyType subtype, PyObject[] args, String[] keywords) { ArgParser ap = new ArgParser("float", args, keywords, new String[] {"x"}, 0); PyObject x = ap.getPyObject(0, null); if (x == null) { if (new_.for_type == subtype) { return new PyFloat(0.0); } else { return new PyFloatDerived(subtype, 0.0); } } else { PyFloat floatObject = null; try { floatObject = x.__float__(); } catch (PyException e) { if (e.match(Py.AttributeError)) { // Translate AttributeError to TypeError // XXX: We are using the same message as CPython, even if // it is not strictly correct (instances of types // that implement the __float__ method are also // valid arguments) throw Py.TypeError("float() argument must be a string or a number"); } throw e; } if (new_.for_type == subtype) { return floatObject; } else { return new PyFloatDerived(subtype, floatObject.getValue()); } } }
public void append_json_repr(StringBuffer buf, PyObject py_obj) throws JSONEncodeError { if (py_obj instanceof PyString) append_json_string_repr(buf, ((PyString) py_obj).toString()); // Must test for PyBoolean before PyInteger because former is a subclass of latter. else if (py_obj instanceof PyBoolean) buf.append(((PyBoolean) py_obj).getBooleanValue() ? "true" : "false"); else if (py_obj instanceof PyInteger) buf.append(Integer.toString(((PyInteger) py_obj).getValue())); else if (py_obj instanceof PyLong) { String repr = ((PyLong) py_obj).__repr__().toString(); buf.append(repr.substring(0, repr.length() - 1)); } else if (py_obj instanceof PyFloat) buf.append(Double.toString(((PyFloat) py_obj).getValue())); else if (py_obj instanceof PyStringMap) append_json_string_map_repr(buf, (PyStringMap) py_obj); else if (py_obj instanceof PyDictionary) append_json_dictionary_repr(buf, (PyDictionary) py_obj); else if (py_obj instanceof PySequence) append_json_sequence_repr(buf, (PySequence) py_obj); else if (py_obj instanceof PyNone) buf.append("null"); else if (py_obj.__findattr__("__json__") != null && py_obj.__findattr__("__json__").isCallable()) buf.append(((PyMethod) py_obj.__findattr__("__json__")).__call__().toString()); else throw new JSONEncodeError( "Python '" + ((PyType) py_obj.fastGetClass()).fastGetName() + "' object '" + py_obj.__repr__() + "' is not encodable in JSON"); }
@Override protected Class<?> findClass(String name) throws ClassNotFoundException { PySystemState sys = Py.getSystemState(); ClassLoader sysClassLoader = sys.getClassLoader(); if (sysClassLoader != null) { // sys.classLoader overrides this class loader! return sysClassLoader.loadClass(name); } // Search the sys.path for a .class file matching the named class. PyList path = sys.path; for (int i = 0; i < path.__len__(); i++) { byte[] buffer; PyObject entry = replacePathItem(sys, i, path); if (entry instanceof SyspathArchive) { SyspathArchive archive = (SyspathArchive) entry; buffer = getBytesFromArchive(archive, name); } else { if (!(entry instanceof PyUnicode)) { entry = entry.__str__(); } String dir = entry.toString(); buffer = getBytesFromDir(dir, name); } if (buffer != null) { definePackageForClass(name); return defineClass(name, buffer, 0, buffer.length); } } // couldn't find the .class file on sys.path throw new ClassNotFoundException(name); }
public static PyObject SyntaxError() { PyObject __dict__ = new PyStringMap(); defineSlots(__dict__, "msg", "filename", "lineno", "offset", "text", "print_file_and_line"); __dict__.__setitem__("__init__", bindStaticJavaMethod("__init__", "SyntaxError__init__")); __dict__.__setitem__("__str__", bindStaticJavaMethod("__str__", "SyntaxError__str__")); return __dict__; }
@ExposedMethod(type = MethodType.BINARY, doc = BuiltinDocs.list___rmul___doc) final synchronized PyObject list___rmul__(PyObject o) { if (!o.isIndex()) { return null; } return repeat(o.asIndex(Py.OverflowError)); }
@ExposedMethod(type = MethodType.BINARY, doc = BuiltinDocs.list___imul___doc) final synchronized PyObject list___imul__(PyObject o) { if (!o.isIndex()) { return null; } int count = o.asIndex(Py.OverflowError); int size = size(); if (size == 0 || count == 1) { return this; } if (count < 1) { clear(); return this; } if (size > Integer.MAX_VALUE / count) { throw Py.MemoryError(""); } int newSize = size * count; if (list instanceof ArrayList) { ((ArrayList) list).ensureCapacity(newSize); } List<PyObject> oldList = new ArrayList<PyObject>(list); for (int i = 1; i < count; i++) { list.addAll(oldList); } gListAllocatedStatus = __len__(); // now omit? return this; }
public void __del_derived__() { PyType self_type = getType(); PyObject impl = self_type.lookup("__del__"); if (impl != null) { impl.__get__(this, self_type).__call__(); } }
/** * Initialize all __slots__ arguments in the specified dict to None. * * @param self a PyObject dict */ private static void initSlots(PyObject self) { for (PyObject name : self.__findattr__("__slots__").asIterable()) { if (!(name instanceof PyString)) { continue; } self.__setattr__((PyString) name, Py.None); } }
public PyObject __iter__() { PyType self_type = getType(); PyObject impl = self_type.lookup("__iter__"); if (impl != null) return impl.__get__(this, self_type).__call__(); impl = self_type.lookup("__getitem__"); if (impl == null) return super.__iter__(); return new PySequenceIter(this); }
public PyObject __call__(PyObject args[], String keywords[]) { PyType self_type = getType(); PyObject impl = self_type.lookup("__call__"); if (impl != null) { return impl.__get__(this, self_type).__call__(args, keywords); } return super.__call__(args, keywords); }
private static PyObject buildClass( PyObject dict, String classname, String superclass, PyObject classDict, String doc) { classDict.__setitem__("__doc__", Py.newString(doc)); PyType type = (PyType) Py.makeClass("exceptions." + classname, dict.__finditem__(superclass), classDict); type.builtin = true; dict.__setitem__(classname, type); return type; }
public static PyObject EnvironmentError() { PyObject dict = new PyStringMap(); defineSlots(dict, "errno", "strerror", "filename"); dict.__setitem__("__init__", bindStaticJavaMethod("__init__", "EnvironmentError__init__")); dict.__setitem__("__str__", bindStaticJavaMethod("__str__", "EnvironmentError__str__")); dict.__setitem__( "__reduce__", bindStaticJavaMethod("__reduce__", "EnvironmentError__reduce__")); return dict; }
public void __delete__(PyObject obj) { PyType self_type = getType(); PyObject impl = self_type.lookup("__delete__"); if (impl != null) { impl.__get__(this, self_type).__call__(obj); return; } super.__delete__(obj); }
public void __delitem__(PyObject key) { // ??? PyType self_type = getType(); PyObject impl = self_type.lookup("__delitem__"); if (impl != null) { impl.__get__(this, self_type).__call__(key); return; } super.__delitem__(key); }
public int __len__() { PyType self_type = getType(); PyObject impl = self_type.lookup("__len__"); if (impl != null) { PyObject res = impl.__get__(this, self_type).__call__(); return res.asInt(); } return super.__len__(); }
public void __delattr__(String name) { PyType self_type = getType(); PyObject impl = self_type.lookup("__delattr__"); if (impl != null) { impl.__get__(this, self_type).__call__(PyString.fromInterned(name)); return; } super.__delattr__(name); }
@ExposedMethod(doc = BuiltinDocs.list_count_doc) final synchronized int list_count(PyObject o) { int count = 0; for (PyObject item : list) { if (item.equals(o)) { count++; } } return count; }
public static void SystemExit__init__(PyObject self, PyObject[] args, String[] kwargs) { PyBaseException.TYPE.invoke("__init__", self, args, kwargs); initSlots(self); if (args.length == 1) { self.__setattr__("code", args[0]); } else if (args.length > 1) { self.__setattr__("code", new PyTuple(args)); } }
public PyObject __ixor__(PyObject other) { PyType self_type = getType(); PyObject impl = self_type.lookup("__ixor__"); if (impl != null) { PyObject res = impl.__get__(this, self_type).__call__(other); if (res == Py.NotImplemented) return null; return res; } return super.__ixor__(other); }
public PyObject __int__() { PyType self_type = getType(); PyObject impl = self_type.lookup("__int__"); if (impl != null) { PyObject res = impl.__get__(this, self_type).__call__(); if (res instanceof PyInteger || res instanceof PyLong) return res; throw Py.TypeError("__int__" + " should return an integer"); } return super.__int__(); }
// Return value >= 0 is the index where the sequences differs. // -1: reached the end of o1 without a difference // -2: reached the end of both seqeunces without a difference // -3: reached the end of o2 without a difference private static int cmp(PyObject o1, int ol1, PyObject o2, int ol2) { if (ol1 < 0) ol1 = o1.__len__(); if (ol2 < 0) ol2 = o2.__len__(); int i = 0; for (; i < ol1 && i < ol2; i++) { if (!o1.__getitem__(i)._eq(o2.__getitem__(i)).__nonzero__()) return i; } if (ol1 == ol2) return -2; return (ol1 < ol2) ? -1 : -3; }
final void file_writelines(PyObject a) { PyObject iter = Py.iter(a, "writelines() requires an iterable argument"); PyObject item = null; while ((item = iter.__iternext__()) != null) { if (!(item instanceof PyString)) throw Py.TypeError("writelines() argument must be a " + "sequence of strings"); write(item.toString()); } }
public PyObject __get__(PyObject obj, PyObject type) { PyType self_type = getType(); PyObject impl = self_type.lookup("__get__"); if (impl != null) { if (obj == null) obj = Py.None; if (type == null) type = Py.None; return impl.__get__(this, self_type).__call__(obj, type); } return super.__get__(obj, type); }
public int __len__() { PyType self_type = getType(); PyObject impl = self_type.lookup("__len__"); if (impl != null) { PyObject res = impl.__get__(this, self_type).__call__(); if (res instanceof PyInteger) return ((PyInteger) res).getValue(); throw Py.TypeError("__len__ should return a int"); } return super.__len__(); }
public void setDict(PyObject newDict) { if (newDict instanceof PyStringMap || newDict instanceof PyDictionary) { dict = newDict; if (dict.__finditem__(PyString.fromInterned("__del__")) != null && !JyAttribute.hasAttr(this, JyAttribute.FINALIZE_TRIGGER_ATTR)) { FinalizeTrigger.ensureFinalizer(this); } } else { throw Py.TypeError("__dict__ must be set to a Dictionary " + newDict.getClass().getName()); } }
public PyFloat __float__() { PyType self_type = getType(); PyObject impl = self_type.lookup("__float__"); if (impl != null) { PyObject res = impl.__get__(this, self_type).__call__(); if (res instanceof PyFloat) return (PyFloat) res; throw Py.TypeError( "__float__" + " returned non-" + "float" + " (type " + res.getType().fastGetName() + ")"); } return super.__float__(); }
public static void UnicodeTranslateError__init__( PyObject self, PyObject[] args, String[] kwargs) { PyBaseException.TYPE.invoke("__init__", self, args, kwargs); ArgParser ap = new ArgParser( "__init__", args, kwargs, new String[] {"object", "start", "end", "reason"}, 4); self.__setattr__("object", ap.getPyObjectByType(0, PyUnicode.TYPE)); self.__setattr__("start", ap.getPyObjectByType(1, PyInteger.TYPE)); self.__setattr__("end", ap.getPyObjectByType(2, PyInteger.TYPE)); self.__setattr__("reason", ap.getPyObjectByType(3, PyString.TYPE)); }
public void __setattr__(String name, PyObject value) { PyType self_type = getType(); PyObject impl = self_type.lookup("__setattr__"); if (impl != null) { impl.__get__(this, self_type).__call__(PyString.fromInterned(name), value); // CPython does not support instance-acquired finalizers. // So we don't check for __del__ here. return; } super.__setattr__(name, value); }
public PyUnicode __unicode__() { PyType self_type = getType(); PyObject impl = self_type.lookup("__unicode__"); if (impl != null) { PyObject res = impl.__get__(this, self_type).__call__(); if (res instanceof PyUnicode) return (PyUnicode) res; if (res instanceof PyString) return new PyUnicode((PyString) res); throw Py.TypeError("__unicode__" + " should return a " + "unicode"); } return super.__unicode__(); }
public Object __coerce_ex__(PyObject o) { PyType self_type = getType(); PyObject impl = self_type.lookup("__coerce__"); if (impl != null) { PyObject res = impl.__get__(this, self_type).__call__(o); if (res == Py.NotImplemented) return Py.None; if (!(res instanceof PyTuple)) throw Py.TypeError("__coerce__ didn't return a 2-tuple"); return ((PyTuple) res).getArray(); } return super.__coerce_ex__(o); }