How do I determine the size of an object in Python?

前端 未结 13 1459
半阙折子戏
半阙折子戏 2020-11-21 21:53

I want to know how to get size of objects like a string, integer, etc. in Python.

Related question: How many bytes per element are there in a Python list (tuple)?

13条回答
  •  余生分开走
    2020-11-21 22:53

    Use sys.getsizeof() if you DON'T want to include sizes of linked (nested) objects.

    However, if you want to count sub-objects nested in lists, dicts, sets, tuples - and usually THIS is what you're looking for - use the recursive deep sizeof() function as shown below:

    import sys
    def sizeof(obj):
        size = sys.getsizeof(obj)
        if isinstance(obj, dict): return size + sum(map(sizeof, obj.keys())) + sum(map(sizeof, obj.values()))
        if isinstance(obj, (list, tuple, set, frozenset)): return size + sum(map(sizeof, obj))
        return size
    

    You can also find this function in the nifty toolbox, together with many other useful one-liners:

    https://github.com/mwojnars/nifty/blob/master/util.py

提交回复
热议问题