From 9687231832c72787a2ce3adff1755b716177eaf2 Mon Sep 17 00:00:00 2001 From: Johnathon Selstad Date: Wed, 12 Aug 2026 22:39:53 -0700 Subject: [PATCH 01/12] Fix type.__subclasscheck__ for indirect subclasses issubclass(C, A) returned False for A <- B <- C when A's metaclass is not type (the custom-metaclass path delegates to type.__subclasscheck__, which only checked tp_bases). This also broke zero-argument super() inside __new__ for such hierarchies. Walk the full MRO instead. Co-Authored-By: Claude Fable 5 --- www/src/py_type.js | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/www/src/py_type.js b/www/src/py_type.js index c87ec5406..0ddec9bb1 100644 --- a/www/src/py_type.js +++ b/www/src/py_type.js @@ -1773,7 +1773,9 @@ type_funcs.__subclasscheck__ = function(self, subclass) { if (subclass.tp_bases === undefined) { return self === _b_.object } - return subclass.tp_bases.indexOf(self) > -1 + // walk the full MRO, not only the direct bases: a class is a subclass + // of its indirect ancestors too + return $B.get_mro(subclass).indexOf(self) > -1 } type_funcs.__subclasses__ = function(cls) { From a4a8d0536856ef407e4f6e9ada02a0bea0381ec6 Mon Sep 17 00:00:00 2001 From: Johnathon Selstad Date: Wed, 12 Aug 2026 22:39:53 -0700 Subject: [PATCH 02/12] Use CPython-like slot dispatch for unary operators and abs() -obj / +obj / ~obj / abs(obj) resolved the dunder on the class and called it with the instance, bypassing the descriptor protocol. A dunder defined as a zero-argument staticmethod (as in sympy.core.numbers Zero/One/ NegativeOne) then failed with 'takes 0 positional arguments but 1 was given'. New helper $B.call_special_unary emulates CPython's _PyObject_LookupSpecial: search_in_mro + tp_descr_get, then call with no arguments. Co-Authored-By: Claude Fable 5 --- www/src/ast_to_js.js | 8 +++++-- www/src/py_builtin_functions.js | 40 +++++++++++++++++++++++---------- 2 files changed, 34 insertions(+), 14 deletions(-) diff --git a/www/src/ast_to_js.js b/www/src/ast_to_js.js index c7ab2fe8b..2fbcd76c7 100644 --- a/www/src/ast_to_js.js +++ b/www/src/ast_to_js.js @@ -4103,8 +4103,12 @@ $B.ast.UnaryOp.prototype.to_js = function(scopes) { return -operand + '' } } - var method = opclass2dunder[this.op.constructor.$name] - return `$B.$call($B.$getattr($B.get_class(locals.$result = ${operand}), '${method}'), locals.$result)` + var method = opclass2dunder[this.op.constructor.$name], + op_repr = {UAdd: '+', USub: '-', Invert: '~'}[this.op.constructor.$name] + // Use CPython-like slot dispatch: resolve the method on the type with + // the descriptor protocol, so that dunders defined as zero-argument + // staticmethods (as in sympy.core.numbers) are called without arguments. + return `$B.call_special_unary(${operand}, '${method}', 'unary ${op_repr}')` } $B.ast.While.prototype.to_js = function(scopes) { diff --git a/www/src/py_builtin_functions.js b/www/src/py_builtin_functions.js index 9eef739dc..29ac7e3e5 100644 --- a/www/src/py_builtin_functions.js +++ b/www/src/py_builtin_functions.js @@ -52,18 +52,9 @@ _b_.__build_class__ = function() { _b_.abs = function(obj) { check_nb_args_no_kw('abs', 1, arguments) - - var klass = $B.get_class(obj) - try { - var method = $B.$getattr(klass, "__abs__") - } catch (err) { - if ($B.is_exc(err, [_b_.AttributeError])) { - $B.RAISE(_b_.TypeError, "Bad operand type for abs(): '" + - $B.class_name(obj) + "'") - } - throw err - } - return $B.$call(method, obj) + // use CPython-like slot dispatch (descriptor protocol on the type), + // cf. $B.call_special_unary + return $B.call_special_unary(obj, '__abs__', 'abs()') } _b_.aiter = function(async_iterable) { @@ -712,6 +703,31 @@ $B.search_in_mro = function(klass, attr, _default) { return _default } +$B.call_special_unary = function(obj, name, op_repr) { + // Emulates CPython's slot dispatch for unary operations: resolve `name` + // on the type (not the instance), apply the descriptor protocol with the + // instance, then call the result with no argument. In particular, a + // dunder defined as a zero-argument staticmethod is called without the + // instance, like in CPython. + var klass = $B.get_class(obj), + raw = $B.search_in_mro(klass, name, $B.NULL) + if (raw === $B.NULL) { + $B.RAISE(_b_.TypeError, + `bad operand type for ${op_repr}: '${$B.class_name(obj)}'`) + } + if (typeof raw == 'function') { + // fast path: plain method; binding to obj then calling with no + // argument is equivalent to calling with obj + return $B.$call(raw, obj) + } + var descr_get = raw.ob_type && raw.ob_type.tp_descr_get + if (descr_get) { + return $B.$call(descr_get(raw, obj, klass)) + } + // non-descriptor class attribute: "bound" to nothing, call with no args + return $B.$call(raw) +} + $B.search_in_dict = function(obj, attr, _default) { if ($B.get_dict(obj)) { try { From 999a16c373b6e1c8363debd2d77739dff0cc1d43 Mon Sep 17 00:00:00 2001 From: Johnathon Selstad Date: Wed, 12 Aug 2026 22:39:53 -0700 Subject: [PATCH 03/12] Fix globals of code run by exec()/eval() with distinct globals and locals Functions, classes and comprehensions defined by exec(src, g, l) got frames whose globals slot referenced the exec *locals* object, so their bodies raised NameError for names present in g (breaks mpmath's exec-generated operators). New make_globals_name() returns the name of the actual globals object for exec scopes; also used for augmented assignment to global names, and unbound-name resolution now searches the exec globals after the locals. Co-Authored-By: Claude Fable 5 --- www/src/ast_to_js.js | 34 ++++++++++++++++++++++++++++------ 1 file changed, 28 insertions(+), 6 deletions(-) diff --git a/www/src/ast_to_js.js b/www/src/ast_to_js.js index 2fbcd76c7..ee6ceb465 100644 --- a/www/src/ast_to_js.js +++ b/www/src/ast_to_js.js @@ -279,6 +279,21 @@ function make_scope_name(scopes, scope) { return scope_name } +function make_globals_name(scopes) { + // Name of the JS object that holds the global namespace. + // This is normally the root scope's namespace object (at module level, + // locals and globals are the same object), but code run by exec() or + // eval() may have distinct globals and locals: the globals object is + // then referenced by namespaces.global_name (cf. py_eval_exec.js). + // Using the root locals object in that case gave functions defined in + // exec() a global namespace that ignored the "globals" argument. + var ns = scopes.namespaces + if (ns && ns.exec_locals !== ns.exec_globals) { + return ns.global_name + } + return make_scope_name(scopes, scopes[0]) +} + function make_search_namespaces(scopes) { var namespaces = [] for (var scope of scopes.slice().reverse()) { @@ -288,6 +303,13 @@ function make_search_namespaces(scopes) { namespaces.push('$B.exec_scope') } namespaces.push(make_scope_name(scopes, scope)) + var ns = scopes.namespaces + if (scope.is_exec_scope && ns && + ns.exec_locals !== ns.exec_globals) { + // exec()/eval() with distinct globals and locals: unbound names + // must also be searched in the globals object, after locals + namespaces.push(ns.global_name) + } } namespaces.push('_b_') return namespaces @@ -930,7 +952,7 @@ function make_comp(scopes) { var comp = {ast:this, id, type, varnames, module_name: scopes[0].name, locals_name: make_scope_name(scopes), - globals_name: make_scope_name(scopes, scopes[0])} + globals_name: make_globals_name(scopes)} indent() if (prefix.length > plen + tab.length) { @@ -1604,7 +1626,7 @@ $B.ast.AugAssign.prototype.to_js = function(scopes) { // The left part of the assignment must be an attribute of a // namespace (global or local), not a call to $B.resolve let left_scope = scope.resolve == 'global' ? - make_scope_name(scopes, scopes[0]) : 'locals' + make_globals_name(scopes) : 'locals' js = prefix + `${left_scope}.${this.target.id} = $B.augm_assign(` + make_ref(this.target.id, scopes, scope, this.target) + `, '${iop}', ${value})` } else { @@ -1818,7 +1840,7 @@ $B.ast.ClassDef.prototype.to_js = function(scopes) { locals_name = 'locals_' + qualified_scope_name(scopes, class_scope), ref = this.name + make_id(), glob = scopes[0].name, - globals_name = make_scope_name(scopes, scopes[0]), + globals_name = make_globals_name(scopes), decorators = [], decorated = false for (let dec of this.decorator_list) { @@ -2358,7 +2380,7 @@ function transform_args(scopes) { function type_param_in_def(tp, ref, scopes) { var gname = scopes[0].name, - globals_name = make_scope_name(scopes, scopes[0]) + globals_name = make_globals_name(scopes) var js = '' var name, param_type = tp.constructor.$name @@ -2435,7 +2457,7 @@ $B.ast.FunctionDef.prototype.to_js = function(scopes) { var func_name_scope = bind(this.name, scopes) var gname = scopes[0].name, - globals_name = make_scope_name(scopes, scopes[0]) + globals_name = make_globals_name(scopes) var decorators = [], decorated = false, @@ -2934,7 +2956,7 @@ $B.ast.GeneratorExp.prototype.to_js = function(scopes) { var comp = {ast:this, id, type: 'genexpr', varnames, module_name: scopes[0].name, locals_name: make_scope_name(scopes), - globals_name: make_scope_name(scopes, scopes[0])} + globals_name: make_globals_name(scopes)} indent() var head = init_comprehension(comp, scopes) From 91adf780b3243a88df9b5752ffd10c317567d2c0 Mon Sep 17 00:00:00 2001 From: Johnathon Selstad Date: Wed, 12 Aug 2026 22:39:53 -0700 Subject: [PATCH 04/12] Fix iteration protocol: tp_iter inheritance and sequence-protocol fallback 1. make_iter followed tp_base only, so a dict subclass whose first base is a plain class (class PolyElement(DomainElement, ..., dict)) lost dict's __iter__ and iter() failed. Resolve tp_iter with search_slot (full MRO). 2. The __getitem__ fallback iterator required __len__ and crashed with a raw JS error when it was missing. CPython semantics: only __getitem__ is required, and IndexError ends the iteration. Co-Authored-By: Claude Fable 5 --- www/src/py_builtin_functions.js | 36 ++++++++++++++++++++++++--------- www/src/py_type.js | 23 +++++++++++++++------ 2 files changed, 44 insertions(+), 15 deletions(-) diff --git a/www/src/py_builtin_functions.js b/www/src/py_builtin_functions.js index 29ac7e3e5..a84cf1e6f 100644 --- a/www/src/py_builtin_functions.js +++ b/www/src/py_builtin_functions.js @@ -973,6 +973,10 @@ $B.$hash = function(obj) { if (! $B.is_int(res)) { $B.RAISE(_b_.TypeError, '__hash__ method should return an integer') } + if (typeof res == 'object') { + // int subclass: hash of its integer value + res = _b_.int.tp_hash(res) + } } else { $B.RAISE(_b_.TypeError, "unhashable type: '" + _b_.str.$factory($B.jsobj2pyobj(obj)) + "'" @@ -1215,18 +1219,31 @@ var issubclass = _b_.issubclass = function(cls, class_or_tuple) { /* iterator start */ $B.iterator.tp_iter = function(self) { var ob_type = $B.get_class(self.it_seq) - self.len = $B.search_in_mro(ob_type, '__len__')(self.it_seq) - self.getitem = $B.search_in_mro(ob_type, '__getitem__') + var getitem = $B.search_in_mro(ob_type, '__getitem__', $B.NULL) + if (getitem === $B.NULL) { + $B.RAISE(_b_.TypeError, + `'${$B.class_name(self.it_seq)}' object is not iterable`) + } + self.getitem = getitem self.it_index = 0 return self } $B.iterator.tp_iternext = function*(self){ - if (self.it_index < self.len) { - var res = self.getitem(self.it_seq, self.it_index) - self.it_index++ - yield res + // "sequence protocol" iteration: call __getitem__ with increasing + // indices; IndexError ends the iteration (__len__ is not used, same + // as CPython) + var res + try { + res = $B.$call(self.getitem, self.it_seq, self.it_index) + } catch (err) { + if ($B.is_exc(err, [_b_.IndexError, _b_.StopIteration])) { + return + } + throw err } + self.it_index++ + yield res } var iterator_funcs = $B.iterator.tp_funcs = {} @@ -1307,13 +1324,14 @@ $B.$iter = function(obj, sentinel) { } return res } + // fallback for the "sequence protocol": objects with __getitem__ + // are iterated with increasing indices until IndexError; __len__ is + // not required (same as CPython) var getitem_func = $B.search_in_mro(klass, '__getitem__', $B.NULL) - var len_func = $B.search_in_mro(klass, '__len__', $B.NULL) if (test) { console.log('getitem_func', getitem_func) - console.log('len_func', len_func) } - if (getitem_func !== $B.NULL && len_func !== $B.NULL) { + if (getitem_func !== $B.NULL) { var it = { ob_type: $B.iterator, it_seq: obj diff --git a/www/src/py_type.js b/www/src/py_type.js index 0ddec9bb1..fe15e98d9 100644 --- a/www/src/py_type.js +++ b/www/src/py_type.js @@ -956,13 +956,24 @@ function reset_factory(cls) { } $B.make_iter = function(cls) { + // resolve the tp_iter slot by walking the full MRO, not only tp_base: + // __iter__ can be inherited from any ancestor, eg a dict subclass whose + // first base is a plain class. Only raw class attributes are used: a + // descriptor must not have its __get__ invoked at slot-resolution time + // (it would have side effects, cf unittest.mock.MagicProxy); descriptors + // are handled at call time by $B.$iter cls.tp_iter = $B.NULL - var iter = $B.get_from_dict(cls, '__iter__', $B.NULL) - if (iter !== $B.NULL) { - cls.tp_iter = iter - } else if (cls.tp_base) { - cls.tp_iter = cls.tp_base.tp_iter ?? - (cls.tp_base.tp_iter = $B.make_iter(cls.tp_base)) + for (var klass of $B.get_mro(cls)) { + var iter = $B.get_from_dict(klass, '__iter__', $B.NULL) + if (iter !== $B.NULL) { + cls.tp_iter = iter + break + } + if (klass !== cls && Object.hasOwn(klass, 'tp_iter') && + klass.tp_iter !== $B.NULL && klass.tp_iter != null) { + cls.tp_iter = klass.tp_iter + break + } } return cls.tp_iter } From 445334a5ad33df16aadeac48fcd3c9219e64bf0e Mon Sep 17 00:00:00 2001 From: Johnathon Selstad Date: Wed, 12 Aug 2026 22:39:53 -0700 Subject: [PATCH 05/12] dict() from a sequence: use the iteration protocol on the pairs init_from_list read item.length and item[0]/item[1] as raw JS properties, so dict() over a sequence of Python sequence objects (e.g. instances with __len__/__getitem__) failed with 'has length undefined; 2 is required'. Co-Authored-By: Claude Fable 5 --- www/src/py_dict.js | 10 +++++++--- 1 file changed, 7 insertions(+), 3 deletions(-) diff --git a/www/src/py_dict.js b/www/src/py_dict.js index 11cde502a..ca81d1f17 100644 --- a/www/src/py_dict.js +++ b/www/src/py_dict.js @@ -712,11 +712,15 @@ dict.tp_hash = _b_.None function init_from_list(self, args) { var i = 0 for (var item of args) { - if (item.length != 2) { + // item may be any Python sequence (eg an instance of a class with + // __iter__), not only a JS array: use the iteration protocol + var pair = Array.isArray(item) ? item : + Array.from($B.make_js_iterator_no_trace(item)) + if (pair.length != 2) { $B.RAISE(_b_.ValueError, "dictionary " + - `update sequence element #${i} has length ${item.length}; 2 is required`) + `update sequence element #${i} has length ${pair.length}; 2 is required`) } - dict.$setitem(self, item[0], item[1]) + dict.$setitem(self, pair[0], pair[1]) i++ } } From e10b562fd52c8770961d9109cf502ec692a1f37c Mon Sep 17 00:00:00 2001 From: Johnathon Selstad Date: Wed, 12 Aug 2026 22:39:53 -0700 Subject: [PATCH 06/12] Fix TypeError when hashing tuples/frozensets containing large ints hash(n) for 2**53 < n < 2**61 is a JS BigInt (the exact value, too large for Number). tuple hash then evaluated 'y & 0xFFFFFFFF' and frozenset hash '_h << 16', raising 'Cannot mix BigInt and other types' (breaks functools.lru_cache keys containing big ints). Reduce bigint element hashes with BigInt.asIntN(32, ...) before Number mixing. Co-Authored-By: Claude Fable 5 --- www/src/py_list.js | 6 ++++++ www/src/py_set.js | 6 ++++++ 2 files changed, 12 insertions(+) diff --git a/www/src/py_list.js b/www/src/py_list.js index cd04d9c77..be80f9f71 100644 --- a/www/src/py_list.js +++ b/www/src/py_list.js @@ -1066,6 +1066,12 @@ _b_.tuple.tp_hash = function(self) { var x = 0x3456789 for (var i = 0, len = self.length; i < len; i++) { var y = _b_.hash(self[i]) + if (typeof y == 'bigint') { + // hash values above Number.MAX_SAFE_INTEGER are bigints (eg + // hash(2 ** 60)); reduce to 32 bits before mixing with Number + // arithmetic + y = Number(BigInt.asIntN(32, y)) + } x = c_mul(1000003, x) ^ y & 0xFFFFFFFF } return x diff --git a/www/src/py_set.js b/www/src/py_set.js index ee1afb5d4..6cf0cf186 100644 --- a/www/src/py_set.js +++ b/www/src/py_set.js @@ -936,6 +936,12 @@ frozenset.tp_hash = function(self) { for (var entry of set_iter_with_hash(self)) { var _h = entry.hash + if (typeof _h == 'bigint') { + // hash values above Number.MAX_SAFE_INTEGER are bigints (eg + // hash(2 ** 60)); reduce to 32 bits before mixing with Number + // arithmetic + _h = Number(BigInt.asIntN(32, _h)) + } _hash ^= ((_h ^ 89869747) ^ (_h << 16)) * 3644798167 } From 7ccbaa7e87272ce0372f8d22f30e688e6dfd98e4 Mon Sep 17 00:00:00 2001 From: Johnathon Selstad Date: Wed, 12 Aug 2026 22:39:53 -0700 Subject: [PATCH 07/12] Fix math.lcm, broken for every input $B.$getattr(product, '__floordiv__') on a JS number is not callable; use $B.rich_op which handles both small ints and long ints. Co-Authored-By: Claude Fable 5 --- www/src/libs/math.js | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/www/src/libs/math.js b/www/src/libs/math.js index 375e920d0..010e3ebcc 100644 --- a/www/src/libs/math.js +++ b/www/src/libs/math.js @@ -1843,7 +1843,9 @@ function lcm() { } gcd = gcd2(a, b) product = $B.rich_op('__mul__', a, b) - a = $B.$getattr(product, "__floordiv__")(gcd) + // product may be a JS number (Brython small int) or a long_int: + // use rich_op, which handles both, instead of getattr on the value + a = $B.rich_op('__floordiv__', product, gcd) } return a } From 63596f41a594436076217705c425e6b7d9de30a5 Mon Sep 17 00:00:00 2001 From: Johnathon Selstad Date: Wed, 12 Aug 2026 22:39:53 -0700 Subject: [PATCH 08/12] array.array: support negative indices in getitem/setitem a[-1] and a[-1] = v raised IndexError because the index was used directly as a JS array subscript. Co-Authored-By: Claude Fable 5 --- www/src/libs/array.js | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/www/src/libs/array.js b/www/src/libs/array.js index 5bc8e30b4..fdb0f5ca9 100644 --- a/www/src/libs/array.js +++ b/www/src/libs/array.js @@ -70,6 +70,10 @@ array.bf_getbuffer = function(_self, flag) { array.mp_subscript = function(_self, key) { if (_self.obj) { + if ($B.is_int(key) && key < 0) { + // Python semantics: negative indices count from the end + key = _self.obj.length + Number(key) + } if (_self.obj[key] !== undefined) { return _self.obj[key] } else if ($B.$isinstance(key, _b_.slice)) { @@ -120,6 +124,10 @@ array.bf_release_buffer = function(_self, buffer) { array.mp_ass_subscript = function(_self, index, value) { if ($B.is_int(index)) { + if (index < 0) { + // Python semantics: negative indices count from the end + index = _self.obj.length + Number(index) + } if (_self.obj[index] === undefined) { $B.RAISE(_b_.IndexError, "array index out of range") } From 69655ac1def276a9be6ed4e17f57a083792c7e09 Mon Sep 17 00:00:00 2001 From: Johnathon Selstad Date: Wed, 12 Aug 2026 22:39:53 -0700 Subject: [PATCH 09/12] Fix cmath, unimportable under Brython itself The 'set all functions as built-in' compliance loop calls type(abs)(func), which raises TypeError in Brython, so 'import cmath' always failed (and mpmath/sympy with it). Skip the cosmetic conversion if the implementation does not support it. Co-Authored-By: Claude Fable 5 --- www/src/Lib/cmath.py | 11 ++++++++--- 1 file changed, 8 insertions(+), 3 deletions(-) diff --git a/www/src/Lib/cmath.py b/www/src/Lib/cmath.py index 90be70041..1e839e5f9 100644 --- a/www/src/Lib/cmath.py +++ b/www/src/Lib/cmath.py @@ -680,12 +680,17 @@ def tanh(x): return complex(_real, _imag) # For compliance with CPython, set all functions as built-in +# (cosmetic: makes type(cmath.sin) look like a builtin function; skip it +# if the implementation cannot construct builtin_function_or_method) FunctionType = type(_takes_complex) locs = locals() keys = list(locs.keys()) -for f in keys: - if type(locs[f]) is FunctionType and not f.startswith("_"): - locals()[f] = type(abs)(locals()[f]) +try: + for f in keys: + if type(locs[f]) is FunctionType and not f.startswith("_"): + locals()[f] = type(abs)(locals()[f]) +except TypeError: + pass pi = math.pi e = math.e From 2970b77d7fe846eee66549d7d09e22358fc92b8d Mon Sep 17 00:00:00 2001 From: Johnathon Selstad Date: Wed, 12 Aug 2026 22:39:53 -0700 Subject: [PATCH 10/12] Add a minimal pure-Python ctypes subset Fundamental c_* types with sizeof()/alignment() (wasm32-like sizes), CDLL raising OSError. Enough for pure-Python libraries that only probe the platform word size (e.g. sympy.external needs sizeof(c_long)); loading native libraries stays an explicit error. Co-Authored-By: Claude Fable 5 --- www/src/Lib/ctypes/__init__.py | 162 +++++++++++++++++++++++++++++++++ 1 file changed, 162 insertions(+) create mode 100644 www/src/Lib/ctypes/__init__.py diff --git a/www/src/Lib/ctypes/__init__.py b/www/src/Lib/ctypes/__init__.py new file mode 100644 index 000000000..79c6e5c9d --- /dev/null +++ b/www/src/Lib/ctypes/__init__.py @@ -0,0 +1,162 @@ +"""Minimal pure-Python subset of ctypes for Brython. + +Brython runs in a JavaScript engine and cannot load native libraries, so +this module only provides what pure-Python packages commonly use to probe +the platform: the fundamental C type classes, sizeof()/alignment(), and +byref/pointer stubs. Loading shared libraries raises OSError. + +Sizes follow a 32-bit (wasm32-like) data model, matching what CPython +reports on WebAssembly platforms. +""" + +class _SimpleCData: + _size_ = 4 + _align_ = 4 + + def __init__(self, value=None): + self.value = value + + def __repr__(self): + return f"{type(self).__name__}({self.value!r})" + + +class c_bool(_SimpleCData): + _type_ = "?" + _size_ = 1 + _align_ = 1 + +class c_char(_SimpleCData): + _type_ = "c" + _size_ = 1 + _align_ = 1 + +class c_byte(_SimpleCData): + _type_ = "b" + _size_ = 1 + _align_ = 1 + +class c_ubyte(_SimpleCData): + _type_ = "B" + _size_ = 1 + _align_ = 1 + +class c_short(_SimpleCData): + _type_ = "h" + _size_ = 2 + _align_ = 2 + +class c_ushort(_SimpleCData): + _type_ = "H" + _size_ = 2 + _align_ = 2 + +class c_int(_SimpleCData): + _type_ = "i" + +class c_uint(_SimpleCData): + _type_ = "I" + +class c_long(_SimpleCData): + _type_ = "l" + +class c_ulong(_SimpleCData): + _type_ = "L" + +class c_longlong(_SimpleCData): + _type_ = "q" + _size_ = 8 + _align_ = 8 + +class c_ulonglong(_SimpleCData): + _type_ = "Q" + _size_ = 8 + _align_ = 8 + +class c_size_t(_SimpleCData): + _type_ = "N" + +class c_ssize_t(_SimpleCData): + _type_ = "n" + +class c_float(_SimpleCData): + _type_ = "f" + +class c_double(_SimpleCData): + _type_ = "d" + _size_ = 8 + _align_ = 8 + +class c_char_p(_SimpleCData): + _type_ = "z" + +class c_wchar_p(_SimpleCData): + _type_ = "Z" + +class c_wchar(_SimpleCData): + _type_ = "u" + +class c_void_p(_SimpleCData): + _type_ = "P" + +c_int8 = c_byte +c_uint8 = c_ubyte +c_int16 = c_short +c_uint16 = c_ushort +c_int32 = c_int +c_uint32 = c_uint +c_int64 = c_longlong +c_uint64 = c_ulonglong + + +def sizeof(obj_or_type): + if isinstance(obj_or_type, type): + return getattr(obj_or_type, "_size_", 4) + return getattr(type(obj_or_type), "_size_", 4) + +def alignment(obj_or_type): + if isinstance(obj_or_type, type): + return getattr(obj_or_type, "_align_", 4) + return getattr(type(obj_or_type), "_align_", 4) + +def byref(obj, offset=0): + raise NotImplementedError("ctypes.byref is not supported in Brython") + +def pointer(obj): + raise NotImplementedError("ctypes.pointer is not supported in Brython") + +def POINTER(cls): + raise NotImplementedError("ctypes.POINTER is not supported in Brython") + +def cast(obj, typ): + raise NotImplementedError("ctypes.cast is not supported in Brython") + +def create_string_buffer(init, size=None): + raise NotImplementedError( + "ctypes.create_string_buffer is not supported in Brython") + + +class ArgumentError(Exception): + pass + + +class CDLL: + def __init__(self, name, *args, **kw): + raise OSError( + "ctypes cannot load shared libraries in Brython: %r" % (name,)) + +PyDLL = CDLL +OleDLL = CDLL +WinDLL = CDLL + + +class LibraryLoader: + def __init__(self, dlltype): + self._dlltype = dlltype + + def LoadLibrary(self, name): + return self._dlltype(name) + + __getattr__ = LoadLibrary + +cdll = LibraryLoader(CDLL) +pydll = LibraryLoader(PyDLL) From dce79c627010cf954e60109ff6966f6d5647e098 Mon Sep 17 00:00:00 2001 From: Johnathon Selstad Date: Wed, 12 Aug 2026 23:17:41 -0700 Subject: [PATCH 11/12] Add tests for PR #2912 to issues.py Covers: issubclass/super() with custom metaclasses across multiple inheritance levels, unary dunders as zero-argument staticmethods, exec() with distinct globals and locals, iteration of dict subclasses and sequence-protocol objects, dict() from Python pair objects, hashing tuples/frozensets containing large ints, math.lcm, array negative indices, cmath and ctypes imports. Co-Authored-By: Claude Fable 5 --- www/tests/issues.py | 124 ++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 124 insertions(+) diff --git a/www/tests/issues.py b/www/tests/issues.py index f6fd9b518..cafd5b0e9 100644 --- a/www/tests/issues.py +++ b/www/tests/issues.py @@ -3345,6 +3345,130 @@ def f2735(x): f2735(0) +# PR 2912 : issubclass / super() with a custom metaclass and indirect subclass +class Meta2912(type): + pass + +class A2912(metaclass=Meta2912): + pass + +class B2912(A2912): + pass + +class C2912(B2912): + pass + +assert issubclass(C2912, A2912) +assert issubclass(C2912, B2912) + +class D2912(A2912): + def __new__(cls, *args): + obj = super().__new__(cls) + obj.tag = "ok" + return obj + +class E2912(D2912): + pass + +assert E2912().tag == "ok" + +# PR 2912 : unary dunders defined as zero-argument staticmethods +class Unary2912: + @staticmethod + def __neg__(): + return "neg" + + @staticmethod + def __pos__(): + return "pos" + + @staticmethod + def __invert__(): + return "invert" + + @staticmethod + def __abs__(): + return "abs" + +u2912 = Unary2912() +assert -u2912 == "neg" +assert +u2912 == "pos" +assert ~u2912 == "invert" +assert abs(u2912) == "abs" +assert_raises(TypeError, lambda: -object()) +assert_raises(TypeError, abs, object()) + +# PR 2912 : functions defined by exec() with distinct globals and locals +# see the globals dict +g2912 = {"VALUE": 42, "__name__": "mod2912"} +l2912 = {} +exec("def f2912():\n return VALUE", g2912, l2912) +assert "f2912" in l2912 +assert l2912["f2912"]() == 42 + +# PR 2912 : iteration of a dict subclass whose first base is a plain class +class PlainBase2912: + pass + +class DictSub2912(PlainBase2912, dict): + pass + +d2912 = DictSub2912(a=1, b=2) +assert sorted(iter(d2912)) == ["a", "b"] +assert sorted(list(d2912)) == ["a", "b"] +assert max(d2912) == "b" + +# PR 2912 : sequence-protocol iteration only needs __getitem__ + IndexError +class Seq2912: + def __getitem__(self, i): + if i > 2: + raise IndexError(i) + return i * 10 + +assert list(Seq2912()) == [0, 10, 20] + +# PR 2912 : dict() from a sequence of Python pair objects +class Pair2912: + def __init__(self, a, b): + self.pair = (a, b) + + def __len__(self): + return 2 + + def __getitem__(self, i): + return self.pair[i] + +assert dict([Pair2912("x", 1), Pair2912("y", 2)]) == {"x": 1, "y": 2} + +# PR 2912 : hash of tuples / frozensets containing large ints +# (hash(2 ** 60) is above Number.MAX_SAFE_INTEGER) +assert isinstance(hash((2 ** 60, "x")), int) +assert isinstance(hash(frozenset([2 ** 60, "x"])), int) +assert hash((2 ** 60,)) == hash((2 ** 60,)) +dbig2912 = {(2 ** 60, "x"): 1} +assert dbig2912[(2 ** 60, "x")] == 1 + +# PR 2912 : math.lcm +import math +assert math.lcm(6, 4) == 12 +assert math.lcm() == 1 +assert math.lcm(5) == 5 +assert math.lcm(0, 3) == 0 + +# PR 2912 : array.array negative indices +from array import array +arr2912 = array("l", [1, 2, 3]) +assert arr2912[-1] == 3 +arr2912[-1] = 5 +assert arr2912[-1] == 5 +assert_raises(IndexError, lambda: arr2912[-4]) + +# PR 2912 : cmath and ctypes are importable +import cmath +assert cmath.sqrt(-1) == 1j +import ctypes +assert ctypes.sizeof(ctypes.c_long) in (4, 8) + # ========================================== # Finally, report that all tests have passed # ========================================== From bedafa5aa3335ec2f8835d0e647967e50881bded Mon Sep 17 00:00:00 2001 From: Johnathon Selstad Date: Thu, 13 Aug 2026 00:09:27 -0700 Subject: [PATCH 12/12] Fix property() called with only keyword arguments property.$factory inserted positional defaults before forwarding to tp_init, which shifted a keyword-arguments marker into the fget slot: property(fset=f) raised "__init__() got multiple values for argument 'fset'" (breaks mpmath 1.4). Forward the arguments unchanged and let tp_init's argument parser apply the defaults. Co-Authored-By: Claude Fable 5 --- www/src/py_type.js | 8 +++++--- www/tests/issues.py | 19 +++++++++++++++++++ 2 files changed, 24 insertions(+), 3 deletions(-) diff --git a/www/src/py_type.js b/www/src/py_type.js index fe15e98d9..dd4d89564 100644 --- a/www/src/py_type.js +++ b/www/src/py_type.js @@ -1859,12 +1859,14 @@ $B.internal_property = function(module, fget, fset) { } } -property.$factory = function(fget, fset, fdel, doc) { +property.$factory = function() { var res = { ob_type: property } - property.tp_init(res, fget, fset ?? _b_.None, fdel ?? _b_.None, - doc ?? _b_.None) + // forward the arguments unchanged: they may end with a keyword-arguments + // marker (eg property(fset=...)), which tp_init's argument parser + // handles; inserting positional defaults here would shift it into fget + property.tp_init(res, ...arguments) return res } diff --git a/www/tests/issues.py b/www/tests/issues.py index cafd5b0e9..f680b64b6 100644 --- a/www/tests/issues.py +++ b/www/tests/issues.py @@ -3469,6 +3469,25 @@ def __getitem__(self, i): import ctypes assert ctypes.sizeof(ctypes.c_long) in (4, 8) +# PR 2912 : property() with only keyword arguments +prop2912 = property(fset=lambda self, value: None) +assert prop2912.fget is None +assert prop2912.fset is not None + +class WithProp2912: + def __init__(self): + self._x = 0 + + def _set_x(self, value): + self._x = value + + x = property(fset=_set_x) + +wp2912 = WithProp2912() +wp2912.x = 5 +assert wp2912._x == 5 +assert_raises(AttributeError, lambda: wp2912.x) + # ========================================== # Finally, report that all tests have passed # ==========================================