1

Coming from an imperative programming background, it comes as a surprise that the assignment operator "=" makes two variable names point to the same place in memory rather than copying the value in memory from one unique object to another. This pattern shows up both in native data types, such as lists, but also classes defined with the 'class' keyword. I do, however, notice an exception to this rule:

a = 2
if id(a) == id(2):
    print "The id function returns the object's address in memory."
a = 3
if id(a) != id(2):
    print "The hardcoded integer '2' does not get its address in memory re-assigned to that of 3"

Both of these if conditions are met. It is necessary that they do, or else the construction of the natural numbers would break down. Is there any way that I can leverage this const-ness in classes that I define? I would like for some classes to be less like a "ln -s" and more like a "cp".

seewalker
  • 1,123
  • 10
  • 18
  • This is only true for integers between -5 and 256. See this question for a more detailed explanation: http://stackoverflow.com/questions/306313/python-is-operator-behaves-unexpectedly-with-integers – Blender Jun 30 '13 at 02:24
  • Does the copy module/protocol (http://docs.python.org/2/library/copy.html) provide what you want, or are you specifically interested in overriding assignment? If the latter, you can get something similar using the descriptor protocol (http://docs.python.org/2/howto/descriptor.html), but it is still not quite what you want. – jcrudy Jun 30 '13 at 02:29
  • The copy module does provide what I was looking for. Thank you very much. – seewalker Jun 30 '13 at 02:32
  • I believe there is no way to override assignment. – Elazar Jun 30 '13 at 10:35

1 Answers1

0

(This should be a comment, but is a bit long.)

Note that you seem to rely on the objects being integers in your example, but nothing depends on it, and integers are not special --- they are just regular objects. id(x) returns the identity of whatever object is currently stored in x. So if we adapt your example like this, we get the same results:

object2 = []    # or any object, really
object3 = []    # or any *other* object
a = object2
assert id(a) == id(object2)
a = object3
assert id(a) != id(object2)

The only special thing about integers is that if you write "2" several times in your source code, it might (and will actually) be optimized to refer to the same integer object, because it's never useful to get different integer objects with the same value.

Armin Rigo
  • 12,048
  • 37
  • 48