D
Dan Barbus
Hi all,
I'm a python beginner, and I have a problem with no solution I can
see:
I want to index all instances of an object by an internal id (not the
hash) and be able to retrieve them later.
I created a class-level dictionary (Item._itemById) where I add every
new instance. My problem is:
How do I delete the instances when the class is no longer in use?
( having it in a map makes it 'in use' all the time, so my
implementation results in a memory leak ).
Here's the code:
class Item():
"""This is the base class for all data items"""
_idBase = None
_count = 0
_itemsById = {}
def __init__(self, title = ''):
Item._count += 1
self.id = Item._generateId(self)
Item._itemsById[self.id] = self
self.title = title
def __del__(self):
Item._count -= 1
# Should I do something here to delete the instance?
# Will this ever be called if the instance is in a static
dictionary?
def _generateId(self):
"""Generates an unique id for the instance. The id will be
unique
for both the current run and all runs in general.
"""
if not Item._idBase:
Item._idBase = str(hash(self))
return Item._idBase + '-' + str(Item._count).zfill(6)
def getItemById(id):
return _itemsById[id]
I'm a python beginner, and I have a problem with no solution I can
see:
I want to index all instances of an object by an internal id (not the
hash) and be able to retrieve them later.
I created a class-level dictionary (Item._itemById) where I add every
new instance. My problem is:
How do I delete the instances when the class is no longer in use?
( having it in a map makes it 'in use' all the time, so my
implementation results in a memory leak ).
Here's the code:
class Item():
"""This is the base class for all data items"""
_idBase = None
_count = 0
_itemsById = {}
def __init__(self, title = ''):
Item._count += 1
self.id = Item._generateId(self)
Item._itemsById[self.id] = self
self.title = title
def __del__(self):
Item._count -= 1
# Should I do something here to delete the instance?
# Will this ever be called if the instance is in a static
dictionary?
def _generateId(self):
"""Generates an unique id for the instance. The id will be
unique
for both the current run and all runs in general.
"""
if not Item._idBase:
Item._idBase = str(hash(self))
return Item._idBase + '-' + str(Item._count).zfill(6)
def getItemById(id):
return _itemsById[id]