26

In contrast to functions, a class' body is executed at definition time:

class A(object):
    print 'hello'

Out:

hello

Why is it the case? Is it related to @classmethod / @staticmethod methods and class attributes?

wjandrea
  • 28,235
  • 9
  • 60
  • 81
usual me
  • 8,338
  • 10
  • 52
  • 95
  • 6
    When else would it get executed? – John Zwinck Oct 04 '14 at 14:16
  • 9
    @JohnZwinck I could understand their confusion. It would be intuitive that a class body would only get executed upon instantiation of the first instance of the class (although that is not the case). – Cory Kramer Oct 04 '14 at 14:20
  • 4
    a simple answer - because that is the way the language is defined.. – Tony Suffolk 66 Oct 04 '14 at 14:21
  • 2
    Ask yourself: how could you use the class if it *wasn't* executed when the module is loaded? – Martijn Pieters Oct 04 '14 at 14:31
  • 4
    Unlike in some languages, a class is a first-class object (no pun intended) that exists in memory, rather than a static instruction to the compiler on how to create objects later. A class object is created by executing the `class` statement, which is simply a declarative wrapper around a call to the `type` function (or whatever callable is specified as the metaclass, but you don't need to worry about that technicality). – chepner Oct 04 '14 at 14:43
  • Also consider that _some_ parts of a function are executed at definition time: specifically, its default arguments are evaluated. And that also applies to any functions that are defined inside the function. – PM 2Ring Oct 04 '14 at 14:44
  • @PM2Ring Well, to be precise, the `def` statement is executed. Part of that execution is to evaluate the default arguments. – chepner Oct 04 '14 at 15:17
  • @chepner Nicely put. Defining the function name is the main thing, evaluating default arguments is a just a side "benefit". :) And I guess the function's local name space is also set up at that time? – PM 2Ring Oct 05 '14 at 00:51
  • @JohnzWinck For example lazily when needed. Don't misunderstand me - I like it that way more too. – NoDataDumpNoContribution Dec 01 '14 at 11:51

3 Answers3

34

Everything is executed at the module level when Python first imports a module. Function bodies (and generator expression bodies) are the exception here, not the rule. Python executes everything to create the objects contained in a module; like everything in Python, classes are objects, and so are functions.

The only reason a class body uses a separate code object is because a class body is executed in a separate namespace, with that namespace then forming the class attributes. Class bodies are not the only such namespaces; set and dict comprehensions, and in Python 3, list comprehensions are also executed with a separate namespace, scoping their locals.

So functions and generator expressions are the exception, expressly because their whole purpose is to be executed at a later time. Note that the function definition is executed:

>>> import dis
>>> dis.dis(compile('def foo(): pass', '<stdin>', 'exec'))
  1           0 LOAD_CONST               0 (<code object foo at 0x106aef2b0, file "<stdin>", line 1>)
              3 MAKE_FUNCTION            0
              6 STORE_NAME               0 (foo)
              9 LOAD_CONST               1 (None)
             12 RETURN_VALUE        

The MAKE_FUNCTION bytecode there creates the function object, together with the stored bytecode for that function, and the result is bound to the global name foo.

Class objects are no different here; the class statement produces a class object, and as part of that object, we need to know the attributes from the class body.

If Python did not execute the class body, other code could not make any use of those class members. You couldn't access class attributes (including class methods and static methods), you couldn't set class attributes, etc.

Any functions that are part of the class body are of course not executed at that time. Just like top-level functions, only a MAKE_FUNCTION bytecode is executed and the resulting local name (set with STORE_FAST) is then turned into a class attribute, analogous to a global function object being bound to a global with STORE_NAME.

Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
11

According to Class definitions - Python documentation:

A class definition is an executable statement. It first evaluates the inheritance list, if present. Each item in the inheritance list should evaluate to a class object or class type which allows subclassing. The class’s suite is then executed in a new execution frame (see section Naming and binding), using a newly created local namespace and the original global namespace. (Usually, the suite contains only function definitions.) When the class’s suite finishes execution, its execution frame is discarded but its local namespace is saved. A class object is then created using the inheritance list for the base classes and the saved local namespace for the attribute dictionary. The class name is bound to this class object in the original local namespace.

falsetru
  • 357,413
  • 63
  • 732
  • 636
  • 1
    Side note: This innocently looking part: *A class object is then created using the inheritance list for the base classes and the saved local namespace for the attribute dictionary* is a source of a lot of confusion when it comes to name resolution in class's methods... – BartoszKP Oct 04 '14 at 14:26
  • This just states that the class body is indeed executed. It doesn't really motivate *why* it is executed. It is a 'because' answer. – Martijn Pieters Oct 04 '14 at 16:25
0

Consider these two classes A and B:

class A:
    p=4

def add(i, j):
    return i + j

class B:
    p = add(2, 2)

a = A()
b = B()
print("a.p:",a.p)
print("b.p:",b.p)

Both have similar function and in both p is equal to 4. This occurs in definition and not instantiation.

In definition of class B the value of p is calculated and is used later during instantiation. This means everything about these properties is created beforehand.

Ahmad
  • 8,811
  • 11
  • 76
  • 141