Implementing PEP 3130 using decorators

Hi PEP 3130, 'Access to Current Module/Class/Function', proposed the introduction of new keywords (__class__, __function__, and __module__) to refer to what lexical unit theses names were in. It was rejected, but I have thought about a way to produce the same functionality without the need of new keywords, by using decorators instead. It would go like this: class Foo(object): # some defs... @bindclass def bar(thisclass, self): # Within this method the name 'thiclass' refers to class Foo # ... @bindclass def bar(Foo, self): # The name of 'thisclass' can be chosen, just like 'self' can. # Within this method the name 'Foo' refers to class Foo, even # after Foo is bound to another object # ... # More defs... @bindfunction def factorial(thisfunction, n): # Within this function the name 'thisfunction' refers to the factorial # function (with only one argument), even after 'factorial' is bound # to another object if n > 0: return n * thisfunction(n - 1) else: return 1 Here is an implementation: class bindclass(object): def __init__(self, f): self.f = f def bind(self, cls, attr): def bound_m(*args, **kwargs): return self.f(cls, *args, **kwargs) bound_m.__name__ = attr self.m = bound_m def __get__(self, obj, objtype=None): return self.m.__get__(obj, objtype) class Type(type): def __init__(self, name, bases, attrs): for attr, val in attrs.iteritems(): if isinstance(val, bindclass): val.bind(self, attr) class Object(object): __metaclass__ = Type def bindfunction(f): def bound_f(*args, **kwargs): return f(bound_f, *args, **kwargs) bound_f.__name__ = f.__name__ return bound_f And an example: class Foo(Object): @bindclass def foo(this_class, self): return this_class, self class Bar(Foo): @bindclass def bar(this_class, self): return this_class, self f = Foo() b = Bar() f.foo() # -> Foo, Foo object b.foo() # -> Foo, Foo object f.bar() # -> Bar, Foo object -- Arnaud
participants (1)
-
Arnaud Delobelle