Open In App

Why do we Need Immutables in Python ?

Last Updated : 10 Jul, 2020
Improve
Improve
Like Article
Like
Save
Share
Report

When a Novice steps into the Programming world and kicks off to learn about different concepts of it and yet eventually reaching to the Data Structures and Algorithms, learning and implementing them, but one or the other way he/she tends to read once and forget about the Immutable object.

Mutable and Immutables exists in every programming language, yet one only tends to care about the mutable, like lists, queues, etc and take no or little notice of the immutables because at first impression it seems to be just an add-on and doesn’t seem to have any real-life problem-solving applications, and to debunk this idea, let us discuss the concept, need of it and Limitations.

What are Immutable Objects?

Mutability is a differentiating property of a data types in Python that makes a big contrast from the other data types, It tends to be an ability of data types to allow being modified after it is created, to which a value can be added as well as can be popped out of it. On the other hand, looking on the other side there are objects too that don’t follow this principle and are unalterable and don’t allow any modification to it after it’s defined. Its State cannot be changed whatsoever, It tends to represent a constant value once initialized. Examples – integer, complex, string, float, Tuple, Complex, Frozen set.

Therefore if any variable has initialized a value corresponding to any of these immutable data types, one cannot change it ever. To ever change it, one has to initialize the same variable to the modification one wants. When a variable is reassigned to some other string it tends to allot a different memory location for both the objects.

Example:

Python3




# string initialized
var = 'Geeks'
print(id(var))
print(var)
  
# Reassigned to another value
var = 'For Geeks'
  
# New Memory Location assigned
print(id(var))
print(var)


Output:

139758810541392
Geeks
139758782345520
For Geeks

Note: In Python there tends to be an exception in case of tuple’s immutability as the tuples themselves is an immutable yet cannot be modified after it’s initialized and the values it is given at the time of initialization be the final values it holds, nothing can add or delete value to/from it, However, a mutable field like a List embedded in a tuple can be modified without any error, and yet it proves that objects referenced by the tuple can be modified, this phenomenon is occasionally called “non-transitive immutability”.

In Python, coders have more advantage of optimization around the property of immutability, mainly for the string objects.

Example:

Python3




var1 = 'GFG' 
var2 = 'GFG'
var3 = 'GFG'
var4 = 'GFG'
var5 = 'GFG'
  
# All the variables points to a
# single String
print(id(var1), id(var2), id(var3),
      id(var4), id(var5))


Output:

140080377558384 140080377558384 140080377558384 140080377558384 140080377558384

If one tends to create 20 string objects one after the other, holding up same values, Then Python won’t be allocating different memory locations for each value, yet it’ll make every identifier to refer to the same string as it will not ever be modified further, Thus Saving lots of memory. The exception being that the same scenario won’t be applicable for every immutable object other than a string, yet this optimization trick proves to be Implementation Dependent.

Why care about Immutables ?

  1. Improves the Exactness and simplicity of the whole code, as it provides an ease to the coder to pass around the object in the program without any fear as it never seems to be ever modified. whereas the mutable is much harder to reason about. In mutable, the aliasing leads to many irregularities and eventually intimidating fidelity of the code, At the end resulting in variability.
  2. Thread Safe – As an object after the assignment cannot be modified, this deduces that a read-only data is being shared among the threads, which certainly provides thread-safety. In simpler words, In immutables, since there is no scope of change for an object, there is no need to be scared of accessing it from many threads. Mutation in any sense in immutable objects can be achieved in such a way that one creates a new object instead of trying to modify existing ones.

Limitations

Over time, different conclusions get introduced with it, as we read that Immutables is Thread safe, and no matter which thread reads their values, They get the right values, but The immutables are found to be immune to “Memory Consistency Errors”, that can be furthermore explained as; Immutable objects by themselves are not thread-safe. It is the code that uses them that must be written to be thread-safe. Simply using immutable objects is not enough to achieve this. One has to also guard against deadlock, livelock, and starvation.



Similar Reads

8 Reasons Why Do We Need IDE
Whether you are a newbie or an experienced programmer, an IDE offers a range of features and functionalities that simplify the software program development technique. In this article, we can discover why IDEs are essential equipment for modern-day software program development. Let's look around "What is IDE (Integrated Development Environment)" and
4 min read
Is Python Case-Sensitive? Yes, Here's What You Need to Know
Yes, Python differentiates between uppercase and lowercase characters, making it a case-sensitive programming language. This distinction means that Python treats identifiers such as variable, Variable, and VARIABLE as entirely separate entities. Understanding this case sensitivity is crucial for anyone working with Python, as it influences how vari
2 min read
Why we write #!/usr/bin/env python on the first line of a Python script?
The shebang line or hashbang line is recognized as the line #!/usr/bin/env python. This helps to point out the location of the interpreter intended for executing a script, especially in Unix-like operating systems. For example, Linux and macOS are Unix-like operating systems whose executable files normally start with a shebang followed by a path to
2 min read
Why is python best suited for Competitive Coding?
When it comes to Product Based Companies, they need good coders and one needs to clear the Competitive Coding round in order to reach the interview rounds. Competitive coding is one such platform that will test your mental ability and speed at the same time. Who should read this? Any programmer who still hasn't tried python for Competitive Coding M
7 min read
Why Python is called Dynamically Typed?
Python variable assignment is different from some of the popular languages like c, c++ and java. There is no declaration of a variable, just an assignment statement. Let us see why? When we declare a variable in C or alike languages, this sets aside an area of memory for holding values allowed by the data type of the variable. The memory allocated
2 min read
Why import star in Python is a bad idea
Using import * in python programs is considered a bad habit because this way you are polluting your namespace, the import * statement imports all the functions and classes into your own namespace, which may clash with the functions you define or functions of other libraries that you import. Also it becomes very difficult at some times to say from w
3 min read
Why do people prefer Selenium with Python?
Selenium is a strong set of tools that firmly supports the quick development of test automation of web applications. It offers a set of testing functions that are specially designed to the requirements of testing of a web application. These functions are reliable facilitating various options for positioning UI elements and making a comparison of th
3 min read
Why Python Is Used For Developing Automated Trading Strategy?
Python is a high-level programming language that is more deployed in machine learning and for automation of trading systems. Python has got exclusive library functions that facilitate ease of coding the algorithmic trading strategies. This article is all about why python programming language is preferred in developing a customized automated trading
5 min read
Why is Numpy faster in Python?
NumPy is a Python fundamental package used for efficient manipulations and operations on High-level mathematical functions, Multi-dimensional arrays, Linear algebra, Fourier Transformations, Random Number Capabilities, etc. It provides tools for integrating C, C++, and Fortran code in Python. NumPy is mostly used in Python for scientific computing.
4 min read
10 Reasons Why You Should Choose Python For Big Data
Big Data is the most valuable commodity in present times! The data generated by companies and people is growing so much that the data generated would reach 175 zettabytes in 2025 whereas it is around 50 zettabytes currently. And Python is the best programming language to manage this Big Data because of its capacity for statistical analysis and its
8 min read
Article Tags :
Practice Tags :