No, you can only specify a metaclass for each class or for each module. You cannot install it for the whole package.
In Python 3.1 and later, you can builtins.__build_class__ and programmatically insert a metaclass, see Overriding the default metaclass () before running Python .
In Python 2.7, you can replace __builtins__.object with a subclass that uses your metaclass. Like the builtins.__build_class__ , it is an advanced hacker and breaks your code in the same way as getting your metaclass anywhere.
Do this by replacing the object reference with __builtin__ module :
import __builtin__ class MetaClass(type): def __new__(mcls, name, *args): # do something in the metaclass return super(MetaClass, mcls).__new__(mcls, name, *args) orig_object = __builtin__.orig_object class metaobject(orig_object): __metaclass__ = MetaClass def enable(): # *replace* object with one that uses your metaclass __builtin__.object = metaobject def disable(): __builtin__.object = orig_object
Run enable() before importing your package, and all new-style classes (those that can support the metaclass) will have your metaclass. Note that this behavior will now apply to all Python code that has not yet been loaded, including the standard library, since your package imports the code. You probably want to use:
enable() import package disable()
to limit the effects.
Martijn pieters
source share