35

In Python 3.1, there is a new builtin function I don't know in the builtins module:

__build_class__(...)
    __build_class__(func, name, *bases, metaclass=None, **kwds) -> class

    Internal helper function used by the class statement.

What does this function do? Why must it be in builtins if it's internal? What is the difference to the type(name, bases, dict) function?

jsbueno
  • 99,910
  • 10
  • 151
  • 209
u0b34a0f6ae
  • 48,117
  • 14
  • 92
  • 101

1 Answers1

33

Compiling the PEP 3115 metaclass

Guido van Rossum said:

The PEP proposes that the class statement accepts keyword arguments, *args, and **kwds syntax as well as positional bases. This is a bit messy to compile and execute, but we already have this, of course, in the code for calling regular functions.

So I think it would be acceptable to this into a call to a new (hidden) built-in function, named __build_class__. Then that this class definition:

  class C(A, B, metaclass=M, other=42, *more_bases, *more_kwds):
    ...

would translate into this:

  C = __build_class__(<func>, 'C', A, B, metaclass=M, other=42,
*more_bases, *more_kwds)

where <func> is a function object for the class body.

Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
CodeJoust
  • 3,760
  • 21
  • 23
  • 4
    What is the "function object for the class body"? – DeFazer Dec 03 '16 at 17:09
  • 1
    You can find this information in the code example in the linked post from Guido van Rossum. `__build_class__` will call something like `locals = {}; func(locals)`. That is, for a class `class X: y = 1`, the equivalent body function `` would be: `def func(locals): locals.y = 1` – filip Jan 21 '17 at 18:37