class - Python print length OR getting the size of several variables at once -
in python, if print
different data types separated commas, act according __str__
(or possibly __repr__
) methods, , print out nice pretty string me.
i have bunch of variables data1, data2...
below, , love total approximate size. know that:
not of variables have useful
sys.getsizeof
(i want know size stored, not size of container.) -thanks martijn pietersthe length of each of printed variables enough size estimate purposes
i'd avoid dealing different data types individually. there way leverage function print
total length of data? find quite unlikely not built python.
>>> obj.data1 = [1, 2, 3, 4, 5] >>> obj.data2 = {'a': 1, 'b':2, 'c':3} >>> obj.data3 = u'have seen crossbow?' >>> obj.data4 = 'trapped on surface of sphere' >>> obj.data5 = 42 >>> obj.data6 = <fake a.b instance @ 0x88888> >>> print obj.data1, obj.data2, obj.data3, obj.data4, obj.data5, obj.data6 [1, 2, 3, 4, 5] {'a': 1, 'c': 3, 'b': 2} have seen crossbow? trapped on surface of sphere 42 meh
i'm looking like:
printlen(obj.data1, obj.data2, obj.data3, obj.data4, obj.data5, obj.data6) 109
i know of write this, i'm asking if python has built-in way it. great solution show me way return
string print
prints in python 2.7. (something print_r
in php, otherwise feel wholly inferior python.) i'm planning on doing programmatically many objects have pre-filled variables, no writing temporary file or that.
thanks!
as side-note, question arose need calculate approximate total size of variables in class being constructed unknown data. if have way total size of non-callable items in class (honestly, total size work too), solution better. didn't make main question because looks me python doesn't support such thing. if does, hooray!
"a great solution show me way return string print prints in python 2.7."
this print
prints (possibly spaces, missing final newline):
def print_r(*args): return " ".join((str(arg) arg in args))
if run in lots of objects aren't str
-able use safer_str
instead:
def safer_str(obj): return str(obj) if hasattr(obj,"__str__") else repr(obj)
Comments
Post a Comment