views:

233

answers:

5

in python everything works by reference:

>>> a = 1
>>> d = {'a':a}
>>> d['a']
1
>>> a = 2
>>> d['a']
1

i want something like this

>>> a = 1
>>> d = {'a':magical pointer to a}
>>> d['a']
1
>>> a = 2
>>> d['a']
2

what would you substitute for 'magical pointer to a' so that python would output what i want

i would appreciate general solutions (not just for the above dictionary example with independent variables, but something that would work for other collections and class/instance variables)

+2  A: 

What about a mutable data structure?

>>> a = mutable_structure(1)
>>> d = {'a':a}
>>> d['a']
1
>>> a.setValue(2)
>>> d['a']
2

An implementation might look like

class mutable_structure:
  def __init__(self, val):
    self.val = val

  def __repr__(self):
    return self.val
danben
+1  A: 

See this question:

http://stackoverflow.com/questions/1145722/simulating-pointers-in-python

Ben Gartner
i wish there was something cleaner and shorter though
random guy
It's a terrible thing to do -- create aliases for a variable -- so it's updated spontaneously by reference to something else. Sadly, it's merely difficult, not impossible.
S.Lott
A: 

This is because 1 is a immutable datatype in python, i.e. you can't change the value of it.

To make it work like a pointer, you need a mutable datatype as storage, which you can do yourself with a class definition

class Mutable(object):
    pass

a = Mutable()
a.value = 1

d = {'a':a}
a.value = 3

d['a'].value equals 3 at this point.

If you really want, you can overload operators etc. so that you get the same semantics as for normal integers, but I'd suggest you instead take a look at some functional programming patterns to see why immutable types are nice.

Joakim Lundborg
A: 

The standard solution is to just use a list; it's the easiest mutable structure.

a = [1]
d = {'a': a}
a[0] = 2
print d['a'][0]
Johann Hibschman
A: 

If you're working in a class you could do something like this:

class DRefsA(object):
    a = 4

    @property
    def d(self):
        return self.a

    @d.setter
    def d(self, value):
        self.a = value
jcdyer