S.E.
S.E.

Reputation: 29

If __metaclass__ is a class attribute, how does it control the generation of the class?

We know that when generating a class in Python2, if there is a metaclass attribute, it will be generated by the metaclass referenced by the attribute. Bug when the class is not generated, it should have no attribute, how does it control the generation of the class?

Upvotes: 0

Views: 42

Answers (2)

chepner
chepner

Reputation: 531075

The Python implementation itself first gathers the names defined in the namespace of the class statement, then generates a call to the metaclass with those names passed as a mapping argument to the metaclass. That is, something like

class Foo:
    x = 3

is used to generate something equivalent to

Foo = type('Foo', (), {'x': 3})

as type is the default metaclass.

When the name __metaclass__ is encountered in the namespace, the implementation uses the value as the metaclass instead of type.

class Foo:
    __metaclass__ = Bar

becomes (roughly)

Foo = Bar('Foo', (), {'__metaclass__': Bar}).

(I am purposely ignoring the lack of an explicit base class for Foo. I don't fully understand how a seemingly old-style class with a specified __metaclass__ differs from a "pure" old-style class or another new-style class, but any differences don't seem relevant to the question at hand.)

Upvotes: 1

juanpa.arrivillaga
juanpa.arrivillaga

Reputation: 95948

Because the body of the class definition statement is evaluated before the creation of the class object.

So indeed, the class doesn't have that attribute, the class doesn't even exist yet. But the class definition statement has been evaluated.

Upvotes: 3

Related Questions