Python: a snake that loves objects

According to webopedia it’s a self-contained entity that consists of both data and procedures to manipulate the data.

We can make the parallel with real-life objects.

For example, a coffee machine.

It has different materials which could represent the data (i.


coffee beans), and it has different functionalities which could represent the procedures to manipulate the data (i.


grinding the beans).

Variables, class instances, functions, methods, and many other things are object in Python.

Without further ado, let’s dive into the wonders of how the Python language treats everything as an object!id and typeFirst things first, every object in Python has an id, a type and a value.

The id of an object is its identity, its address in memory.

According to geeksforgeeks, this identity has to be unique and constant for this object during its lifetime.

In other words: when an object is created it gets an identity, or address in memory, and when the object is deleted it looses this identity.

For programmers that never dealt with low-level languages, this concept might be new, but everything in a computer is stored at one point or another in the memory of the machine.

The id of an object can be retrieved with function id().

Let’s take an example with an integer a of value 9.

>>> a = 9>>> id(a)10105344The id of the variable a is 10105344.

Of course, this will depend on your machine and where the variable is saved by the Python interpreter.

Now the type of an object is, well, its type.

To check the type of an object, we can pass it to the type() function.

Let’s look at our a variable:>>> type(a)<class 'int'>Here we can notice that the function doesn’t just return int, as expected, but class ‘int’.

Yes, in Python, there are no builtin data types like in C or other programming languages.

The types are actually classes, and each variable is an instance of the corresponding class.

So in our case, a is an instance of the int class.

Mutable objectsThere are two main types of objects in Python: mutable and immutableMutable objects in Python are objects that can be modified.

For example lists, sets and dictionaries are mutable.

Let’s see what it means.

>>> l1 = [1, 2, 3]>>> l2 = l1>>> l1.

append(4)>>> print(l2)[1, 2, 3, 4]So we created a first list of ints, l1, and then we assigned l1 to a new list l2.

We then appended an element to l1.

By now l1 should look like [1, 2, 3, 4].

But what about l2?.When we print it, we see that it has been updated too, even though we assigned l1 to l2 before modifying l1.

What we did in the second line is called aliasing.

We created an alias of l1 called l2, but both these names point to the same object.

We can verify this by using the id() function we mentioned earlier, or the is operator:>>> id(l1)140672713370824>>> id(l2)140672713370824>>> l1 is l2TrueBoth l1 and l2 have the same identity, so they’re pointing to the same object.

Note: the is operator is different from the == operator.

The former evaluates if two names point to the same object in memory and the latter evaluates if they have the same value.

If we wanted to make a copy of a list and be able to not modify the original one, we would need to clone it.

This can be done by using the slicing method:>>> l1 = [1, 2, 3]>>> l2 = l1[:]>>> l1.

append(4)>>> print(l2)[1, 2, 3]>>> id(l1)140672713370824>>> id(l2)140672692500488>>> l1 is l2FalseHere we can see that the cloning worked and l2 is now referencing to a different object than l1, as their ids are different.

Immutable objectsNumbers, strings and tuples are immutable objects in Python.

That means that they can’t be modified in place.

Let’s take an example with ints:>>> a = 89>>> b = a>>> a += 1>>> a90>>> b89We see now that if a equals b and we modify a, b will remain unmodified.

That’s the meaning of immutable.

How differently does Python treat mutable and immutable objectsWe’ve seen that you can’t modify immutable objects after assignation, but you can do it with mutable objects.

So what goes on under the hood?.If we take the example of our lists l1 and l2, what happens is that Python will actually reassign all the elements of the list to add a new element to it.

Memory-wise and time-wise, it’s definitely not so efficient.

Immutable objects, on the other hand, work quicker because there is not reassigning the whole object every time we try to modify it.

Python will just create a new object with the updated value.

How arguments are passed to functions and what does that imply for mutable and immutable objectsThe way Python stores variables in memory is actually quite interesting.

For people familiar with the C programming language, it works a little bit like pointers.

Variables in Python actually store the address (or the id) of the object they reference.

That being said, an argument is passed by reference to a function.

That means we don’t actually pass objects to functions, we pass references to them.

In general, a function works this way: it has a name and take arguments or don’t, executes a block of statements, and exits.

So when we pas arguments to it, depending on the mutability of the object referenced by this argument we will get different behaviors.

If we pass a mutable object to a function, and modify its value inside the function block, the new value of that object is accessible from outside the scope of the function.

Let’s illustrate:def foo(n): n.

append(5)l1 = [1, 2, 3]foo(l1)print(l1)Output:[1, 2, 3, 5]When we print l1 after passing it to our function foo() which appends a number to it, we see the updated list.

