2

Is there a way to do this in Python, so that:

pr(foo)              # => foo is 123
pr(fn())             # => fn() is True
pr(obj.getVal())     # => obj.getVal() is 3.14
pr(obj.a().b.c)      # => obj.a().b.c is "hello"
pr(1 + calc() / 2)   # => 1 + calc() / 2 is 56

that is, print out what is being printed, as well as the value. Some people will say this is not possible in any language, but it is in fact possible in C and Ruby.

nonopolarity
  • 146,324
  • 131
  • 460
  • 740

3 Answers3

3

try this:

a = 1
b = 2

def fnc():
    return 'FUNCTION'

def pr(name):
    print('{} is {}'.format(name, eval(name)))

pr('a')
pr('b')
pr('fnc()')

Output:

a is 1
b is 2
fnc() is FUNCTION
MaxU - stand with Ukraine
  • 205,989
  • 36
  • 386
  • 419
2

I'd want to say: "it is impossible", which is true, for certain degrees of impossible.

There is no way to make a code macro in Python such that the usual C tricks with preprocessor stringifications and such would require.

However, you still have 2 choices:

  1. if sources are available, you can make a debug function that would dig the line in source code where it was called using the call frames. However Python bytecode only stores line numbers, not column positions on the line, so you couldn't distinguish 2 said function calls on the same line.

  2. Use the eval trick - pass in a string that is evalled in the function in the caller's globals and locals, and then printed out.

The 2nd would be slightly less yuck and would be more portable as well:

import inspect

def pr(expr):
    calling_frame = inspect.currentframe().f_back
    value = eval(expr, calling_frame.f_globals, calling_frame.f_locals)
    print("{} = {}".format(expr, value))

Elsewhere you just need to import this and you can do

a = 5
def func():
    b = 42
    pr('a, b')

func()

which prints out

a, b = (5, 42)
Community
  • 1
  • 1
-1

This is not possible. Python object not contains references to its names. If integers, lists, dicts and others needed to maintain a list of strings that represented names that referred to it... Imagine this!

PRVS
  • 1,612
  • 4
  • 38
  • 75