Welcome, guest | Sign In | My Account | Store | Cart

The only catch is that the function has to return locals() at the end. And it doesn't do the __prepare__ part of 3.x metaclasses.

Python, 19 lines
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
def as_class(*bases, metaclass=type, **kwargs):
    def decorator(f):
        namespace = f()
        if "__doc__" not in namespace:
            namespace["__doc__"] = f.__doc__
        return metaclass(f.__name__, bases, namespace)
    return decorator

@as_class(object)
def X():
    def __init__(self, name):
        self.__name__ = name
    def __str__(self):
        return self.__name__
    return locals()

x=X("something")
assert x.__name__ == "something"
print(x)

It wouldn't be too hard to make this technique even more authentic. Also, making the call syntax optional for the decorator factory is pretty simple.