Now if we try that with an immutable object, the modification brought to the argument inside the function will not be accessible from outside its scope.

def foo(n): n += " there" print("The string inside the function is: {}".

format(n))s1 = "Hello"foo(s1)print("The string after the function is: {}".

format(s1))Output:The string inside the function is: Hello thereThe string after the function is: HelloWe can see that the string s1 has been modified inside the function, but still holds the old value outside of the scope of foo().

Other tricky object magic and exceptionsPreallocated range of intsWe said that strings are immutable and that two variables having the same value actually point to the same object.

Well, it’s not always the case, let’s see an example:>>> a = "HBTN">>> b = "HBTN">>> a is bTrue>>> a = "H B T N">>> b = "H B T N">>> a is bFalseWait, what?.In both cases a and b have identical values, so why aren’t they the same object in the second case?.That’s for a very simple reason.

When an instruction is run, there is already an allocated array of ints ranging from -5 (defined by the macro NSMALLNEGINTS in the source code of Python) and 257 (NSMALLPOSINTS).

The most used ints in Python are in that range, so the interpreter already allocates them at the start, and creating object in those ranges doesn’t require an actual creation of object.

That’s why all ints and characters (characters are just numbers) in that range are actually the same object and the condition a is b evaluates to True.

The ASCII value of the space character not being in that range, new objects are created for a and b and they don’t point to the same object.

Let’s see this with int values:>>> a = 1024>>> b = 1024>>> a is bFalseHere a and b have the same value, but they aren’t the same object since they’re not inside the array of ints provided by Python.

Fascinating, isn’t it?Difference between a += b and a = a + bWe could think that using the operation a += b and a = a + b are the same, from a programming standpoint.

But under the hood, they are very different operations.

The += sign is called a compound assignment operator.

It both assigns and operates on a variable, so it does what we call an in place addition.

Since everything is an object and stems from a class in Python, these operators are actually methods from the class of the data they are used on.

the += in turn calls the method __iadd__, and if it doesn’t work it will try to use __add__ instead.

This can lead to unexpected behavior that is implementation dependent.

The + operator only calls __add__.

In both cases, depending on the object they operate on, we can see both the creation of a new object or the modification of an existing object.

Tuple mutationRemember how we said tuples are immutable?.Well, it’s true, but if they contain mutable objects we can change the value of these objects.

Let’s take an example:# Modifying the first tuple will not affect the second>>> a = (9, 2)>>> b = a>>> a += (0,)>>> a(9, 2, 0)>>> b(9, 2)# Modifying the first tuple will modify the second>>> a = (9, [1, 2, 3])>>> a[1].

append(4)>>> a(9, [1, 2, 3, 4])>>> b = a>>> a is bTrue>>> a[1].

append(5)>>> b(9, [1, 2, 3, 4, 5])Tadaaa!.We successfully modified the tuple!.By modifying one of its mutable values, which was also updated in its alias.

We need to be careful though, we should always make sure that tuples put in sets and dictionaries only contain immutable types.

All this beautiful and fun intricacies in Python leave us thinking only one thing: Python is the top snek!SourcesWhat is Object-Oriented Programming?.Webopedia DefinitionA type of programming in which programmers define not only the data type of a data structure, but also the types of…www.


comid() function in Python – GeeksforGeeksIntroduction id() is an inbuilt function in Python.

Syntax: id(object) As we can see the function accepts a single…www.


orgPython | type() function – GeeksforGeekstype() method returns class type of the argument(object) passed as parameter.

type() function is mostly used for…www.


orgPython tuples: immutable but potentially changingPython tuples have a surprising trait: they are immutable, but their values may change.

This may happen when a tuple…radar.



4 Mutable DataOne powerful technique for creating modular programs is to incorporate data that may change state over time.

In this…composingprograms.


Lists – How to Think Like a Computer Scientist: Learning with Python 2nd Edition documentationA list is an ordered set of values, where each value is identified by an index.

The values that make up a list are…www.



Data model – Python 2.


16 documentationThese represent machine-level double precision floating point numbers.

You are at the mercy of the underlying machine…docs.


orgDeepHobbyingObjects of built-in types like (number, string & tuple etc.

) are immutable.

Objects of built-in types like (list, set &…www.


comPython Mutable and Immutable Function ArgumentsPython compiler handles function arguments slightly different than other popular programming languages like C, C++, and…learnandlearn.

comWhy does += behave unexpectedly on lists?The += operator in python seems to be operating unexpectedly on lists.

Can anyone tell me what is going on here?stackoverflow.

com.. More details

Leave a Reply