user972014
user972014

Reputation: 3856

Python delete object received as parameter

I call a function, giving it some very large object. The needs something specific out of it and then wants to remove that from memory. This can be demonstrated using the following code:

def main():
  obj = get_very_large_obj()
  func(obj)
  # obj i not longer used!


def func(obj):
  specific_value = obj.get_some_needed_value()
  del obj
  # Do some very long work
  return

The function func needs something specific out of obj, and once it is retrieved I no longer obj residing in memory. I want to do my "long work" without wasting tons of it.

Can this be achieved?

Upvotes: 0

Views: 252

Answers (1)

Barmar
Barmar

Reputation: 780851

Wrap the large object in a list. Then you can remove the list element, and the object will become garbage collectable.

def main():
    objlist = [get_very_large_obj()]
    func(objlist)

def func(objlist):
    specific_value = obj[0].get_some_needed_value()
    del obj[0]
    # Do some very long work
    return

Upvotes: 2

Related Questions