0

I have sample code

a=10
print(recent_variable) -- it should print value of a

b=20
print(recent_variable) -- it should print value of b

c = [10,12]
print(recent_variable) -- it should print value of c

d= somfunc()
print(recent_variable) -- it should print value of d

any possible way of doing this

Intead of writing the python variable name in the print i can just put print(some syntax to show the recent variable) and it prints it value`

Santhosh
  • 9,965
  • 20
  • 103
  • 243
  • Yo may want to take a look to this answer, if you are working at an interactive shell or jupyter notebook you can use "_" if not you may try to implement the method at: https://stackoverflow.com/questions/19593108/how-to-get-the-value-of-the-last-assigned-variable-in-ipython – Richard Mar 07 '21 at 02:36
  • 1
    You can use `list(locals().values())[-1]` to get the most recently created variable, so long as you're using a version of Python where dictionaries stay in insertion order. Getting the most recently *assigned* variable would be impossible without something bordering on the occult. Not clear which you are looking for. – kaya3 Mar 07 '21 at 02:46

1 Answers1

0

If you had a very narrow use case in mind you could create your own memoized assignment function that keeps track of the last value assigned through it (see below). As a general solution, of course, that approach would not be appropriate.

Example:

import random

def memo_assign(value):
    if not getattr(memo_assign, "last_value", None):
        memo_assign.last_value = None
    memo_assign.last_value = value

    return value
        
a = memo_assign(10)
print(a, memo_assign.last_value)

b = memo_assign(20)
print(b, memo_assign.last_value)

c = memo_assign([10,12])
print(c, memo_assign.last_value)

d = memo_assign(random.randint(1, 100))
print(d, memo_assign.last_value)

Output:

10 10
20 20
[10, 12] [10, 12]
9 9
rhurwitz
  • 2,557
  • 2
  • 10
  • 18