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

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

Introduction:

In this topic we will be talking about Python's mutable/immutable objects, How to figure out mutable and immutable objects and how exactly Python treats them.

Every variable in python holds an instance of an object. There are two types of objects in python i.e. Mutable and Immutable objects. Whenever an object is instantiated, it is assigned a unique object id. The type of the object is defined at the runtime and it can’t be changed afterwards. However, it’s state can be changed if it is a mutable object.

1-id and type:

  • id():

Id is a built-in function in Python, It return the “identity” of an object. This is an integer which is guaranteed to be unique and constant for this object during its lifetime. Two objects with non-overlapping lifetimes may have the same id() value.

for example:

class Foo:

    b = 5

dummyFoo = Foo()
print('id of dummyFoo =',id(dummyFoo))

Output:

id of dummyFoo = 140343867415240

  • type():

With one argument, return the type of an object. The return value is a type object and generally the same object as returned by object.__class__.

The isinstance() built-in function is recommended for testing the type of an object, because it takes sub-classes into account.

With three arguments, return a new type object. This is essentially a dynamic form of the class statement. The name string is the class name and becomes the __name__ attribute; the bases tuple itemizes the base classes and becomes the __bases__ attribute; and the dict dictionary is the namespace containing definitions for class body and is copied to a standard dictionary to become the __dict__ attribute. For example, the following two statements create identical type objects:

>>>    class X:

...    a = 1
...

>>>    X = type('X', (object,), dict(a=1))

2-mutable objects:

A mutable object is an object whose value can change once created. Mutable objects are often objects that can store a collection of data. Lists (Python type list) and dictionaries (Python type dict) are examples of mutable objects. for example:

>>> l = [1, 2, 3]

>>> m = l

>>> l[0] = 'x'

>>> m

['x', 2, 3]

This basically means that you can change their content without changing their identity.

3-immutable objects:

Basically Immutable objects are of in-built types like int, float, bool, string, unicode, tuple. In simple words, an immutable object can’t be changed after it is created. For example:

>>> a = 1
>>> b = a
>>> a = 2
>>> b
1
>>> 


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

Mutable and immutable objects are handled differently in python. Immutable objects are quicker to access and are expensive to change because it involves the creation of a copy. Whereas mutable objects are easy to change.

To summarize Immutable objects can be hashable, mutable objects can’t be hashable.This is important to know, because (for reasons beyond the scope of this post) only hashable objects can be used as keys in a dictionary or as items in a set. Since hashes are based on values and only immutable objects can be hashable, this means that hashes will never change during the object’s lifetime.

As a rule of thumb, Generally Primitive-like types are probably immutable and Customized Container-like types are mostly mutable.

No alt text provided for this image


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

First, you need to understand how Python stores variables before we go further. This will help you to understand the behavior of Python mutable and immutable function arguments. In Python, almost everything is an object. Numbers, strings, functions, classes, modules and even Python compiled code, all are objects.

Python treats all variables as references to the object. This means all variables store the memory address of the actual object. This concept is much like “Pointer” in C and C++ programming language. This means the address of the actual object is stored in the Python named variable, not the value itself.

Hence, immutable and mutable objects or variables are handled differently while working with function arguments.

In the following diagram, variables a, b and name point to their memory locations where the actual value of the object is stored.

No alt text provided for this image

6-In Python, what is the purpose of __slots__ and what are the cases one should avoid this?

The special attribute __slots__ allows you to explicitly state which instance attributes you expect your object instances to have, with the expected results:

  1. faster attribute access.
  2. space savings in memory.

The space savings is from

  1. Storing value references in slots instead of __dict__.
  2. Denying __dict__ and __weakref__ creation if parent classes deny them and you declare __slots__.

The creator of Python, Guido van Rossum, states that he actually created __slots__ for faster attribute access.

Here's a class with no class or object attribute, that prevents the user from dynamically creating new instance attributes, except if the new instance attribute is called first_name:

class LockedClass:
    
  __slots__ = ("first_name")
  

7-A glimpse NSMALLPOSINTS, NSMALLNEGINTS:

These two macros are 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.

No alt text provided for this image


Conclusion:

To conclude this EVERYTHING IN PYTHON IS AN OBJECT and you should glimpse the effect of using mutable and immutable types, you should try to mess around with the interpreter to further get the idea and how they actually work.

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

Iheb Chatti的更多文章

社区洞察

其他会员也浏览了