Commits

masklinn committed 1852db4

Massive change: py.js types aren't JS constructors anymore

The dichotomy was bothersome (although the rewards are nowhere near as
great as I'd originally believed).

* Started adding better documentation
* Added a PY_call utility method (to be documented) to handle the
weird parts of calling a type (which is a big reason why the payout
of constructor-less py.js types is not great)
* Added a fromJSON method (other side of toJSON)
* Added support for __new__ and __init__
* Added some class attributes
* Added python-level isinstance

  • Participants
  • Parent commits 47fed85

Comments (0)

Files changed (7)

 # The reST default role (used for this markup: `text`) to use for all documents.
 #default_role = None
 
+# Default sphinx domain
+default_domain = 'js'
+
 # If true, '()' will be appended to :func: etc. cross-reference text.
 #add_function_parentheses = True
 
 
 # The name of the Pygments (syntax highlighting) style to use.
 pygments_style = 'sphinx'
+# default code-block highlighting
+highlight_language = 'javascript'
 
 # A list of ignored prefixes for module index sorting.
 #modindex_common_prefix = []

File doc/differences.rst

+Differences with Python
+=======================
+
+* ``py.js`` completely ignores old-style classes as well as their
+  lookup details. All ``py.js`` types should be considered matching
+  the behavior of new-style classes
+
+* New types can only have a single base. This is due to ``py.js``
+  implementing its types on top of Javascript's, and javascript being
+  a single-inheritance language.
+
+  This may change if ``py.js`` ever reimplements its object model from
+  scratch.
+
+* Piggybacking on javascript's object model also means metaclasses are
+  not available (:js:func:`py.type` is a function)
+
+* A python-level function (created through :js:class:`py.PY_def`) set
+  on a new type will not become a method, it'll remain a function.
+
+* :js:func:`py.PY_parseArgs` supports keyword-only arguments (though
+  it's a Python 3 feature)
+
+* Because the underlying type is a javascript ``String``, there
+  currently is no difference between :js:class:`py.str` and
+  :js:class:`py.unicode`. As a result, there also is no difference
+  between :js:func:`__str__` and :js:func:`__unicode__`.
+
+Unsupported features
+--------------------
+
+These are Python features which are not supported at all in ``py.js``,
+usually because they don't make sense or there is no way to support them
+
+* The ``__delattr__``, ``__delete__`` and ``__delitem__``: as
+  ``py.js`` only handles expressions and these are accessed via the
+  ``del`` statement, there would be no way to call them.
+
+* ``__del__`` the lack of cross-platform GC hook means there is no way
+  to know when an object is deallocated.
+
+* ``__slots__`` are not handled
+
+* Dedicated (and deprecated) slicing special methods are unsupported
+
+Missing features
+----------------
+
+These are Python features which are missing because they haven't been
+implemented yet:
+
+* Class-binding of descriptors doesn't currently work.
+
+* Instance and subclass checks can't be customized
+
+* "poor" comparison methods (``__cmp__`` and ``__rcmp__``) are not
+  supported and won't be falled-back to.
+
+* ``__coerce__`` is currently supported
+
+* Context managers are not currently supported
+
+* Unbound methods are not supported, instance methods can only be
+  accessed from instances.

File doc/index.rst

    You can adapt this file completely to your liking, but it should at least
    contain the root `toctree` directive.
 
-.. default-domain:: js
-
-.. highlight:: javascript
-
 py.js, a Python expressions parser and evaluator
 ================================================
 
 <http://docs.python.org/reference/expressions.html>`_ (along with the
 lexical analysis part) as well as the Python builtins.
 
+
+.. toctree::
+    :maxdepth: 2
+
+    types
+    differences
+
 Usage
 -----
 
 .. function:: py.PY_parseArgs(arguments, format)
 
     Arguments parser converting from the :ref:`user-defined calling
-    conventions <calling-conventions-python>` to a JS object mapping
+    conventions <types-methods-python-call>` to a JS object mapping
     argument names to values. It serves the same role as
     `PyArg_ParseTupleAndKeywords`_.
 
 
     Type wrapping javascript functions into py.js callables. The
     wrapped function follows :ref:`the py.js calling conventions
-    <calling-conventions-python>`
+    <types-methods-python-call>`
 
     :param Function fn: the javascript function to wrap
     :returns: a callable py.js object
 Most built-in objects provide a :js:func:`py.object.toJSON`
 implementation out of the box.
 
-Calling convention
-++++++++++++++++++
-
-Because Python supports keyword arguments and javascript does not,
-moving arguments from the python domain to the javascript domain is
-not completely straightforward.
-
-``py.js`` implements two different conventions for that case (…)
-
-* Dunder methods (pre- and post-fixed with ``__``) of the Python Data
-  Model — fully and knowingly called in javascript — receive their
-  arguments unwrapped and positionally, as normal arguments to a
-  javascript functions. These arguments will still generally be
-  :class:`py.object`.
-
-.. _calling-conventions-python:
-
-* Arbitrary user-defined callables receive two parameters ``args`` and
-  ``kwargs``, holding respectively the positional and keyword
-  arguments passed to the callable from the expression.
-
-  These can be parsed into a JS object via :func:`py.PY_parseArgs`.
-
 Javascript-level exceptions
 +++++++++++++++++++++++++++
 

File doc/types.rst

+Implementing a custom type
+==========================
+
+To implement a custom python-level type, one can use the
+:func:`py.type` builtin. At the JS-level, it is a function with the
+same signature as the :py:class:`type` builtin [#bases]_. It returns a
+child type of its one base (or :class:`py.object` if no base is
+provided).
+
+The ``dict`` parameter to :func:`py.type` can contain any
+attribute, javascript-level or python-level: the default
+``__getattribute__`` implementation will ensure they are converted to
+Python-level attributes if needed. Most methods are also wrapped and
+converted to :ref:`types-methods-python`, although there are a number
+of special cases:
+
+* Most "magic methods" of the data model ("dunder" methods) remain
+  javascript-level. See :ref:`the listing of magic methods and their
+  signatures <types-methods-dunder>`. As a result, they do not respect
+  the :ref:`types-methods-python-call`
+
+* The ``toJSON`` and ``fromJSON`` methods are special-cased to remain
+  javascript-level and don't follow the
+  :ref:`types-methods-python-call`
+
+* Functions which have been wrapped explicitly (via
+  :class:`py.PY_def`, :class:`py.classmethod` or
+  :class:`py.staticmethod`) are associated to the class
+  untouched. But due to their wrapper, they will use the
+  :ref:`types-methods-python-call` anyway
+
+.. _types-methods-python:
+
+Python-level callable
+---------------------
+
+Wrapped javascript function *or* the :js:func:`__call__` method itself
+follow the :ref:`types-methods-python-call`. As a result, they can't
+(easily) be called directly from javascript code. Because
+:js:func:`__new__` and :js:func:`__init__` follow from
+:js:func:`__call__`, they also follow the
+:ref:`types-methods-python-call`.
+
+:func:`py.PY_call` should be used when interacting with them from
+javascript is necessary.
+
+Because ``__call__`` follows the :ref:`types-methods-python-call`,
+instantiating a ``py.js`` type from javascript requires using
+:func:`py.PY_call`.
+
+.. _types-methods-python-call:
+
+Python calling conventions
+++++++++++++++++++++++++++
+
+The python-level arguments should be considered completely opaque,
+they should be interacted with through :func:`py.PY_parseArgs` (to
+extract python-level arguments to javascript implementation code) and
+:func:`py.PY_call` (to call :ref:`types-methods-python` from
+javascript code).
+
+A callable following the :ref:`types-methods-python-call` *must*
+return a ``py.js`` object, an error will be generated when failing to
+do so.
+
+.. todo:: arguments forwarding when e.g. overriding methods?
+
+.. _types-methods-dunder:
+
+Magic methods
+-------------
+
+``py.js`` doesn't support calling magic ("dunder") methods of the
+datamodel from Python code, and these methods remain javascript-level
+(they don't follow the :ref:`types-methods-python-call`).
+
+Here is a list of the understood datamodel methods, refer to `the
+relevant Python documentation
+<http://docs.python.org/reference/datamodel.html?highlight=data%20model#special-method-names>`_
+for their roles.
+
+Basic customization
++++++++++++++++++++
+
+.. function:: __hash__()
+
+    :returns: String
+
+.. function:: __eq__(other)
+
+    The default implementation tests for identity
+
+    :param other: :class:`py.object` to compare this object with
+    :returns: :class:`py.bool`
+
+.. function:: __ne__(other)
+
+    The default implementation calls :func:`__eq__` and reverses
+    its result.
+
+    :param other: :class:`py.object` to compare this object with
+    :returns: :class:`py.bool`
+
+.. function:: __lt__(other)
+
+    The default implementation simply returns
+    :data:`py.NotImplemented`.
+
+    :param other: :class:`py.object` to compare this object with
+    :returns: :class:`py.bool`
+
+
+.. function:: __le__(other)
+
+    The default implementation simply returns
+    :data:`py.NotImplemented`.
+
+    :param other: :class:`py.object` to compare this object with
+    :returns: :class:`py.bool`
+
+
+.. function:: __ge__(other)
+
+    The default implementation simply returns
+    :data:`py.NotImplemented`.
+
+    :param other: :class:`py.object` to compare this object with
+    :returns: :class:`py.bool`
+
+
+.. function:: __gt__(other)
+
+    The default implementation simply returns
+    :data:`py.NotImplemented`.
+
+    :param other: :class:`py.object` to compare this object with
+    :returns: :class:`py.bool`
+
+.. function:: __str__()
+
+    Simply calls :func:`__unicode__`. This method should not be
+    overridden, :func:`__unicode__` should be overridden instead.
+
+    :returns: :class:`py.str`
+
+.. function:: __unicode__()
+
+    :returns: :class:`py.unicode`
+
+.. function:: __nonzero__()
+
+    The default implementation always returns :data:`py.True`
+
+    :returns: :class:`py.bool`
+
+Customizing attribute access
+++++++++++++++++++++++++++++
+
+.. function:: __getattribute__(name)
+
+    :param String name: name of the attribute, as a javascript string
+    :returns: :class:`py.object`
+
+.. function:: __getattr__(name)
+
+    :param String name: name of the attribute, as a javascript string
+    :returns: :class:`py.object`
+
+.. function:: __setattr__(name, value)
+
+    :param String name: name of the attribute, as a javascript string
+    :param value: :class:`py.object`
+
+Implementing descriptors
+++++++++++++++++++++++++
+
+.. function:: __get__(instance)
+
+    .. note:: readable descriptors don't currently handle "owner
+              classes"
+
+    :param instance: :class:`py.object`
+    :returns: :class:`py.object`
+
+.. function:: __set__(instance, value)
+
+    :param instance: :class:`py.object`
+    :param value: :class:`py.object`
+
+Emulating Numeric Types
++++++++++++++++++++++++
+
+* Non-in-place binary numeric methods (e.g. ``__add__``, ``__mul__``,
+  ...) should all be supported including reversed calls (in case the
+  primary call is not available or returns
+  :js:data:`py.NotImplemented`). They take a single :class:`py.object`
+  parameter and return a single :class:`py.object` parameter.
+
+* Unary operator numeric methods are all supported:
+
+  .. function:: __pos__()
+
+      :returns: :class:`py.object`
+
+  .. function:: __neg__()
+
+      :returns: :class:`py.object`
+
+  .. function:: __invert__()
+
+      :returns: :class:`py.object`
+
+* For non-operator numeric methods, support is contingent on the
+  corresponding :ref:`builtin` being implemented
+
+Emulating container types
++++++++++++++++++++++++++
+
+.. function:: __len__()
+
+    :returns: :class:`py.int`
+
+.. function:: __getitem__(name)
+
+    :param name: :class:`py.object`
+    :returns: :class:`py.object`
+
+.. function:: __setitem__(name, value)
+
+    :param name: :class:`py.object`
+    :param value: :class:`py.object`
+
+.. function:: __iter__()
+
+    :returns: :class:`py.object`
+
+.. function:: __reversed__()
+
+    :returns: :class:`py.object`
+
+.. function:: __contains__(other)
+
+    :param other: :class:`py.object`
+    :returns: :class:`py.bool`
+
+.. [#bases] with the limitation that, because :ref:`py.js builds its
+            object model on top of javascript's
+            <details-object-model>`, only one base is allowed.
             return py.False;
         }
 
-        if (val instanceof py.object
-            || val === py.object
-            || py.issubclass.__call__([val, py.object]) === py.True) {
+        var fn = function () {}
+        fn.prototype = py.object;
+        if (py.PY_call(py.isinstance, [val, py.object]) === py.True
+            || py.PY_call(py.issubclass, [val, py.object]) === py.True) {
             return val;
         }
 
         switch (typeof val) {
         case 'number':
-            return new py.float(val);
+            return py.float.fromJSON(val);
         case 'string':
-            return new py.str(val);
+            return py.str.fromJSON(val);
         case 'function':
-            return new py.PY_def(val);
+            return py.PY_def.fromJSON(val);
         }
 
         switch(val.constructor) {
         case Object:
             // TODO: why py.object instead of py.dict?
-            var o = new py.object();
+            var o = py.PY_call(py.object);
             for (var prop in val) {
                 if (val.hasOwnProperty(prop)) {
                     o[prop] = val[prop];
             }
             return o;
         case Array:
-            var a = new py.list();
+            var a = py.PY_call(py.list);
             a.values = val;
             return a;
         }
     };
 
     // Builtins
-    py.type = function type(constructor, base, dict) {
+    py.PY_call = function (callable, args, kwargs) {
+        if (!args) {
+            args = []; kwargs = {};
+        } else if (typeof args === 'object' && !(args instanceof Array)) {
+            kwargs = args;
+            args = [];
+        } else if (!kwargs) {
+            kwargs = {};
+        }
+        if (callable.__is_type) {
+            // class hack
+            var instance = callable.__new__.call(callable, args, kwargs);
+            var typ = function () {}
+            typ.prototype = callable;
+            if (instance instanceof typ) {
+                instance.__init__.call(instance, args, kwargs);
+            }
+            return instance
+        }
+        return callable.__call__(args, kwargs);
+    };
+    py.type = function type(name, bases, dict) {
         var proto;
-        if (!base) {
-            base = py.object;
+        if (typeof name !== 'string') {
+            throw new Error("ValueError: a class name should be a string");
         }
-        proto = constructor.prototype = create(base.prototype);
-        proto.constructor = constructor;
+        if (!bases || bases.length === 0) {
+            bases = [py.object];
+        } else if (bases.length > 1) {
+            throw new Error("ValueError: can't provide multiple bases for a "
+                          + "new type");
+        }
+        var base = bases[0];
+        var ClassObj = create(base);
         if (dict) {
-            for(var k in dict) {
+            for (var k in dict) {
                 if (!dict.hasOwnProperty(k)) { continue; }
-                proto[k] = dict[k];
+                ClassObj[k] = dict[k];
             }
         }
-        constructor.__call__ = function () {
-            // create equivalent type with same prototype
-            var instance = create(proto);
-            // call actual constructor
-            var res = constructor.apply(instance, arguments);
-            // return result of constructor if any, otherwise instance
-            return res || instance;
-        };
-        return constructor;
+        ClassObj.__class__ = ClassObj;
+        ClassObj.__name__ = name;
+        ClassObj.__bases__ = bases;
+        ClassObj.__is_type = true;
+
+        return ClassObj;
+    };
+    py.type.__call__ = function () {
+        var args = py.PY_parseArgs(arguments, ['object']);
+        return args.object.__class__;
     };
 
     var hash_counter = 0;
-    py.object = py.type(function object() {}, {}, {
+    py.object = py.type('object', [{}], {
+        __new__: function () {
+            // If ``this`` isn't the class object, this is going to be
+            // beyond fucked up
+            var inst = create(this);
+            inst.__is_type = false;
+            return inst;
+        },
+        __init__: function () {},
         // Basic customization
         __hash__: function () {
             if (this._hash) {
                 var val = this[name];
                 if (typeof val === 'object' && '__get__' in val) {
                     // TODO: second argument should be class
-                    return val.__get__(this);
+                    return val.__get__(this, py.PY_call(py.type, [this]));
                 }
                 if (typeof val === 'function' && !this.hasOwnProperty(name)) {
                     // val is a method from the class
-                    return new PY_instancemethod(val, this);
+                    return PY_instancemethod.fromJSON(val, this);
                 }
                 return PY_ensurepy(val);
             }
             throw new Error(this.constructor.name + ' can not be converted to JSON');
         }
     });
-    var NoneType = py.type(function NoneType() {}, py.object, {
+    var NoneType = py.type('NoneType', null, {
         __nonzero__: function () { return py.False; },
         toJSON: function () { return null; }
     });
-    py.None = new NoneType();
-    var NotImplementedType = py.type(function NotImplementedType(){});
-    py.NotImplemented = new NotImplementedType();
+    py.None = py.PY_call(NoneType);
+    var NotImplementedType = py.type('NotImplementedType', null, {});
+    py.NotImplemented = py.PY_call(NotImplementedType);
     var booleans_initialized = false;
-    py.bool = py.type(function bool(value) {
-        value = (value instanceof Array) ? value[0] : value;
-        // The only actual instance of py.bool should be py.True
-        // and py.False. Return the new instance of py.bool if we
-        // are initializing py.True and py.False, otherwise always
-        // return either py.True or py.False.
-        if (!booleans_initialized) {
-            return;
-        }
-        if (value === undefined) { return py.False; }
-        return value.__nonzero__() === py.True ? py.True : py.False;
-    }, py.object, {
+    py.bool = py.type('bool', null, {
+        __new__: function () {
+            if (!booleans_initialized) {
+                return py.object.__new__.apply(this);
+            }
+
+            var ph = {};
+            var args = py.PY_parseArgs(arguments, [['value', ph]]);
+            if (args.value === ph) {
+                return py.False;
+            }
+            return args.value.__nonzero__() === py.True ? py.True : py.False;
+        },
         __nonzero__: function () { return this; },
         toJSON: function () { return this === py.True; }
     });
-    py.True = new py.bool();
-    py.False = new py.bool();
+    py.True = py.PY_call(py.bool);
+    py.False = py.PY_call(py.bool);
     booleans_initialized = true;
-    py.float = py.type(function float(value) {
-        value = (value instanceof Array) ? value[0] : value;
-        if (value === undefined) { this._value = 0; return; }
-        if (value instanceof py.float) { return value; }
-        if (typeof value === 'number' || value instanceof Number) {
-            this._value = value;
-            return;
-        }
-        if (typeof value === 'string' || value instanceof String) {
-            this._value = parseFloat(value);
-            return;
-        }
-        if (value instanceof py.object && '__float__' in value) {
-            var res = value.__float__();
-            if (res instanceof py.float) {
-                return res;
+    py.float = py.type('float', null, {
+        __init__: function () {
+            var placeholder = {};
+            var args = py.PY_parseArgs(arguments, [['value', placeholder]]);
+            var value = args.value;
+            if (value === placeholder) {
+                this._value = 0; return;
             }
-            throw new Error('TypeError: __float__ returned non-float (type ' +
-                            res.constructor.name + ')');
-        }
-        throw new Error('TypeError: float() argument must be a string or a number');
-    }, py.object, {
+            if (py.PY_call(py.isinstance, [value, py.float]) === py.True) {
+                this._value = value._value;
+            }
+            if (py.PY_call(py.isinstance, [value, py.object]) === py.True
+                    && '__float__' in value) {
+                var res = value.__float__();
+                if (py.PY_call(py.isinstance, [res, py.float]) === py.True) {
+                    this._value = res._value;
+                    return;
+                }
+                throw new Error('TypeError: __float__ returned non-float (type ' +
+                                res.__class__.__name__ + ')');
+            }
+            throw new Error('TypeError: float() argument must be a string or a number');
+        },
         __eq__: function (other) {
             return this._value === other._value ? py.True : py.False;
         },
         __lt__: function (other) {
-            if (!(other instanceof py.float)) { return py.NotImplemented; }
+            if (py.PY_call(py.isinstance, [other, py.float]) !== py.True) {
+                return py.NotImplemented;
+            }
             return this._value < other._value ? py.True : py.False;
         },
         __le__: function (other) {
-            if (!(other instanceof py.float)) { return py.NotImplemented; }
+            if (py.PY_call(py.isinstance, [other, py.float]) !== py.True) {
+                return py.NotImplemented;
+            }
             return this._value <= other._value ? py.True : py.False;
         },
         __gt__: function (other) {
-            if (!(other instanceof py.float)) { return py.NotImplemented; }
+            if (py.PY_call(py.isinstance, [other, py.float]) !== py.True) {
+                return py.NotImplemented;
+            }
             return this._value > other._value ? py.True : py.False;
         },
         __ge__: function (other) {
-            if (!(other instanceof py.float)) { return py.NotImplemented; }
+            if (py.PY_call(py.isinstance, [other, py.float]) !== py.True) {
+                return py.NotImplemented;
+            }
             return this._value >= other._value ? py.True : py.False;
         },
         __add__: function (other) {
-            if (!(other instanceof py.float)) { return py.NotImplemented; }
-            return new py.float(this._value + other._value);
+            if (py.PY_call(py.isinstance, [other, py.float]) !== py.True) {
+                return py.NotImplemented;
+            }
+            return py.float.fromJSON(this._value + other._value);
         },
         __neg__: function () {
-            return new py.float(-this._value);
+            return py.float.fromJSON(-this._value);
         },
         __sub__: function (other) {
-            if (!(other instanceof py.float)) { return py.NotImplemented; }
-            return new py.float(this._value - other._value);
+            if (py.PY_call(py.isinstance, [other, py.float]) !== py.True) {
+                return py.NotImplemented;
+            }
+            return py.float.fromJSON(this._value - other._value);
         },
         __mul__: function (other) {
-            if (!(other instanceof py.float)) { return py.NotImplemented; }
-            return new py.float(this._value * other._value);
+            if (py.PY_call(py.isinstance, [other, py.float]) !== py.True) {
+                return py.NotImplemented;
+            }
+            return py.float.fromJSON(this._value * other._value);
         },
         __div__: function (other) {
-            if (!(other instanceof py.float)) { return py.NotImplemented; }
-            return new py.float(this._value / other._value);
+            if (py.PY_call(py.isinstance, [other, py.float]) !== py.True) {
+                return py.NotImplemented;
+            }
+            return py.float.fromJSON(this._value / other._value);
         },
         __nonzero__: function () {
             return this._value ? py.True : py.False;
         },
+        fromJSON: function (v) {
+            if (!(typeof v === 'number')) {
+                throw new Error('py.float.fromJSON can only take numbers');
+            }
+            var instance = py.PY_call(py.float);
+            instance._value = v;
+            return instance;
+        },
         toJSON: function () {
             return this._value;
         }
     });
-    py.str = py.type(function str(s) {
-        s = (s instanceof Array) ? s[0] : s;
-        if (s === undefined) { this._value = ''; return; }
-        if (s instanceof py.str) { return s; }
-        if (typeof s === 'string' || s instanceof String) {
-            this._value = s;
-            return;
-        }
-        var v = s.__str__();
-        if (v instanceof py.str) { return v; }
-        throw new Error('TypeError: __str__ returned non-string (type ' +
-                        v.constructor.name + ')');
-    }, py.object, {
+    py.str = py.type('str', null, {
+        __init__: function () {
+            var placeholder = {};
+            var args = py.PY_parseArgs(arguments, [['value', placeholder]]);
+            var s = args.value;
+            if (s === placeholder) { this._value = ''; return; }
+            if (py.PY_call(py.isinstance, [s, py.str]) === py.True) {
+                this._value = s._value;
+                return;
+            }
+            var v = s.__str__();
+            if (py.PY_call(py.isinstance, [v, py.str]) === py.True) {
+                this._value = v._value;
+                return;
+            }
+            throw new Error('TypeError: __str__ returned non-string (type ' +
+                            v.__class__.__name__ + ')');
+        },
         __hash__: function () {
             return '\1\0\1' + this._value;
         },
         __eq__: function (other) {
-            if (other instanceof py.str && this._value === other._value) {
+            if (py.PY_call(py.isinstance, [other, py.str]) === py.True
+                    && this._value === other._value) {
                 return py.True;
             }
             return py.False;
         },
         __lt__: function (other) {
-            if (!(other instanceof py.str)) { return py.NotImplemented; }
+            if (py.PY_call(py.isinstance, [other, py.str]) !== py.True) {
+                return py.NotImplemented;
+            }
             return this._value < other._value ? py.True : py.False;
         },
         __le__: function (other) {
-            if (!(other instanceof py.str)) { return py.NotImplemented; }
+            if (py.PY_call(py.isinstance, [other, py.str]) !== py.True) {
+                return py.NotImplemented;
+            }
             return this._value <= other._value ? py.True : py.False;
         },
         __gt__: function (other) {
-            if (!(other instanceof py.str)) { return py.NotImplemented; }
+            if (py.PY_call(py.isinstance, [other, py.str]) !== py.True) {
+                return py.NotImplemented;
+            }
             return this._value > other._value ? py.True : py.False;
         },
         __ge__: function (other) {
-            if (!(other instanceof py.str)) { return py.NotImplemented; }
+            if (py.PY_call(py.isinstance, [other, py.str]) !== py.True) {
+                return py.NotImplemented;
+            }
             return this._value >= other._value ? py.True : py.False;
         },
         __add__: function (other) {
-            if (!(other instanceof py.str)) { return py.NotImplemented; }
-            return new py.str(this._value + other._value);
+            if (py.PY_call(py.isinstance, [other, py.str]) !== py.True) {
+                return py.NotImplemented;
+            }
+            return py.str.fromJSON(this._value + other._value);
         },
         __nonzero__: function () {
             return this._value.length ? py.True : py.False;
         __contains__: function (s) {
             return (this._value.indexOf(s._value) !== -1) ? py.True : py.False;
         },
+        fromJSON: function (s) {
+            if (typeof s === 'string') {
+                var instance = py.PY_call(py.str);
+                instance._value = s;
+                return instance;
+            };
+            throw new Error("str.fromJSON can only take strings");
+        },
         toJSON: function () {
             return this._value;
         }
     });
-    py.tuple = py.type(function tuple() {}, null, {
+    py.tuple = py.type('tuple', null, {
         __contains__: function (value) {
             for(var i=0, len=this.values.length; i<len; ++i) {
                 if (this.values[i].__eq__(value) === py.True) {
         }
     });
     py.list = py.tuple;
-    py.dict = py.type(function dict(d) {
-        this._store = {};
-        for (var k in (d || {})) {
-            if (!d.hasOwnProperty(k)) { continue; }
-            var py_k = new py.str(k);
-            var val = PY_ensurepy(d[k]);
-            this._store[py_k.__hash__()] = [py_k, val];
-        }
-    }, py.object, {
+    py.dict = py.type('dict', null, {
+        __init__: function () {
+            this._store = {};
+        },
         __getitem__: function (key) {
             var h = key.__hash__();
             if (!(h in this._store)) {
             }
             return this._store[h][1];
         },
+        fromJSON: function (d) {
+            var instance = py.PY_call(py.dict);
+            for (var k in (d || {})) {
+                if (!d.hasOwnProperty(k)) { continue; }
+                instance.__setitem__(
+                    py.str.fromJSON(k),
+                    PY_ensurepy(d[k]));
+            }
+            return instance;
+        },
         toJSON: function () {
             var out = {};
             for(var k in this._store) {
             return out;
         }
     });
-    py.PY_def = py.type(function def(nativefunc) {
-        this._inst = null;
-        this._func = nativefunc;
-    }, py.object, {
+    py.PY_def = py.type('function', null, {
         __call__: function () {
             // don't want to rewrite __call__ for instancemethod
             return this._func.apply(this._inst, arguments);
         },
+        fromJSON: function (nativefunc) {
+            var instance = py.PY_call(py.PY_def);
+            instance._inst = null;
+            instance._func = nativefunc;
+            return instance;
+        },
         toJSON: function () {
             return this._func;
         }
     });
-    var PY_instancemethod = py.type(function instancemethod(nativefunc, instance, _cls) {
-        // could also use bind?
-        this._inst = instance;
-        this._func = nativefunc;
-    }, py.PY_def, {});
+    var PY_instancemethod = py.type('instancemethod', [py.PY_def], {
+        fromJSON: function (nativefunc, instance) {
+            var inst = py.PY_call(PY_instancemethod);
+            // could also use bind?
+            inst._inst = instance;
+            inst._func = nativefunc;
+            return inst;
+        }
+    });
 
-    py.issubclass = new py.PY_def(function issubclass() {
+    py.isinstance = new py.PY_def.fromJSON(function isinstance() {
+        var args = py.PY_parseArgs(arguments, ['object', 'class']);
+        var fn = function () {};
+        fn.prototype = args['class'];
+        return (args.object instanceof fn) ? py.True : py.False;
+    });
+    py.issubclass = new py.PY_def.fromJSON(function issubclass() {
         var args = py.PY_parseArgs(arguments, ['C', 'B']);
-        if (args.C === args.B || args.C.prototype instanceof args.B) {
+        var fn = function () {};
+        fn.prototype = args.B;
+        if (args.C === args.B || args.C instanceof fn) {
             return py.True;
         }
         return py.False;
         '==': ['eq', 'eq', function (a, b) { return a === b; }],
         '!=': ['ne', 'ne', function (a, b) { return a !== b; }],
         '<>': ['ne', 'ne', function (a, b) { return a !== b; }],
-        '<': ['lt', 'gt', function (a, b) {return a.constructor.name < b.constructor.name;}],
-        '<=': ['le', 'ge', function (a, b) {return a.constructor.name <= b.constructor.name;}],
-        '>': ['gt', 'lt', function (a, b) {return a.constructor.name > b.constructor.name;}],
-        '>=': ['ge', 'le', function (a, b) {return a.constructor.name >= b.constructor.name;}],
+        '<': ['lt', 'gt', function (a, b) {return a.__class__.__name__ < b.__class__.__name__;}],
+        '<=': ['le', 'ge', function (a, b) {return a.__class__.__name__ <= b.__class__.__name__;}],
+        '>': ['gt', 'lt', function (a, b) {return a.__class__.__name__ > b.__class__.__name__;}],
+        '>=': ['ge', 'le', function (a, b) {return a.__class__.__name__ >= b.__class__.__name__;}],
 
         '+': ['add', 'radd'],
         '-': ['sub', 'rsub'],
         }
         throw new Error(
             "TypeError: unsupported operand type(s) for " + op + ": '"
-                + o1.constructor.name + "' and '"
-                + o2.constructor.name + "'");
+                + o1.__class__.__name__ + "' and '"
+                + o2.__class__.__name__ + "'");
     };
 
     var PY_builtins = {
         tuple: py.tuple,
         list: py.list,
         dict: py.dict,
+        isinstance: py.isinstance,
         issubclass: py.issubclass
     };
 
             }
             return PY_ensurepy(val, expr.value);
         case '(string)':
-            return new py.str(expr.value);
+            return py.str.fromJSON(expr.value);
         case '(number)':
-            return new py.float(expr.value);
+            return py.float.fromJSON(expr.value);
         case '(constant)':
             switch (expr.value) {
             case 'None': return py.None;
                             py.evaluate(arg.second, context);
                     }
                 }
-                return callable.__call__(args, kwargs);
+                return py.PY_call(callable, args, kwargs);
             }
             var tuple_exprs = expr.first,
                 tuple_values = [];
                 tuple_values.push(py.evaluate(
                     tuple_exprs[j], context));
             }
-            var t = new py.tuple();
+            var t = py.PY_call(py.tuple);
             t.values = tuple_values;
             return t;
         case '[':
                 list_values.push(py.evaluate(
                     list_exprs[k], context));
             }
-            var l = new py.list();
+            var l = py.PY_call(py.list);
             l.values = list_values;
             return l;
         case '{':
-            var dict_exprs = expr.first, dict = new py.dict;
+            var dict_exprs = expr.first, dict = py.PY_call(py.dict);
             for(var l=0; l<dict_exprs.length; ++l) {
                 dict.__setitem__(
                     py.evaluate(dict_exprs[l][0], context),

File test/builtins/type.js

+var py = require('../../lib/py.js'),
+    expect = require('expect.js');
+
+var ev = function (str, context) {
+    return py.evaluate(py.parse(py.tokenize(str)), context);
+};
+
+describe('Create new type', function () {
+    describe('basic properties', function () {
+        var typ = py.type('MyType', null, {});
+        it('should have a __name__', function () {
+            expect(typ.__name__).to.be('MyType');
+            expect(py.eval('typ.__name__', {typ: typ}))
+                .to.be("MyType");
+        });
+        it('should have default __bases__', function () {
+            expect(typ.__bases__).to.eql([py.object]);
+        });
+    });
+    describe('limitations', function () {
+        it('should not accept multiple bases', function () {
+            expect(function () {
+                py.type('MyType', [py.float, py.str], {});
+            }).to.throwException(/^ValueError/);
+        });
+    });
+});
+describe('Get object type', function () {
+    expect(ev('type(True)')).to.be(py.bool);
+    expect(ev('type("foo")')).to.be(py.str);
+    var typ = py.type('MyType', null, {});
+    expect(ev('type(typ())', {typ: typ})).to.be(typ);
+});

File test/test.js

             }).to.throwException(/^TypeError/);
         });
         it('should not require optional arguments', function () {
-            var val = new py.float(3);
+            var val = py.float.fromJSON(3);
             expect(py.PY_parseArgs([[], {}], [['foo', val]]))
                 .to.eql({
                     foo: val
                 });
         });
         it('should override defaults', function () {
-            var def = new py.float(3);
-            var val = new py.float(4);
+            var def = py.float.fromJSON(3);
+            var val = py.float.fromJSON(4);
 
             expect(py.PY_parseArgs([[val], {}], [['foo', def]]))
                 .to.eql({
 describe('Literals', function () {
     describe('Number', function () {
         it('should have the right type', function () {
-            expect(ev('1')).to.be.a(py.float);
+            expect(ev('1').__class__).to.be(py.float);
         });
         it('should yield the corresponding JS value', function () {
             expect(py.eval('1')).to.be(1);
     });
     describe('Booleans', function () {
         it('should have the right type', function () {
-            expect(ev('False')).to.be.a(py.bool);
-            expect(ev('True')).to.be.a(py.bool);
+            expect(ev('False').__class__).to.be(py.bool);
+            expect(ev('True').__class__).to.be(py.bool);
         });
         it('should yield the corresponding JS value', function () {
             expect(py.eval('False')).to.be(false);
     });
     describe('None', function () {
         it('should have the right type', function () {
-            expect(ev('None')).to.be.a(py.object)
+            expect(ev('isinstance(None, object)')).to.be(py.True)
         });
         it('should yield a JS null', function () {
             expect(py.eval('None')).to.be(null);
     });
     describe('String', function () {
         it('should have the right type', function () {
-            expect(ev('"foo"')).to.be.a(py.str);
-            expect(ev("'foo'")).to.be.a(py.str);
+            expect(ev('"foo"').__class__).to.be(py.str);
+            expect(ev("'foo'").__class__).to.be(py.str);
         });
         it('should yield the corresponding JS string', function () {
             expect(py.eval('"somestring"')).to.be('somestring');
     });
     describe('Tuple', function () {
         it('shoud have the right type', function () {
-            expect(ev('()')).to.be.a(py.tuple);
+            expect(ev('()').__class__).to.be(py.tuple);
         });
         it('should map to a JS array', function () {
             expect(py.eval('()')).to.eql([]);
     });
     describe('List', function () {
         it('shoud have the right type', function () {
-            expect(ev('[]')).to.be.a(py.list);
+            expect(ev('[]').__class__).to.be(py.list);
         });
         it('should map to a JS array', function () {
             expect(py.eval('[]')).to.eql([]);
     });
     describe('Dict', function () {
         it('shoud have the right type', function () {
-            expect(ev('{}')).to.be.a(py.dict);
+            expect(ev('{}').__class__).to.be(py.dict);
         });
         it('should map to a JS object', function () {
             expect(py.eval("{}")).to.eql({});
     });
     describe('missing eq/neq', function () {
         it('should fall back on identity', function () {
-            var typ = new py.type(function MyType() {});
+            var typ = py.type('MyType', null, {});
             expect(py.eval('MyType() == MyType()', {MyType: typ})).to.be(false);
         });
     });
     describe('un-comparable types', function () {
         it('should default to type-name ordering', function () {
-            var t1 = new py.type(function Type1() {});
-            var t2 = new py.type(function Type2() {});
+            var t1 = py.type('Type1', null, {});
+            var t2 = py.type('Type2', null, {});
             expect(py.eval('T1() < T2()', {T1: t1, T2: t2})).to.be(true);
             expect(py.eval('T1() > T2()', {T1: t1, T2: t2})).to.be(false);
         });
 });
 describe('Attribute access', function () {
     it("should return the attribute's value", function () {
-        var o = new py.object();
+        var o = py.PY_call(py.object);
         o.bar = py.True;
         expect(py.eval('foo.bar', {foo: o})).to.be(true);
         o.bar = py.False;
         expect(py.eval('foo.bar', {foo: o})).to.be(false);
     });
     it("should work with functions", function () {
-        var o = new py.object();
-        o.bar = new py.PY_def(function () {
-            return new py.str("ok");
+        var o = py.PY_call(py.object);
+        o.bar = py.PY_def.fromJSON(function () {
+            return py.str.fromJSON("ok");
         });
         expect(py.eval('foo.bar()', {foo: o})).to.be('ok');
     });
     it('should not convert function attributes into methods', function () {
-        var o = new py.object();
-        o.bar = new py.type(function bar() {});
+        var o = py.PY_call(py.object);
+        o.bar = py.type('bar', null, {});
         o.bar.__getattribute__ = function () {
             return o.bar.baz;
         }
         expect(py.eval('foo.bar.baz', {foo: o})).to.be(true);
     });
     it('should work on instance attributes', function () {
-        var typ = py.type(function MyType() {
-            this.attr = new py.float(3);
-        }, py.object, {});
+        var typ = py.type('MyType', null, {
+            __init__: function () {
+                this.attr = py.float.fromJSON(3);
+            }
+        });
         expect(py.eval('MyType().attr', {MyType: typ})).to.be(3);
     });
     it('should work on class attributes', function () {
-        var typ = py.type(function MyType() {}, py.object, {
-            attr: new py.float(3)
+        var typ = py.type('MyType', null, {
+            attr: py.float.fromJSON(3)
         });
         expect(py.eval('MyType().attr', {MyType: typ})).to.be(3);
     });
     it('should work with methods', function () {
-        var typ = py.type(function MyType() {
-            this.attr = new py.float(3);
-        }, py.object, {
-            some_method: function () { return new py.str('ok'); },
+        var typ = py.type('MyType', null, {
+            __init__: function () {
+                this.attr = py.float.fromJSON(3);
+            },
+            some_method: function () { return py.str.fromJSON('ok'); },
             get_attr: function () { return this.attr; }
         });
         expect(py.eval('MyType().some_method()', {MyType: typ})).to.be('ok');
 });
 describe('Callables', function () {
     it('should wrap JS functions', function () {
-        expect(py.eval('foo()', {foo: function foo() { return new py.float(3); }}))
+        expect(py.eval('foo()', {foo: function foo() { return py.float.fromJSON(3); }}))
             .to.be(3);
     });
     it('should work on custom types', function () {
-        var typ = py.type(function MyType() {}, py.object, {
+        var typ = py.type('MyType', null, {
             toJSON: function () { return true; }
         });
         expect(py.eval('MyType()', {MyType: typ})).to.be(true);
 });
 describe('dicts', function () {
     it('should be possible to retrieve their value', function () {
-        var d = new py.dict({foo: 3, bar: 4, baz: 5});
+        var d = py.dict.fromJSON({foo: 3, bar: 4, baz: 5});
         expect(py.eval('d["foo"]', {d: d})).to.be(3);
         expect(py.eval('d["baz"]', {d: d})).to.be(5);
     });
     it('should raise KeyError if a key is missing', function () {
-        var d = new py.dict();
+        var d = py.dict.fromJSON();
         expect(function () {
             py.eval('d["foo"]', {d: d});
         }).to.throwException(/^KeyError/);
     });
     it('should have a method to provide a default value', function () {
-        var d = new py.dict({foo: 3});
+        var d = py.dict.fromJSON({foo: 3});
         expect(py.eval('d.get("foo")', {d: d})).to.be(3);
         expect(py.eval('d.get("bar")', {d: d})).to.be(null);
         expect(py.eval('d.get("bar", 42)', {d: d})).to.be(42);
 
-        var e = new py.dict({foo: null});
+        var e = py.dict.fromJSON({foo: null});
         expect(py.eval('d.get("foo")', {d: e})).to.be(null);
         expect(py.eval('d.get("bar")', {d: e})).to.be(null);
     });