[Tutor] How python keeps track of data types

Steven D'Aprano steve at pearwood.info
Mon Mar 28 18:32:51 EDT 2016


On Tue, Mar 29, 2016 at 01:01:57AM +0530, Abhishek Kumar wrote:
> Hello
> I am a computer science student,I want to know how python keeps track of
> data types of variables and is there a way to get data types of variables
> without actually running the script(with type() function). I think python
> AST can help, but am unable to figure out.Please help me.
> I've explored compiler library but could not find anything helpful.

Variables in Python do not have types like in C, Pascal or Haskell. 
Variables can take values of any type:

x = None
x = 42  # x is now an int
x = "Hello"  # now x is a str
x = [1, 2, 3]  # a list of ints
x = [1, None, "Hello", 2.5]  # list of mixed types
x = lambda arg: arg + 1   # and now a function

So Python doesn't track the type of variables at all, since variables do 
not have types. Only values have types:

None  # the special "None" singleton has type NoneType
42  # an int
"Hello"  # a string
2.5  # a float

and so forth.


How does Python track the type of values? In Python, all values are 
objects. Even strings, floats, ints and None. Objects are typically 
implemented as a C struct, with a pointer back to the class. So the 
interpreter can tell the type of the object by looking at the pointer to 
the class.

But that is not part of the Python language, that is part of the 
implementation. Different Python interpreters, and different versions, 
will work differently.

For example, Jython uses the Java Virtual Machine, so all objects in 
Jython are Java objects. Jython lets the JVM track the type of objects, 
using whatever method the JVM uses.

Likewise, IronPython uses the .Net Common Language Runtime, so all 
objects in IronPython are CLR objects. IronPython lets .Net (or Mono) 
track the type of objects.

The "reference implementation" of Python is the normal version of Python 
most people use, sometimes called CPython. Remember that other 
versions of Python may work differently inside the interpeter, but the 
language features should be the same. Python's data model is explained 
here:

https://docs.python.org/3/reference/datamodel.html

The CPython implementation is explained in part here:

https://docs.python.org/3/c-api/intro.html

but only the parts which are public and part of the C API. To really 
understand the inner workings, you must read the source code:

https://hg.python.org/cpython/

The way to determine the type of an object in Python is to call the 
type() function.




-- 
Steve


More information about the Tutor mailing list