Skip to content

Instantly share code, notes, and snippets.

@usr-ein
Last active August 5, 2021 10:17
Show Gist options
  • Save usr-ein/85a6cd433ce27f14b79b82009e595aae to your computer and use it in GitHub Desktop.
Save usr-ein/85a6cd433ce27f14b79b82009e595aae to your computer and use it in GitHub Desktop.
Prints a NumPy-like array's shape, as well as the name of its input variable outside the functions' scope
# Pshape is now a fully fledged Python library !
# Check it out at https://github.com/sam1902/pshape
# and install it anywhere with
#
# pip3 install pshape
import inspect, re
def pshape(arr):
frame = inspect.currentframe()
func_name = inspect.getframeinfo(frame).function
vname = "array"
for line in inspect.getframeinfo(frame.f_back)[3]:
m = re.search(func_name + "\((.*)\)$", line)
if m:
vname = m.group(1)
print(f"{vname}: \t{tuple(arr.shape)}")
if __name__ == "__main__":
import numpy as np
my_cool_array = np.random.rand(123,4,2)
pshape(my_cool_array)
# prints:
# my_cool_array: (123,4,2)
pshape(np.arange(12).reshape(3,4))
# prints:
# np.arange(12).reshape(3,4): (3,4)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment