Nothing endures but change
Python3: Mutable, Immutable… everything is object!
Today we will talk about Python, about why everyone is an object.
It follows the principle of “First-Class Everything”. This concept centers around the idea of having every single item of data in python belonging to a class as an object with attributes and methods.
id and type
Each object has an id and a type, it is what identifies them.
It is a built-in function and is used by passing the object as an id(object) parameter to tell us what the id of an object.
Is a built-in function too, and is used to know what type a certain object is, its syntax is the same, we must pass the object as a parameter.
mutable and inmutable
Now that we know that all objects have an id and a type, it is time to know that there are mutable and immutable objects.
The mutable objects are those that can be modified and the immutable ones are all those that cannot be changed.
In order to save up memory space, python takes advantage of the immutability of some of its objects in order to reduce memory occupation in the system.
For example, in this case, “string” is a single object referred to by two different variables.
>>> text = "string"
>>> other_text = "string"
>>> id(text) 139774005161352 >>> id(other_text) 139774005161352
How objects are passed on to functions
Now that we know that we have mutable and immutable objects, the way we pass them on to functions is important.
The efficiency of memory is greatly affected when the right objects are used.
If a mutable object is called by reference in a function, it can change the original variable itself.
To avoid this, the original variable needs to be copied to another variable. Immovable objects can be called by reference because their value cannot be changed anyway.
Unlike other languages, in Python objects are always passed by reference. There is no classic variable concept like container of values.
In this way we can have two variables pointing to the same object and they will behave as an alias.
preasigned integer at start
To avoid allocating a new integer object each time a new integer object is needed, Python allocates a block of free unused integer objects in advance. PyIntObjects structure is used by Python. The array of 262 integer objects is initialized. They don’t have any values assigned to them — they are free integers that are ready to be called and used whenever needed. It speeds up the process, because you don’t need to create a new object when you need to use an integer, the value will simply be assigned to the next available object and no memory allocation will be necessary.
The value range of these integer objects is -5 to 257, and they are defined like that:
#define NSMALLPOSINTS 257
#define NSMALLNEGINTS 5
When you assign a value to a variable (variable passed to a function by assignment) it will check if the integer is in range of -5 to 257 and return the integer object pointed by the small integers at the offset.