No, you can only specify the metaclass per class or per module. You cannot set it for the whole package.
In Python 3.1 and onwards, you can intercept the builtins.__build_class__
hook and insert a metaclass programatically, see Overriding the default type() metaclass before Python runs.
In Python 2.7, you could replace __builtins__.object
with a subclass that uses your metaclass. Like the builtins.__build_class__
hook, this is advanced hackery and break your code as much as getting your metaclass in everwhere.
Do so by replacing the object
reference on the __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()
this before importing your package and all new-style classes (those that can support a metaclass) will have your metaclass. Note that this behaviour now will propagate to all Python code not already loaded, including the standard library, as your package imports code. You probably want to use:
enable()
import package
disable()
to limit the effects.