Python3: Mutable, Immutable... everything is object!

Python3: Mutable, Immutable... everything is object!

  • introduction

In this post I am going to comment on aspects to take into account about objects in python.


I am taking the software fundamentals course at Holberton. And as such I must make this article about everything that has to do with objects, a topic in which we are currently.

  • id

The id() method returns a unique integer (identity) of a passed argument object.


a = 
b = 6
sum = a + b
# id of sum variable
print("The id of sum is", id(sum))
# Output: The id of sum is 97893125        

id() Syntax

The syntax of the id() method is:

id(object)
        

id() Parameter

The id() method takes a single parameter:

  • object - can be a class, variable, list, tuple, set, etc.

id() Return Value

The id() method returns:

  • the identity of the object (which is a unique integer for a given object)

Here, the id() method returns a unique integer number for every unique value it is used with.

In the above example, we have used the id() method with variables a, b and c and got their corresponding ids.

As you can see, the id() method returns the integer 140472391630016 for both a = 5 and 5.

Since both values are the same, the id is also the same.


  • type

The type() function either returns the type of the object or returns a new type object based on the arguments passed.

prime_numbers = [2, 3, 5, 7
# check type of prime_numbers
result = type(prime_numbers)
print(result)
# Output: <class 'list'>]        

type() Syntax

The type() function has two different forms:

# type with single paramete
type(object)


# type with 3 parameters
type(name, bases, dict)        

type() Parameters

The type() function either takes a single object parameter.

Or, it takes 3 parameters

name

  • - a class name; becomes the __name__ attribute
  • bases - a tuple that itemizes the base class; becomes the __bases__ attribute
  • dict - a dictionary which is the namespace containing definitions for the class body; becomes the __dict__ attribute

type() Return Value

The type() function returns

  • type of the object, if only one object parameter is passed
  • a new type, if 3 parameters passed


  • mutable objects

What is mutability?

In technical programming terms, a mutable object is an object whose state can be modified after it is defined. The opposite of a mutable object is an immutable object, whose state cannot be altered after it is initially defined.

Examples of immutable objects in Python include integers, floats, strings, and tuples. The two types of mutable objects you’ll likely deal with most often when programming in Python are lists and dictionaries.

Let’s look at a concrete example of the difference between mutability and immutability. Say I define a list of songs. If I want to change the list by replacing one of the songs, that’s perfectly fine, because lists are mutable:

>>> my_songs = ["All Too Well", "No Tears Left to Cry", "Cruel Summer"
>>> my_songs[1] = "Champagne Problems"
>>> my_songs
['All Too Well', 'Champagne Problems', 'Cruel Summer']]        

By contrast, suppose I define a string, which is an immutable object, but I accidentally misspell it. If I then try to modify the string, Python complains:

>>> my_song = "All Too Wall
>>> my_song[9] = 'e'
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'str' object does not support item assignment"        

Once the string has been defined, its contents cannot be changed. I will need to define a new string if I want to fix the spelling.

If you think about the functionality of lists and dictionaries, you’ll realize you’ve been taking advantage of their mutability all along, even if you may not have realized it. Functions such as append , extend , and update all modify the list or dictionary they refer to, and can be very useful for keeping track of data or accomplishing a certain programming task.

However, although mutable objects can be helpful in some cases, they can often lead to bugs if the programmer is unaware of how they work under the hood. In the next section, I explore a detailed example to explain what can go wrong if mutability is misunderstood.

Objects of built-in type that are mutable are:

  • Lists
  • Sets
  • Dictionaries
  • User-Defined Classes (It purely depends upon the user to define the characteristics)?

immutable objects

Definition:

Immutable is the when no change is possible over time. In Python, if the value of an object cannot be changed over time, then it is known as immutable. Once created, the value of these objects is permanent.

Objects of built-in type that are immutable are:

  • Numbers (Integer, Rational, Float, Decimal, Complex & Booleans)
  • Strings
  • Tuples
  • Frozen Sets
  • User-Defined Classes (It purely depends upon the user to define the characteristics)

How an immutable object is stored in memory?

Definition An immutable object is an object whose value cannot change. What does this mean behind the scenes, in computer memory??An object created and given a value is assigned some space in memory. The variable name bound to the object points to that place in memory.

why does it matter and how differently does Python treat mutable and immutable objects

Mutable is a fancy way of saying that the internal state of the object is changed/mutated. So, the simplest definition is: An?object?whose internal state can be changed is?mutable. On the other hand,?immutable?doesn’t allow any change in the object once it has been created.

Both of these states are integral to Python data structure.

how arguments are passed to functions and what does that imply for mutable and immutable objects

This call by reference can change between immutable and mutable objects implying the following:?Passing immutable arguments to a function would be passed by value, the object reference is passed to the function parameters and they can't be changed within the function, because they can't change at all.

difference between assignment and referencing

The first snippet creates?two?unique list objects, which are not the same. Hence?a is b?returns false because?a?and?b?are pointing to distinct objects:

          +------+
a ------> | list |
          +------+

          +------+
b ------> | list |
          +------+        

Your second snippet creates a single list object, and points both?c?and?d?to that objects, hence?c is d?return true:

          +------+
c ------> | list | <------ d
          +------+        

Note the following, from?https://docs.python.org/3/reference/datamodel.html:

Every object has an identity, a type and a value. An object’s?identity?never changes once it has been created; you may think of it as the object’s address in memory. The?is?operator compares the identity of two objects; the?id()?function returns an integer representing its identity.

So?is?and?==?are very different; while the former compares object identity, the latter compares object values. Indeed,?==?tests in your snippets would return true.

Given the explanation above, it may come as a surprise that that the story is slightly different with strings:

>>> a = 'str'
>>> b = 'str'
>>> 
>>> a is b
True        

This is due to?string interning, which occurs in CPython (i.e. it's implementation specific). Therefore, if the same string literal shows up in two different places, the same string object will be used for both (with restrictions).

This is explained in greater detail in?"Python string interning".

about integer pre-allocation? (262 first integers created when CPython starts)

Because CPython implementers have decided that it's a good default range for performance reasons, since it covers the most commonly used integer values. There is nothing magical in the range [-5,256]. The few negative numbers are probably included in the range of common error codes and negative list indexing, and the upper bound was simply set to a good round power of two.

explaining the mechanism of aliases

Since variables refer to objects, if we assign one variable (a) to another (b), both variables refer to the same object.

Since the same list has two different names, a and b, we say that it has an alias. Changes made with one alias affect the other.

Although this behavior can be useful, it is sometimes unexpected or unwanted. In general, it is safer to avoid creating aliases when working with mutable objects. Of course, for immutable objects, there is no problem. That's why Python is free to alias strings and integers when it sees an opportunity to economize.

What is NSMALLPOSINTS,?NSMALLNEGINTS?

Those values are used, because they are most used integers!

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 
#define NSMALLNEGINTS         

explain the special case of Tuple and Frozen Set

tuples are immutable lists , frozensets are immutable sets?. frozensets aren't indexed, but you have the functionality of sets - O(1) element lookups, and functionality such as unions and intersections. They also can't contain duplicates, like their mutable counterparts.

要查看或添加评论,请登录

Gustavo Daniel Ponce Marsiglia的更多文章

  • Qué esperar de la nueva Scout en 2026?

    Qué esperar de la nueva Scout en 2026?

    artículo en desarrollo ..

  • ls command

    ls command

    ls In computing, ls is a command for listing computer files and directories on Unix and Unix-like operating systems. It…

    1 条评论

社区洞察

其他会员也浏览了