[issue23132] Faster total_ordering

Nick Coghlan report at bugs.python.org
Sun Jan 4 10:20:25 CET 2015


Nick Coghlan added the comment:

While I like the readability of Raymond's version, I think the main pay-off we're getting from the template based version is that each decorator invocation is creating *new* function objects.

That creation of new function objects is what allows Serhiy's patch to set __module__ and __qualname__ for each method implementation based on the class being defined.

The two approaches could be combined by moving the explicit definitions into factory functions that always created new function objects and set their introspection attributes appropriately. For example (untested code):

    def _fix_introspection(module, cls_qualname):
        def update_metadata(f):
            f.__qualname__ = "%s.%s" % (cls_qualname, f.__name__)
            f.__module__ = module
            return f
        return update_metadata

    def _derive_from_lt(module, cls_qualname):
        _NotImplemented = NotImplemented

        @_fix_introspection(module, cls_qualname)
        def __gt__(self, other):
            op_result = self.__lt__(other)
            if op_result is _NotImplemented:
                return _NotImplemented
            return not op_result and self != other

        @_fix_introspection(module, cls_qualname)
        def __le__(self, other):
            op_result = self.__lt__(other)
            return op_result or self == other

        @_fix_introspection(module, cls_qualname)
        def __ge__(self, other):
            op_result = self.__lt__(other)
            if op_result is _NotImplemented:
                return _NotImplemented
            return not op_result

        return __lt__, __gt__, __ge__

----------

_______________________________________
Python tracker <report at bugs.python.org>
<http://bugs.python.org/issue23132>
_______________________________________


More information about the Python-bugs-list mailing list