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 ?
Use enumerate() to access previous and next values in a list. Loop over enumerate(list) in a for loop with the syntax for index, elem in enumerate(list) . To access the next element in list , use list[index+1] and to access the previous element use list[index-1] .
Answer: When a new value is stored in a variable then its previous value gets overwritten. Explanation: A variable is basically a container which represents a memory location.
Some values in python can be modified, and some cannot. This does not ever mean that we can't change the value of a variable – but if a variable contains a value of an immutable type, we can only assign it a new value. We cannot alter the existing value in any way.
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.
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'])
Rejoice!
Custom namespaces is very powerful technique but almost never used.
The fact I find somewhat puzzling.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With