Skip to main content

A simple and dirty way to define generic methods to existing types.

Project description

It provides a simple and dirty way to define generic methods to existing types. You can make overloaded methods using this.


TypeQuery does not depend on any non-standard libraries. It works on these environments:

  • Python 2.5 to 3.2
  • CPython, Stackless, PyPy, Jython


Install using pip:

$ pip install TypeQuery

or easy_install:

$ easy_install TypeQuery

Example: JSON encoder

from typequery import GenericMethod
from sys import version_info
from re import sub
from numbers import Real
from collections import Mapping, Iterable

if version_info.major > 2:
    basestring = string = str
    string = unicode

json = GenericMethod('serialize')

def json(value):
    return 'null'

def json(value):
    return 'true' if value else 'false'

def json(value):
    return str(value)

def json(value):
    def escape(match):
        s =
        if s in ('\\', '"', '\b', '\f', '\n', '\r', '\t'):
            return '\\' + s
        n = ord(s)
        if n < 0x10000:
            return r'\u%04x' % n
        n -= 0x10000
        s1 = 0xd800 | ((n >> 10) & 0x3ff)
        s2 = 0xdc00 | (n & 0x3ff)
        return r'\u%04x\u%04x' % (s1, s2)
    return '"%s"' % sub(r'([\\"]|[^\ -~])', escape, value)

def json(value):
    return '[%s]' % ', '.join(json(element) for element in value)

def json(value):
    return '{%s}' % ', '.join('%s: %s' % (json(string(key)), json(value))
                              for key, value in value.items())

And defined json function works like:

>>> json(123)
>>> json(True)
>>> json({'apple': 3, 'banana': 5, 'carrot': 1})
'{"apple": 3, "banana": 5, "carrot": 1}'

As the above shows, you can define type-aware instance methods to existing types even including ABCs like collections.Iterable.

Author and license

Written by Hong Minhee. Distributed under MIT license. You can find the source code from the Bitbucket repository:

$ hg clone

Project details

Supported by

Elastic Elastic Search Pingdom Pingdom Monitoring Google Google BigQuery Sentry Sentry Error logging AWS AWS Cloud computing DataDog DataDog Monitoring Fastly Fastly CDN SignalFx SignalFx Supporter DigiCert DigiCert EV certificate StatusPage StatusPage Status page