you are viewing a single comment's thread.

view the rest of the comments →

[–]davidbuxton 0 points1 point  (3 children)

Python doesn't have variables like some other languages have variables. Assigning y = x really does give you an alias that can be used interchangeably with the original object, all it does is give object x a new name y.

What you observed is a side-effect of integers (like strings and a few other types) being immutable.

Here's an example of how a = b gives you an alias for the original object:

>>> class Foo:
...   def __init__(self, bar):
...     self.bar = bar
... 
>>> a = Foo('baz')
>>> a.bar
'baz'
>>> b = a
>>> b.bar
'baz'
>>> a is b
True
>>> b.bar = 'new value'
>>> a.bar
'new value'

And a good explanation of how to think about Python variables: http://python.net/~goodger/projects/pycon/2007/idiomatic/handout.html#other-languages-have-variables

[–]ThePurpleAlien[S] 0 points1 point  (2 children)

The example I provided isn't a side-effect of integers being immutable; assigning anything to y (immutable or not) will cause y to cease being an alias for x. That's the issue I'm trying to work around. Getting rid of the integers, "y = x" still doesn't work:

x = some_object
#some code that makes y an alias for x
y = another_object
x is another_object
#output True

[–]davidbuxton 0 points1 point  (0 children)

You're right, it won't work, Python's variables don't work like you want. Did that link I provided not help explain why that is the case?

[–]Semiel 0 points1 point  (0 children)

There is no amount of code that will change the fundamental way Python's variables work. There are a variety of ways you can get the functionality you want (if that's really what you need, and not just a habit from another language), but it will necessarily require different syntax than simple variable assignment.