Find previous value of a variable in Python

  • A+

This might be a really strange question but nevertheless,

Consider a variable called a. Let us now assign it a value as follows:

a = 1 

Let us now change the value of a now.

a = 3 

Is there any way in Python to know the previous value of a variable without storing it in another variable.Does python internally maintain a sort of a ledger of all the values of a variable during its lifetime that can be accessed ?


Answer: actually, we CAN

But not in general case.

You need some magick for this.

And magick is called "custom namespaces".

Whole idea is from Armin Ronacher presentation 5 years of Bad Ideas.

Magick: custom namespace with history of values

Let's create custom namespace that saves history of values.

For demonstration purposes let's change rule for __del__ - instead of deleting values we will insert None.

from collections import MutableMapping class HistoryNamespace(MutableMapping):     def __init__(self):         self.ns = {}             def __getitem__(self, key):         return self.ns[key][-1]  # Rule 1. We return last value in history      def __delitem__(self, key):         self.ns[key].append(None) # Rule 4. Instead of delete we will insert None in history     def __setitem__(self, key, value): # Rule 3. Instead of update we insert value in history         if key in self.ns:             self.ns[key].append(value)                     else:             self.ns[key] = list([value,]) # Rule 2. Instead of insert we create history list     def __len__(self):          return len(self.ns)     def __iter__(self):          return iter(self.ns)      history_locals = HistoryNamespace()         exec(''' foo=2 foo=3 del foo   foo=4 print(foo) ''', {}, history_locals) print("History of foo:", history_locals.ns['foo']) 


Custom namespaces is very powerful technique but almost never used.

The fact I find somewhat puzzling.


:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: