I wrote the following simple class as, effectively, a way to emulate a pointer in python:
"""Syntactic sugar for getter/setter pair
p = Parameter(getter, setter)
Set parameter value:
p.val = value
Retrieve parameter value:
def __init__(self, getter, setter):
Required positional parameters:
getter: called with no arguments, retrieves the parameter value.
setter: called with value, sets the parameter.
self._get = getter
self._set = setter
def __call__(self, val=None):
if val is not None:
def set(self, val):
def val(self, val):
Here’s an example of use (from a jupyter notebook page):
l1 = list(range(10))
def l1_5_getter(lst=l1, number=5):
def l1_5_setter(val, lst=l1, number=5):
lst[number] = val
Out = [5, None, [0, 1, 2, 3, 4, 12, 6, 7, 8, 9], 12]
p = Parameter(l1_5_getter, l1_5_setter)
p.val = 15
[12, 12, 12, 13, 13, None, 14]
15 [0, 1, 2, 3, 4, 15, 6, 7, 8, 9]
Of course, it is also easy to make this work for dict items or attributes of an object. There is even a way to do what the OP asked for, using globals():
def setter(val, dict=globals(), key='a'):
dict[key] = val
def getter(dict=globals(), key='a'):
pa = Parameter(getter, setter)
This will print out 2, followed by 3.
Messing with the global namespace in this way is kind of transparently a terrible idea, but it shows that it is possible (if inadvisable) to do what the OP asked for.
The example is, of course, fairly pointless. But I have found this class to be useful in the application for which I developed it: a mathematical model whose behavior is governed by numerous user-settable mathematical parameters, of diverse types (which, because they depend on command line arguments, are not known at compile time). And once access to something has been encapsulated in a Parameter object, all such objects can be manipulated in a uniform way.
Although it doesn’t look much like a C or C++ pointer, this is solving a problem that I would have solved with pointers if I were writing in C++.