Python equivalent of pointers

13,056

Solution 1

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

Solution 2

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]

Solution 3

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.

Share:
13,056
random guy
Author by

random guy

Updated on June 15, 2022

Comments

  • random guy
    random guy over 1 year

    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)

  • Samuel
    Samuel almost 9 years
    Not a graceful solution, but better than the others and simple. Weird this is not just part of the language in my opinion. I could write an easier to read answer in C than I could in Python for this case.