Python3: Everything is object!

Etienne Brun
3 min readMay 26, 2021

--

Python is a popular programming language.

Everybody likes python, because it is quite simple to learn, easy to read and very powerful.

It is important to understand its specificities and this is what i’m going to talk about.

Object introduction

Python is an object oriented language. In python, everything is an object: a module, a function, a variable… An object is an instance of a class. And every object has its own data type and internal state (data).

For exemple when Python executes:

This create an integer object at memory location 0x111 for exemple. a doesn’t contain value 1000 but just holds the reference (memory address) to this object. If i run:

it will create another integer object with the memory address of 0x222 .

And if i run:

b take the reference of the object integer.

Id and type

id() and type() are two built-in functions. They give information about a variable. The type function will return the data type of the object, wich most of the time is the class.

The id function will return the variable identifier of the variable. All variables in Python refer to an object and the variable identifier is an integer number that refers to a specific object. In the CPython implementation, this number is the memory address of the object. The id will be used if we want to know if the variables point on the same object.

We are going to see that some types of data are mutable, they don’t change their id when we make modifications and others are immutable, they have no choice but to create a new object.

Mutable objects

Mutability is the ability to mutate an object. Mutable types in Python include lists, sets, dicts, and bytearrays.

Let’s take an exemple with the list:

Lists are mutable

id(m) and id(l) is the same here.

But if we do : id(m[0]) is id(l[0]), Python interpreter will return False. Because integers and strings are not mutable.

Immutable objects

This means that you cannot change/move the contents of the object. Some built-in immutable types include numbers(ints, floats, complexes), strings, tuples frozen sets and bytes.

Since Python must create a separate object for each unique immutable value (which takes up a lot of memory) the interpreter cleverly optimizes its creation of objects. It does so by using the same reference number for objects that cannot change, such as strings:

How arguments are passed to functions

Python passes the reference to the object. It means that the function’s argument is aliased to the object reference by the variable passed to the function. So if a reassignment occurs inside of the function, it will not alter the original variable passed to the function.

--

--