1. Python is Dynamically Typed rather than Statically Typed.¶

What this means is that at the time the program executes, the interpreter doesn't know the type of the variables that are defined. The difference between a C variable (I'm using C as a stand-in for compiled languages) and a Python variable is summarized by this diagram:

For a variable in C, the compiler knows the type by its very definition. For a variable in Python, all you know at the time the program executes is that it's some sort of Python object.

So if you write the following in C:

/* C code */ int a = 1 ; int b = 2 ; int c = a + b ;

the C compiler knows from the start that a and b are integers: they simply can't be anything else! With this knowledge, it can call the routine which adds two integers, returning another integer which is just a simple value in memory. As a rough schematic, the sequence of events looks like this:

C Addition¶

Assign <int> 1 to a Assign <int> 2 to b call binary_add<int, int>(a, b) Assign the result to c

The equivalent code in Python looks like this:

# python code a = 1 b = 2 c = a + b

here the interpreter knows only that 1 and 2 are objects, but not what type of object they are. So the interpreter must inspect PyObject_HEAD for each variable to find the type information, and then call the appropriate summation routine for the two types. Finally it must create and initialize a new Python object to hold the return value. The sequence of events looks roughly like this:

Python Addition¶

Assign 1 to a 1a. Set a->PyObject_HEAD->typecode to integer

Set to integer 1b. Set a->val = 1 Assign 2 to b 2a. Set b->PyObject_HEAD->typecode to integer

Set to integer 2b. Set b->val = 2 call binary_add(a, b) 3a. find typecode in a->PyObject_HEAD

find typecode in 3b. a is an integer; value is a->val

is an integer; value is 3c. find typecode in b->PyObject_HEAD

find typecode in 3d. b is an integer; value is b->val

is an integer; value is 3e. call binary_add<int, int>(a->val, b->val)

call 3f. result of this is result , and is an integer. Create a Python object c 4a. set c->PyObject_HEAD->typecode to integer

set to integer 4b. set c->val to result

The dynamic typing means that there are a lot more steps involved with any operation. This is a primary reason that Python is slow compared to C for operations on numerical data.