diff options
author | Timothy Crosley <timothy.crosley@gmail.com> | 2013-12-14 21:56:39 -0500 |
---|---|---|
committer | Timothy Crosley <timothy.crosley@gmail.com> | 2013-12-14 21:56:39 -0500 |
commit | 185c87d0b5073cbb684fe38d5143515a5b0d07c5 (patch) | |
tree | 2ed6b6caf06322b4571f0fe49fbf9b505e86e9ac | |
parent | 5ae96206ed544d7360ddd88086f611e0a1c2f2a5 (diff) | |
download | pies-185c87d0b5073cbb684fe38d5143515a5b0d07c5.tar.gz |
Add support for Python2 & 3 compatible metaclass usage
-rw-r--r-- | README.md | 1 | ||||
-rw-r--r-- | pies/overrides.py | 27 | ||||
-rw-r--r-- | pies/unittest.py | 2 |
3 files changed, 29 insertions, 1 deletions
@@ -122,6 +122,7 @@ Sadly, there is still special syntax that is present for corner cases. - keysview(collection) - should replace collection.keys() where you do not control the collection passed in - execute() - enables Python 3 style exec statements on both environments. - integer_types - may want to use isinstance(variable, integer_types) instead of type(variable, int) as long values will not match int in Python2. +- NewClass(with_metaclass(metaclass, parent_class)) - Should replace both "__metaclass__ = metaclass" and "NewClass(metaclass=metaclass)" as a way to assign meta-classes. What Could be Improved? ====================== diff --git a/pies/overrides.py b/pies/overrides.py index 926d51b..e8376f5 100644 --- a/pies/overrides.py +++ b/pies/overrides.py @@ -41,7 +41,7 @@ native_next = next common = ['native_dict', 'native_round', 'native_filter', 'native_map', 'native_range', 'native_str', 'native_chr', 'native_input', 'PY2', 'PY3', 'u', 'itemsview', 'valuesview', 'keysview', 'execute', 'integer_types', - 'native_next'] + 'native_next', 'with_metaclass'] if PY3: import urllib @@ -200,3 +200,28 @@ else: __all__ = common + ['round', 'dict', 'apply', 'cmp', 'coerce', 'execfile', 'raw_input', 'unpacks', 'str', 'chr', 'input', 'range', 'filter', 'map', 'zip'] + +def with_metaclass(meta, *bases): + """ + Enables use of meta classes across Python Versions. + taken from jinja2/_compat.py + + Use it like this:: + + class BaseForm(object): + pass + + class FormType(type): + pass + + class Form(with_metaclass(FormType, BaseForm)): + pass + """ + class metaclass(meta): + __call__ = type.__call__ + __init__ = type.__init__ + def __new__(cls, name, this_bases, d): + if this_bases is None: + return type.__new__(cls, name, (), d) + return meta(name, bases, d) + return metaclass('temporary_class', None, {}) diff --git a/pies/unittest.py b/pies/unittest.py index 03b130e..328e554 100644 --- a/pies/unittest.py +++ b/pies/unittest.py @@ -3,6 +3,8 @@ from __future__ import absolute_import import sys from unittest import * +NativeTestCase = TestCase + if sys.version_info < (2, 7): skip = lambda why: (lambda func: 'skip') skipIf = lambda cond, why: (skip(why) if cond else lambda func: func) |