Everything Is Object!

Everything Is Object!

During this module of my Python learning journey, I learned about how Python3 handles mutable and immutable objects and how they can be leveraged to save memory. Immutable objects cannot be changed after declaration to assure safety and improve optimization. Mutable objects can be used to create customized objects which can change over time. Interning is used by Python to save memory. 

The id() function can be used to find the memory address of the input variable. I used id() to prove when interning is being used, which is when Python saves memory by using the same memory address for two variables which are assigned the same value. This code snippet should return the same memory address for each print statement. 

>>> str1 = “hello”

>>> str2 = “hello”

>>> print(“ID of str1: {}”.format(id(str1)))

>>> print(“ID of str2: {}”.format(id(str2)))

1649755297543922

1649755297543922

However this code snippet should prove that string concatenation creates a new string object with a different memory address.

>>> str2 += “ world”

>>> print(“ID of str1: {}”.format(id(str1)))

>>> print(“ID of str2: {}”.format(id(str2)))

1649755297543922

8825432976596324

Strings, ints from -5 to 256, and user defined objects can use interning. The type() function can be used to return the type of the input variable. This can be useful for determining an object's type for use in conditional logic and error handling. With integers specifically this is called integer pre allocation. Two macros are used NSMALLPOSINTS and NSMALLNEGINTS which define the -5 to 256 range of ints which are most commonly used and are pre allocated during initialization. If an integer is within that range it returns a reference to the existing allocated object defined by the macros.

Mutable objects in Python are objects which value or values can be changed after being created or declared. The contents of the object can be modified without creating a new object. Lists are a mutable object type which includes an ordered sequence of elements called items. Items can be added, removed or updated.

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

>>> string_list = [“apple”, “orange”, “grape”]

>>> mixed_list = [1, “orange”, True]

Sets are a similar mutable object type but cannot include duplicate values.

>>> integer_set = {1, 2, 3}

Dictionaries are another mutable object type which includes unordered key-value pairs, which can be added, removed or updated

>>> name_age_dict = {“Harry”: 18, “Tom”: 32, “Jenny”: 23}

Byte Arrays are a mutable ordered sequence of bytes which is useful for working with binary data.

>>> bytes = bytearray([89, 22, 46])

Immutable objects are objects which value or values cannot be changed after being created. Once created an immutable object cannot be modified for security reasons. Integers, Floating-Point Numbers, Strings, complexes, frozen sets, bytes and Tuples are immutable object types in Python. If an attempt to change one of these objects is made, an error will be raised.

>>> str = “hello”

>>> s[0] = “H”

TypeError: ‘str’ object does not support item assignment

Tuples and Frozen sets are special because they themselves are immutable but they can contain mutable objects. For example a Tuple can contain a mutable list

>>> a = []

>>> b, c = (a, ), (a, )

>>> b[0].append(1)

>>> b

>>> c

([1],)

([1],)

Python treats mutable and immutable objects differently for behavior and performance reasons. Mutable objects can provide in-place value modifications which can produce unexpected effects. Immutable objects,  because of their static nature, provide predictable behavior. Immutable objects are also more memory efficient and use interning to save memory space reusing memory addresses. For example when a list is created a reference is assigned to that address in memory.

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

When interning is used for two ints with the same value, or when assigning one variable to another both variables reference the same object. This is also called Aliasing.

>>> a = 1

>>> b = a

In Python, functions are passed arguments with object reference or pass by assignment. For immutable objects, any attempt to modify the value in the function will instead create a new object instead of changing the original value. Outside of the function, the original object will be unchanged. 

>>> def mod_immuteable(x):

>>> x +=  1

>>> print(“Inside: {}”.format(x))

>>> int_a = 1

>>> mod_immutable(int_a)

>>> print(“Outside: {}”.format(int_a))

Inside 2

Outside 1

For mutable objects, objects passed can be changed directly, modifying the original object passed.  

>>> def mod_mutable(list):

>>> list.append(4)

>>> print(“Inside: {}”.format(list))

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

>>> mod_mutable(l)

>>> print(“Outside: {}”.format(l))

Inside: [1, 2, 3, 4]

Outside: [1, 2, 3, 4]

To view or add a comment, sign in

More articles by Tanner Saint

  • Postman: Making API Testing Simple (and Fun)

    Every full stack developer has had to write at least one curl command in their career, and I know the pain. Tell me if…

  • Hack Sprint Retrospective

    My group and I have just finished our Hack Sprint project for the end of T2 at Atlas School! This project was the first…

    5 Comments

Explore content categories