Types Are Dynamic (Advanced) in Python

To programmers who only program using Python, it would seem odd that a particular variable could have only one type and that it would have to be initially defined to have that type, but it is true. In Python, the type associated with a vari­able can change. For example, consider the statements:

x =     10              # X is an integer

x =     x*0.1           # X is floating point  now

x =     (x*10 == 10)    # X is Boolean

Some find this perfectly logical, and others find it confusing. As the variable is used according to its current type, all will be well.

Even simple Python types can be complex in terms of their implementation. A programmer rarely needs to know about the underlying details of types like integers. In many programming languages, an integer is simply a one- or two- word number, and the languages build operations like + from the instruction set of the computer. If, for example, a one-word integer A is added to another one B, it can be done using a single computer instruction like ADD A, B. This is very fast at execution time.

Python was designed to be convenient for the programmer, not fast. An in­teger is actually a complex object that has attributes and operations. This will become clearer as more Python examples are written and understood, but as a simple case, think about the way that C++ represents an integer. It is a 32-bit (4 byte) memory location, which is a fixed size space in memory. The largest num­ber that can be stored there is 232-1. Is that true in Python?

Here’s a program that will answer that question, although it uses more ad­vanced features:

for i in range (0,65):
print (i, 2**i)

Even an especially long integer is less than 65 bits. This program runs suc­cessfully and quickly. Integers in Python have an arbitrarily large size. Calculat­ing 264 * 264 is possible and results in 340282366920938463463374607431768211 456. This is very handy indeed from a programmer’s perspective.

The type of a variable can be determined by the programmer as the program executes. The function type () returns the type of its parameter as a string, and it can be printed or tested. So, the code

z = 1

print (type(z))

z = 1.0


will result in

<class ‘int’>

<class ‘float’>

If one needed to know if z was a float at a particular moment, then

if type(z)is float:

would do the trick. Type(z) does not return a string, it returns a type. The print () function recognizes that and prints a string, just as it does for True and False. So

if type(z) == “<class ‘float’>”:

would be incorrect.

In future chapters, this malleability of types will be further described, and practical methods for taking advantage of it in Python will be examined.


Source: Parker James R. (2021), Python: An Introduction to Programming, Mercury Learning and Information; Second edition.

Leave a Reply

Your email address will not be published. Required fields are marked *