Created
September 12, 2024 00:56
-
-
Save rhee-elten/84569d1a5ef3bfee37beac52c4d7ac04 to your computer and use it in GitHub Desktop.
obj_summary.py
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
# obj_summary.py | |
# gist: https://gist.github.com/rhee-elten/84569d1a5ef3bfee37beac52c4d7ac04 | |
import sys | |
from functools import partial | |
import numpy as np | |
import pandas as pd | |
def obj_summary(obj, *, key=None, prefix="", visited=None): | |
_recurse = obj_summary | |
if visited is None: | |
visited = [] | |
def emit(msg, *, key=key): | |
if key is None: | |
print(f"{prefix}{msg}", file=sys.stderr) | |
else: | |
print(f"{prefix}{key}={msg}", file=sys.stderr) | |
is_array = lambda obj: isinstance(obj, np.ndarray) and obj.shape != () | |
if ( | |
isinstance(obj, dict) | |
or isinstance(obj, list) | |
or isinstance(obj, tuple) | |
or isinstance(obj, pd.DataFrame) | |
or isinstance(obj, pd.Series) | |
): | |
if id(obj) in visited: | |
emit(type(obj)) | |
return | |
visited.append(id(obj)) | |
pass | |
if isinstance(obj, dict): | |
emit(f"{type(obj)}:") | |
for k, v in obj.items(): | |
_recurse(v, key=k, prefix=prefix + " ", visited=visited) | |
return | |
if isinstance(obj, list) or isinstance(obj, tuple): | |
emit(f"{type(obj)}:") | |
for v in obj: | |
_recurse(v, key=None, prefix=prefix + " ", visited=visited) | |
return | |
if is_array(obj): | |
emit(f"{type(obj)}, shape={obj.shape}, dtype={obj.dtype}") | |
return | |
if isinstance(obj, pd.DataFrame) or isinstance(obj, pd.Series): | |
emit(f"{type(obj)}, shape={obj.shape}") | |
return | |
emit(repr(obj)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment