Is it possible to instantiate a class in my metaclass in Python?

Is it safe to create a class instance constructors metaclass ( __new__and __init__)? I'm particularly interested in Python 2.7, but what Python 3 does is also welcome.

Python data model documents sound as if they were written to create a regular instance of a class, and I'm not quite sure how rules can be subtly different when they appear in a metaclass.

For example, let's say I have a code like this:

class Meta(type):
  NEWED = []
  INITED_BEFORE = []
  INITED_AFTER = []
  def __new__(meta, name, bases, dict):
    cls = super(Meta, meta).__new__(meta, name, bases, dict)
    instance = cls()
    Meta.NEWED.append(instance)
    return cls

  def __init__(cls, name, bases, dict):
    Meta.INITED_BEFORE.append(cls())
    super(Meta, cls).__init__(name, bases, dict)
    Meta.INITED_AFTER.append(cls())

class Foo(object):
  __metaclass__ = Meta

At what points, if any, is it safe to build an instance of Foo, while the metaclass will build it, and what warnings exist?

, Foo , , cls() - . ?

+4
1

: Foo , , cls() - . ?

, __new__ __init__ . __init__, , , . , .

, , - __init__ __new__. - __init__, , __init__ 'd . , , .

0

All Articles