Python 3: Mutable and Unmutable. Everything is object.
Ricardo Monta?a
Desarrollador Full Stack | Python | JavaScript | MySQL | HTML | CSS | Angular | ReactJS. Creación de soluciones innovadoras y escalables.
Introduction
If there is a very true sentence it is precisely this: "Everything in Python is an object". Let's define what an object is as a data abstraction.
In Python there are a variety of data types that are handled as objects, among which are strings, lists, functions and even modules are objects. When you create a variable and assign it an integer value, that value is an object; a function is an object; lists, tuples, dictionaries, sets, ... are objects; a string is an object.?
But why is object-oriented programming so important? Well, this type of programming introduces a new paradigm that allows us to encapsulate and isolate data and operations that can be performed on that data.
Particularly in Python, data types can be mutable or immutable, which means that if the value can change, the object is called mutable, while if the value cannot change, the object is called immutable.
id and type
The?id ()?function receives an object as an argument and returns another object that serves as the unique identifier for the first one. The returned value is an integer that indicates the memory address where the object is stored.
Sintax:?id (object)
>>> a1 = "Hello
>>> id(a1)
140461961446768
>>> num = 50
>>> id(num)
9802816
>>>
The?type ()?function returns the type of the object, based on the built-in module types, which defines the names for all known type symbols in the standard interpreter.
Sintax:?type (object)
>>> list_a = [2, 1, 8]
>>> type(list_a)
<class 'list'>
>>> a1 = "Hello"
>>> type(a1)
<class 'str'>
>>> type(50)
<class 'int'>
>>>?
Mutable objects
Mutable object values can be changed anytime, anywhere after creation.
Mutable types
1.Lists
2.Sets
3.Dictionaries.
4.Bytearray
Let’s see an example
>>> name = ['R','i','c','a','r','d','o']
>>> name
['R', 'i', 'c', 'a', 'r', 'd', 'o']
>>> name[1] = 'o'
>>> name
['R', 'o', 'c', 'a', 'r', 'd', 'o']
>>>?
In this example, we have assigned the characters ‘R’ ‘i’ ‘c’ ‘a’ ‘r’ ‘d’ ‘o’ to the list name.
Then we are trying to change the second letter in the list, which is done successfully.
This happens because we are trying to change the value of a mutable object, since the lists in Python are mutable.
bytearray() Syntax
The syntax of?bytearray()?method is:
bytearray([source[, encoding[, errors]]])
bytearray()?method returns a bytearray object (i.e. array of bytes) which is mutable (can be modified) sequence of integers in the range?0 <= x < 256.
If you want the immutable version, use the?bytes()?method.
Immutable objects
That a type is immutable means that it cannot be changed after it has been created.
Immutable types
1.Numbers (int, float, compex)
2. String
3. Tuples
4. Frozen Set
5. bytes
Let’s see an example
>>> name = "Ricardo"
>>> name
'Ricardo'
>>> name[1] = 'o'
Traceback (most recent call last):
?File "<stdin>", line 1, in <module>
TypeError: 'str' object does not support item assignment
>>> name
'Ricardo'
>>>?
In this example we have assigned the string?“Ricardo”?to the variable name. Then we are trying to change the second letter of the string, which gives us an error.
The error message is as follows: “?‘str’ object does not support item assignment?”
This happens because we are trying to change the value of an immutable object, since the strings in Python are immutable.
What we could do is assign a new value to the variable that would not be the same as changing the string
?>>> name = "Ricardo"
>>> name = name + " Monta?a"
>>> name
'Ricardo Monta?a'
>>>?
It seems that we are changing the string, but in reality what we are doing is assigning it a new value, since if you realize it, we are passing the = sign and the new value that we want that variable to have.
then immutability can be used to ensure that one object remains constant throughout the program
Why does it matter and how differently does Python treat mutable and immutable objects
Python handles mutable and immutable objects differently. Immutables are faster to access than mutable objects. Also, immutable objects are fundamentally expensive to “change”, because doing so involves creating a copy. Changing mutable objects is cheap.
Mutable objects are very good when you need to resize the object, i.e. it will be dynamically modified
How arguments are passed to functions and what does that imply for mutable and immutable objects
The value was only modified in the function block, outside the function it continues with its same value.
领英推荐
Python Mutable Function Arguments
If one of these parameters is changed inside the body of the function to point to another value, this change is not changed outside the function. If, on the other hand, the content of any of the mutable parameters is modified, this change is modified outside the function.
>>> def sum(a):
...???print(id(a))
...???a += [2]
...???print(id(a))
...?
>>> b = [4]
>>> print(id(b))
140461936958016
>>> sum(b)
140461936958016
140461936958016
>>> print(b)
[4, 2]
>>>?
Now that you know how Python handles data, it's time to program and put what you've learned into practice.
?
Python Immutable Function Arguments
Immutable objects in python like a number, a string or a tuple are passed as arguments in a function these are changed inside the function block, so it behaves like a copy of an object. A new duplicate local copy of the call object is created and manipulated within the scope of the function block. The calling object will remain unchanged. Therefore, the calling block will not notice any changes made within the scope of the function block to the immutable object.
>>> def sum(a):
...???print(id(a))
...???a += 1
...???print(id(a))
...?
>>> a = 3
>>> print(id(a))
9801312
>>> sum(a)
9801312
9801344
>>> print(a)
3
>>> print(id(a))
9801312
The value was only modified in the function block, outside the function it continues with its same value.
Difference between assignment and referencing
The difference between assignment and referencing is in the way of using the names of the variables to address them towards a certain object.
ASSIGNMENT.................................................... REFERENCING
Assignment:
>>> a = ['spam']
>>> b = ['spam']
>>> a is b
False
By assignment, each variable name is addressed to a different object, even though both objects have identical content. The is operator validates if both objects are the same, and the result obtained is obviously False.
Reference:
>>> c = ['spam']
>>> d = c
>>> c is d
True
By reference, one variable name is addressed to an object, while the other variable name is addressed to the first variable. The operator is valid if both objects are the same, and the result obtained for this case is True.
Python pre-allocates 262 integer numbers when cpython starts.
Since strings are immutable, integers appear to act the same way. To economize memory usage, CPython pre-allocates (or binds) the first 262 integers on start up. This means that numbers -5 - 256 (inclusive) are automatically bound to certain addresses in memory. That’s why a and b reference the same location in memory in the example above. Observe the following:
More technically, CPython has created macros called NSMALLPOSINTS and NSMALLNEGINTS. These macros refer to -5 and 256 respectively. CPython actually stores references to all of these integer objects in an array. When we “create” an integer in that range (Ex: a = 5), we're actually just telling our variable to point to an address stored in that array. The array is set to this particular scope because these are the most commonly used numbers. Once you ask for a number outside this range, CPython will be forced to start finding new memory locations where it can store numbers.
Mechanism of aliases
Since variables refer to objects, if we assign one variable to another, both variables refer to the same object:
>>> a = [1, 2, 3]
>>> b = a
>>> a is b
True
In this case, the state diagram looks like this:
Because the same list has two different names,?a?and?b, we say that it is?aliased. Changes made with one alias affect the other:
>>> b[0] = 5
>>> print a
[5, 2, 3]
Although this behavior can be useful, it is sometimes unexpected or undesirable. In general, it is safer to avoid aliasing when you are working with mutable objects. Of course, for immutable objects, there’s no problem. That’s why Python is free to alias strings when it sees an opportunity to economize.
nssmallpoints and nsmallnegints (why have thos values)
Easy, because they are most used integers!
And this answer is from StackOverflow but is clear and to the point: To better understand how NSMALLPOSINTS and NSMALLNEGINTS work:
It is actually an array of 262 integers (most commonly used). And this structure is basically used to access these integers fast. They get allocated right when you initialize your NSMALLPOSINTS and NSMALLNEGINTS.
#define NSMALLPOSINTS 257 (257 non inclusive)
#define NSMALLNEGINTS 5
?What Are Frozen Sets?
Frozen sets are a native data type in Python that have the qualities of sets - including class methods - but are immutable like tuples.
To use a frozen set, call the function frozenset () and pass an iterable as the argument.
scores = {1,2}
scores.add (3) # {1,2,3}
If you pass a set to the function, it will return the same set, which is now immutable.
scores = {1,2}
frozen_scores = frozenset (scores)
frozen_scores.add (3)
# AttributeError: 'frozenset' object has no attribute 'add'
If you pass another data type such as a list, tuple, or string, then it will be treated as an iterable.
This means the value will be deconstructed into its individual parts, which will be reduced to a set of unique values that is immutable.
myList = [1,1,2,3,4]
myString = "Hello"
frozenList = frozenset(myList)
frozenString = frozenset(myString)
print(frozenList)
# frozenset({1, 2, 3, 4})
print(frozenString)
# frozenset({'e', 'l', 'H', 'o'})
Why Use Frozen Sets?
Honestly, there isn’t much to gain in terms of performance when choosing to use frozen sets.
The primary reason to use them is to write more clear, functional code. By defining a variable as a frozen set, you’re telling future readers: do not modify this!
Unfortunately, frozen sets cannot be declared with a character notation like sets with curly braces, lists with square brackets, or tuples with parentheses.
If you want to use a frozen set you’ll have to use the function to construct it.
So thats its, and you know now, everything is an?AWESOME OBJECT.