getting memory usage of varaibles

Ned Batchelder ned at nedbatchelder.com
Wed May 3 19:30:58 EDT 2017


On Wednesday, May 3, 2017 at 6:22:28 PM UTC-4, Larry.... at gmail.com wrote:
> On Wed, May 3, 2017 at 6:15 PM, Terry Reedy <tjreedy at udel.edu> wrote:
> > On 5/3/2017 8:40 AM, Larry Martell wrote:
> >>
> >> On Wed, May 3, 2017 at 8:29 AM, Chris Angelico <rosuav at gmail.com> wrote:
> >>>
> >>> On Wed, May 3, 2017 at 10:12 PM, Larry Martell <larry.martell at gmail.com>
> >>> wrote:
> >>>>
> >>>> On Wed, May 3, 2017 at 12:57 AM, Chris Angelico <rosuav at gmail.com>
> >>>> wrote:
> >>>>>
> >>>>> On Wed, May 3, 2017 at 5:53 AM, Larry Martell <larry.martell at gmail.com>
> >>>>> wrote:
> >>>>>>
> >>>>>> And I can see it getting larger and larger. But I want to see what it
> >>>>>> is that is causing this. My thought was to put all the objects in a
> >>>>>> dict with their sizes and compare them as the program runs and report
> >>>>>> on the one that are growing. But I can't get the name of the object
> >>>>>> from gc.get_objects only the id.
> >>>>>
> >>>>>
> >>>>> Coming right back to the beginning here: What do you expect the name
> >>>>> of an object to be?
> >>>>
> >>>>
> >>>> The name of the variable in the program, e.g. sql, db_conn, rows, etc.
> >>>
> >>>
> >>> Name bindings are one-way. You can't go from the object to its name.
> >>> An object may have zero, one, or multiple names; and function-local
> >>> names could be used more than once.
> >>
> >>
> >> Yeah, that makes sense.
> >>
> >>> If you want an object to have a name for tracing purposes, you'll have
> >>> to give it one as some sort of attribute.
> >
> >
> >> A good trick to know. Thanks.
> >
> >
> > Python already uses this trick for functions, classes, and modules by giving
> > them .__name__ attribute.  Code objects have a .co_name attribute.  These
> > are used for tracing and tracebacks.
> 
> But not for a variable like a list or dict?

List and dicts don't inherently have names.  One list could be referred
to by a number of variables:

    a = b = c = [1, 2, 3]

Functions, classes, and modules can also be referred to by a number of
variables:

    def foo(): pass
    bar = baz = foo

But functions (by virtue of the name in the def statement) have an inherent
name, which can be different than the variable you used to access the
function:

    >>> print(foo.__name__)
    'foo'
    >>> print(bar.__name__)
    'foo'
    >>> print(baz.__name__)
    'foo'

--Ned.



More information about the Python-list mailing list