0

I'm trying to pass this code (from this answer):

import sys

# These are the usual ipython objects, including this one you are creating
ipython_vars = ['In', 'Out', 'exit', 'quit', 'get_ipython', 'ipython_vars']

# Get a sorted list of the objects and their sizes
sorted([(x, sys.getsizeof(globals().get(x))/1e6) for x in dir() if not x.startswith('_') and x not in sys.modules and x not in ipython_vars], key=lambda x: x[1], reverse=True)

To a function:

def memory_obj_list():
    import sys

    # These are the usual ipython objects, including this one you are creating
    ipython_vars = ['In', 'Out', 'exit', 'quit', 'get_ipython', 'ipython_vars']

    # Get a sorted list of the objects and their sizes
    a = sorted([(x, sys.getsizeof(globals().get(x))/1e6) for x in dir() if not x.startswith('_') and x not in sys.modules and x not in ipython_vars], key=lambda x: x[1], reverse=True)
    return(a)

But when I use the function just like:

memory_obj_list()

It returns an empty list. If I run the code, it works perfectly. Why?

Chris
  • 2,019
  • 5
  • 22
  • 67
  • Are you importing the function from a module/file or are you defining it in your shell? The "global" namespace for a function will be bound to the module where it was defined – Iain Shelvington Aug 22 '22 at 19:02
  • I'm defining it in the first cells of the notebook and running it well after – Chris Aug 22 '22 at 19:05
  • @IainShelvington in that case, do you know how could I make that the "global" namespace can read outside the function? – Chris Aug 22 '22 at 19:46
  • I'm not sure exactly what notebook/tool you are using but `dir()` returns names in the local scope which may be the issue, try printing `globals()` in your function to see if you do get the names you expect because I think printing `dir()` will not output much – Iain Shelvington Aug 22 '22 at 19:56

0 Answers0