pygobject / pgi-docgen

API Documentation Generator for PyGObject
https://lazka.github.io/pgi-docs/
GNU Lesser General Public License v2.1
128 stars 36 forks source link

Create dummy int subclasses for gintXX/guintXX #4

Closed lazka closed 9 years ago

lazka commented 10 years ago

Atm one has to look at the C docs to know the valid value range. Not sure if the following is the best approach.

from gi.repository import GLib, GObject

class _gint64_type_(type):

    def __instancecheck__(self, other):
        if not isinstance(other, int):
            return False

        return self._in_range(other)

class gint64(int):
    __metaclass__ = _gint64_type_
    __gtype__ = GObject.TYPE_INT64

    @staticmethod
    def _in_range(value):
        return GLib.MININT64 <= value <= GLib.MAXINT64

    def __new__(cls, v, *args, **kwargs):
        instance = super(gint64, cls).__new__(cls, v)
        if not cls._in_range(instance):
            raise ValueError("out of range")
        return instance

assert gint64(2) == 2
assert gint64("2") == 2
assert isinstance(3, gint64)
assert not isinstance("3", gint64)
assert not isinstance(2**70, gint64)
assert GObject.GType(gint64) == GObject.TYPE_INT64
lazka commented 9 years ago

On a second though it is probably enough to note that arbitrary large ints can cause overflow errors.

Stuff for the PyGObject documentation.