0

How to pass a variable for an f-string '=' debugging operator?

from datetime import datetime


def print_var(var):

    print(str(datetime.now())[:19], end=' ')
    print(f'{var = }')


test = 5
print_var(test)

I expect print_var(test) to print the variable name from outside the function, ie.

test = 5

Please refer to Python: Print a variable's name and value? for the context of the question.

OneArb
  • 453
  • 2
  • 14
  • 3
    The name isn't a property of the value. What would you expect for `print_var(some_list[index])`? `print_var(5)`? – jonrsharpe Oct 06 '21 at 09:03
  • are you expecting that variable name gets printed on the screen ? – Kunal Sharma Oct 06 '21 at 09:17
  • @KunalSharma yes, I expect `print_var(test)` to print `test = 5` in the terminal window. – OneArb Oct 06 '21 at 09:40
  • @jonrsharpe I should perhaps reformulate the question in the context of Python 3.8 f-string = syntax? https://stackoverflow.com/questions/32000934/python-print-a-variables-name-and-value/57225950#57225950 – OneArb Oct 06 '21 at 09:44
  • 2
    I'm familiar with the syntax, the problem is your expectation that it _wouldn't_ be the "local name", `var`. There are a bunch of possible dupes around getting the "outer name" (`test`, in this case), but all boil down to the same problem: the value might have been referred to by zero, one or many names, and none of them is a property of the value. Here's a good intro: https://nedbatchelder.com/text/names.html. – jonrsharpe Oct 06 '21 at 09:47
  • something like this `2021-10-06 15:47:19 var = 5 test = 5`?? – Sabil Oct 06 '21 at 09:47
  • @jonrsharpe indeed, I expect the name from outside the function, thanks for reformulating. – OneArb Oct 06 '21 at 09:49
  • @Sabil `2021-10-06 15:47:19 test = 5` – OneArb Oct 06 '21 at 09:56
  • follow the flagged question, hope that will resolve your issue – Sabil Oct 06 '21 at 10:00
  • @Sabil It does in part. I am looking for a production code solution. – OneArb Oct 06 '21 at 10:04

1 Answers1

-2

In f-strings you need to put the variable that needs to be printed between accolades. Like this:

from datetime import datetime
    
def print_var(var):
    print(str(datetime.now())[:19], end=' ')
    print(f'var = {var}')

Running the test yields the following:

test = 5
print_var(test)
>>>2021-10-06 11:32:05 var = 5
kfj_bond
  • 1
  • 1
  • 3
    `f'var = {var}'` does the same thing that `f'{var = }'` does, just with more typing; the OP wants the name from _outside_ the function. – jonrsharpe Oct 06 '21 at 09:46