How did python implement Type free variables from a statically typed language

Python is in no way "type free" (see "Is Python strongly typed?"). All Python objects have a specific type that determines many of their properties and behaviors. For those that are represented as literals, that type is determined by their lexical form. For other objects, it is determined by how they were computed.

What Python does not have is type declarations or any other built-in form of limiting or predetermining the type of objects that a variable or aggregate may contain. Thus it does not make sense to talk about the type of a variable, such as your x, but only about the type of the value that it contains. And that is what the type() function (for example) computes. So when you ask

how does python work under the hood(in terms of its implementation in C) when it comes to determining what type of variable it is

the answer is in one sense simple: Python doesn't do that at all. Variables don't have types -- only their values do. When you call, say, type(x), you are not determining the type of the variable, but rather the type of its current value.

And Python supports that by ensuring that every Python object, such as one represented by the literal 5, contains rather a lot of data. Significantly, it contains information about the object's value and type, but it also contains various other details as well, such as a reference count and much more. The details are much too broad for an SO answer, but you can find a lot of them in the Python / C API Reference Manual. For the deepest and most intimate secrets, you would want to study the cpython headers and source.


This is a huge subject.

The below document will give you more understanding.

https://intopythoncom.files.wordpress.com/2017/04/internalsofcpython3-6-1.pdf

Like you said a simple example for integer types

To hold an integer type object, there is structure defined in C as said below

typedef struct {
PyObject_HEAD
long ob_ival;
} PyIntObject;

The object of C structure PyIntObject (section 7.5 of above said document) holds the objects which are integer type.

If you are more interested, setup the environment and debug as said in same section 7.5 of the above document.

Objects/intobject.c and place a debug point on line number 89. Start debugging the application.

PyTypeObject is at higher level for the types to be represented. (look section 7.3 of above said document)

As a programmer, it is curious aspect to know the internals. But do not spend too much time to understand unless you work at interpreter level.

Tags:

Python

C