Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Indicative Python prints

Tags:

python

I would like it if there was some way to generate a more indicative python prints: when printing some value, not only the result will be printed out, but also the expression that got me that result.

For example, lets say I have:

>>> x = 1

Then, for printing x and its type, we get:

>>> print x ; print type(x)
1
<type 'int'>

I would like to get somthing like:

>>> print x ; print type(x)
x: 1
type(x): <type 'int'>

I've tried using locals(), inspect module, but I couldn't get this result. Any id Thanks.

like image 970
stav Avatar asked Feb 22 '26 08:02

stav


2 Answers

You can certainly write a function for this purpose:

def print_ex(expr, globals=None, locals=None):
    res = eval(expr, globals, locals)
    print expr + ":", res
    print "type(" + expr + "):", type(res)

Example:

>>> print_ex("2 + 3")
2 + 3: 5
type(2 + 3): <type 'int'>

Note that eval() executes arbitrary expressions, so make sure you never pass a string from an untrusted source to print_ex().

If you don't like the need to explicitly pass locals() and globals(), you could also use

frame = inspect.currentframe().f_back
globals = frame.f_globals
locals = frame.f_locals

to automatically use the globals() and locals() of the calling frame.

like image 194
Sven Marnach Avatar answered Feb 24 '26 20:02

Sven Marnach


This demonstrates the most reasonable way I can think to easily show the information you want:

def info(name, namespace):
    thing = namespace[name]
    print "%s: %s" % (name, thing)
    print "type(%s): %s" % (name, type(thing))

To use it, give the name of the object you're interested in, and the namespace:

$ python -i info.py 
>>> a = 1
>>> info('a', locals())
a: 1
type(a): <type 'int'>
>>> 

Of course, you could split this up into two different functions, subclass your favourite logging module and add it as a method, etc.

like image 40
detly Avatar answered Feb 24 '26 20:02

detly



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!