Last active
August 5, 2021 10:17
-
-
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
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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