Skip to content

Instantly share code, notes, and snippets.

Last active June 2, 2022 21:32
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
What would you like to do?
describe - line and filename, variable name, class, str representation and some other info
# Print the line and filename, function call, the class, str representation and some other info
# Inspired by
import inspect
import re
def describe(arg):
frame = inspect.currentframe()
callerframeinfo = inspect.getframeinfo(frame.f_back)
context = inspect.getframeinfo(frame.f_back).code_context
caller_lines = ''.join([line.strip() for line in context])
m ='describe\s*\((.+?)\)$', caller_lines)
if m:
caller_lines =
position = str(callerframeinfo.filename) + "@" + str(callerframeinfo.lineno)
# Add additional info such as array shape or string length
additional = ''
if hasattr(arg, "shape"):
additional += "[shape={}]".format(arg.shape)
elif hasattr(arg, "__len__"): # shape includes length information
additional += "[len={}]".format(len(arg))
# Use str() representation if it is printable
str_arg = str(arg)
str_arg = str_arg if str_arg.isprintable() else repr(arg)
print(position, "describe(" + caller_lines + ") = ", end='')
print(arg.__class__.__name__ + "(" + str_arg + ")", additional)
print("Describe: couldn't find caller context")
del frame
del callerframeinfo
import numpy
describe((3, 2))
describe(numpy.zeros((2, 4)))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment