Skip to content

python: private variables via closure

Anthony Sottile edited this page Jan 23, 2019 · 1 revision
def OneTruePrivate():
    """hax which uses a closure to make _truly_ private variables"""
    x = 1

    class OneTruePrivate:
        @property
        def val(self):
            return x

        def increment(self):
            nonlocal x
            x += 1

    return OneTruePrivate()


var = OneTruePrivate()
print('initial value')
print(var.val)
var.increment()
print('after incremnet')
print(var.val)
print('look ma, no object state!')
import pprint; pprint.pprint(vars(var))

print('ok fine, you can do terrible things')
cell = var.increment.__func__.__closure__[0]
import ctypes
ctypes.pythonapi.PyCell_Set.argtypes = (ctypes.py_object, ctypes.py_object)
ctypes.pythonapi.PyCell_Set(cell, 9001)
print(var.val)

OUTPUT = '''\
$ python3 t.py
initial value
1
after incremnet
2
look ma, no object state!
{}
ok fine, you can do terrible things
9001
'''
Clone this wiki locally