Identity Types and Values

21 Nov 2019

Everything in Python is an object. From an instance of a class to an attribute of that instance and even the class itself.

An Object has three basic properties that govern all of its behaviours. These are:

  • Identity
  • Type
  • Value

Identity

The identity of an object distinguishes it from other objects and will never change. You can get the identity of an object using the id() function.

>>> name = "John"
>>> id(name)
4375513072

You can also compare two variables and see if they have the same identity with the is operator.

>>> a = "a"
>>> b = "b"
>>> a is b
False
>>> a is a
True

It is important to point out that a variable is different to an object (in fact a variable is a reference to an object) so two different variables may resolve to the same identity and therefore the same object.

>>> a = "a"
>>> also_a = a
>>> a is also_a
True

In CPython, and object’s identity is its address in memory

Type

The type of an object determines what operations it supports and also what possible values it can hold. It can never change once an object is created.

You can find the type of an object using the type() function.

>>> type("a")
<class 'str'>
>>> type(1)
<class 'int'>
>>> type(True)
<class 'bool'>

Value

An object’s value may be represented differently depending on its type. For example, the value of a string is the sequence of characters it represents, whereas the value of a List can be the sequence of objects that it holds, as well as the composite value of each item in the List.

Whether or not an object’s value can change depends on the mutability of its type. Note that in some situations an immutable object’s value may change if it is a container holding mutable objects, but more on that next time.