Skip to content

Understanding Python variables - More in Depth #2

Description

@mmcky

Python has a pretty clever automatic memory manager (depending on who you ask) that takes responsibility for managing python's memory use by allocating and de-allocating memory that is used to store objects. The question was asked today if:

'a' == 'a'

is comparing two instances of the data that makes up the character a in memory or if this operation is comparing the same object (physically in memory) and the variable created points to the same information that makes up the letter a.

As it turns out - this is comparing a variable that points the same information in memory. For some simple immutable values python caches them to reduce expensive operations associated with the underlying memory allocation.

In [1]: id('a')
Out[1]: 140045168580400

In [2]: var = 'a'

In [3]: id(var)
Out[3]: 140045168580400

Therefore in this case python caches the object that makes up the letter 'a' and points variables to it in the memory heap managed by python. For more complex objects this isn't necessarily the case.

In [8]: id(2**64)
Out[8]: 140045087723392

In [9]: var = 2**64

In [11]: id(var)
Out[11]: 140045087720712

In [12]: 2**64
Out[12]: 18446744073709551616

In [13]: var
Out[13]: 18446744073709551616

While the values are the same, these objects do not share the same memory id.

Further Reading

http://foobarnbaz.com/2012/07/08/understanding-python-variables/

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions