Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does a class' body get executed at definition time?

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?

like image 496
usual me Avatar asked Oct 04 '14 14:10

usual me


People also ask

What is the body of a class python?

A class body is an execution context just like any other, almost like a function body. It's just that at the end, all the local variables in that context become your class variables.

What happens when a class is called in Python?

In Python, the syntax for instantiating a new class instance is the same as the syntax for calling a function. There's no new needed: we just call the class. When we call a function, we get its return value. When we call a class, we get an “instance” of that class.


2 Answers

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.

like image 139
Martijn Pieters Avatar answered Oct 17 '22 04:10

Martijn Pieters


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.

like image 32
falsetru Avatar answered Oct 17 '22 03:10

falsetru