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

前端 未结 13 1500
半阙折子戏
半阙折子戏 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:35

    You can serialize the object to derive a measure that is closely related to the size of the object:

    import pickle
    
    ## let o be the object, whose size you want to measure
    size_estimate = len(pickle.dumps(o))
    

    If you want to measure objects that cannot be pickled (e.g. because of lambda expressions) dill or cloudpickle can be a solution.

提交回复
热议问题