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

This may sound too good to be true, but see for yourself. No time machines involved. Just plug in this metaclass and look for __newclass__ in your class body. It's not perfect, but the problematic corner cases are more bark than bite.

Python, 11 lines
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
class InwardMeta(type):
    @classmethod
    def __prepare__(meta, name, bases, **kwargs):
        cls = super().__new__(meta, name, bases, {})
        return {"__newclass__": cls}
    def __new__(meta, name, bases, namespace):
        cls = namespace["__newclass__"]
        del namespace["__newclass__"]
        for name in namespace:
            setattr(cls, name, namespace[name])
        return cls

Example

class X(metaclass=Meta):
    print(__newclass__, id(__newclass__))
print(X, id(X))
# this will print the same thing twice
Created by Eric Snow on Thu, 15 Sep 2011 (MIT)
Python recipes (4591)
Eric Snow's recipes (39)

Required Modules

  • (none specified)

Other Information and Tasks