TypeQuery

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

TypeQuery Ranking & Summary

Advertisement

  • Rating:
  • License:
  • MIT/X Consortium Lic...
  • Price:
  • FREE
  • Publisher Name:
  • Hong MinHee
  • Publisher web site:
  • http://dirty.googlecode.com/

TypeQuery Tags


TypeQuery Description

TypeQuery provides a simple and dirty way to define generic methods to existing types. You can make overloaded methods using this.CompatibilityTypeQuery does not depend on any non-standard libraries. It works on these environments:- Python 2.5 to 3.2- CPython, Stackless, PyPy, JythonInstallInstall using pip: pip install TypeQueryor easy_install: easy_install TypeQueryExample: JSON encoderfrom typequery import GenericMethodfrom sys import version_infofrom re import subfrom numbers import Realfrom collections import Mapping, Iterableif version_info.major > 2: basestring = string = strelse: string = unicodejson = GenericMethod('serialize')@json.of(type(None))def json(value): return 'null'@json.of(bool)def json(value): return 'true' if value else 'false'@json.of(Real)def json(value): return str(value)@json.of(string)def json(value): def escape(match): s = match.group(0) if s in ('\\', '"', '\b', '\f', '\n', '\r', '\t'): return '\\' + s n = ord(s) if n < 0x10000: return r'\ux' % n n -= 0x10000 s1 = 0xd800 | ((n >> 10) & 0x3ff) s2 = 0xdc00 | (n & 0x3ff) return r'\ux\ux' % (s1, s2) return '"%s"' % sub(r'(|)', escape, value)@json.of(Iterable)def json(value): return '' % ', '.join(json(element) for element in value)@json.of(Mapping)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)'123'>>> json(True)'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.Product's homepage


TypeQuery Related Software