Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Understanding Python variables - More in Depth #2

Open
mmcky opened this issue Feb 2, 2016 · 0 comments
Open

Understanding Python variables - More in Depth #2

mmcky opened this issue Feb 2, 2016 · 0 comments

Comments

@mmcky
Copy link
Owner

mmcky commented Feb 2, 2016

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/

mmcky added a commit that referenced this issue Feb 10, 2016
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant