473,597 Members | 2,050 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

index all instances by id - a memory leak?

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._generateI d(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(sel f):
"""Generate s 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]
Oct 2 '08 #1
4 1105
On Oct 2, 7:54*am, Dan Barbus <dan.bar...@gma il.comwrote:
>
* * def getItemById(id) :
* * * * return _itemsById[id]
I just saw that this won't compile. Still, ignoring this, I thing the
purpose of the code is pretty clear.

Thanks for any feedback.

Oct 2 '08 #2
On Oct 1, 10:01*pm, Dan Barbus <dan.bar...@gma il.comwrote:
On Oct 2, 7:54*am, Dan Barbus <dan.bar...@gma il.comwrote:
* * def getItemById(id) :
* * * * return _itemsById[id]

I just saw that this won't compile. Still, ignoring this, I thing the
purpose of the code is pretty clear.

Thanks for any feedback.
Check the weakref module, you can create a WeakValueDictio nary which
will not increment the refcount of the value, and will return None
after it's been garbage collected.
Oct 2 '08 #3
On Wed, 01 Oct 2008 21:54:26 -0700, Dan Barbus wrote:
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?
Don't use the `__del__()` method. It is not reliable as there are almost
no guarantees when or if at all it will be called. But its sole
existence may be the cause that objects of that class can't be garbage
collected. Read the documentation of `__del__()` for details.

Ciao,
Marc 'BlackJack' Rintsch
Oct 2 '08 #4
On Oct 1, 10:35*pm, Jason Scheirer <jason.schei... @gmail.comwrote :
On Oct 1, 10:01*pm, Dan Barbus <dan.bar...@gma il.comwrote:
On Oct 2, 7:54*am, Dan Barbus <dan.bar...@gma il.comwrote:
* * def getItemById(id) :
* * * * return _itemsById[id]
I just saw that this won't compile. Still, ignoring this, I thing the
purpose of the code is pretty clear.
Thanks for any feedback.

Check the weakref module, you can create a WeakValueDictio nary which
will not increment the refcount of the value, and will return None
after it's been garbage collected.
Another idea: have an AbstractFactory that keeps track of instances
created. When you done, delete the abstract factory, which will
delete the internal index. You'll have to figure out how to pass the
factory around, and when to delete it. Weakref sounds better, overall.
Oct 2 '08 #5

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

8
3400
by: ranjeet.gupta | last post by:
Dear All Is the Root Cause of the Memory corruption is the Memory leak, ?? suppose If in the code there is Memory leak, Do this may lead to the Memory Corruption while executing the program ? In nut shell, what is/are the realtion/s between the Memory Leak and Memory Corruption. Juts Theoritical Assumtion below:
4
6075
by: Don Nell | last post by:
Hello Why is there a memory leak when this code is executed. for(;;) { ManagementScope scope = new ManagementScope(); scope.Options.Username="username"; scope.Options.Password="password"; scope.Path.Path=@"\\pc\root\cimv2";
20
8081
by: jeevankodali | last post by:
Hi I have an .Net application which processes thousands of Xml nodes each day and for each node I am using around 30-40 Regex matches to see if they satisfy some conditions are not. These Regex matches are called within a loop (like if or for). E.g. for(int i = 0; i < 10; i++) { Regex r = new Regex();
23
4530
by: James | last post by:
The following code will create memory leaks!!! using System; using System.Diagnostics; using System.Data; using System.Data.SqlClient; namespace MemoryLeak
7
6926
by: Salvador | last post by:
Hi, I am using WMI to gather information about different computers (using win2K and win 2K3), checking common classes and also WMI load balance. My application runs every 1 minute and reports the status of the machines. Upon we follow the .NET object lifetime recommendations the application is constantly consuming more memory! The problem is on the ManagementObjectSearch, upon we Dispose the object it seems that is not releasing the...
3
5303
by: Jim Land | last post by:
Jack Slocum claims here http://www.jackslocum.com/yui/2006/10/02/3-easy-steps-to-avoid-javascript- memory-leaks/ that "almost every site you visit that uses JavaScript is leaking memory". Anybody know anything about this? Does *Javascript* leak memeory, or does the *browser* leak memory?
1
1349
by: klopter | last post by:
I will describe what I want using the vector class and then point out the limitations of using vector. vector <MyClass> MyContainer. MyContainer.push( new MyClass(...) ) MyContainer now contains the first instance of MyClass. MyContainer.push( new MyClass(...) )
7
15683
by: Ragnar Agustsson | last post by:
Hi all I have been wandering about the best way to sandbox memory leaks in 3rd party libraries when using them from the .Net framework. I have a 3rd party library, written in C++, that leaks a lot of memory but I still had to use it. 1. After using DLLImport and seeing the memory leak I tried to load and
22
9326
by: Peter | last post by:
I am using VS2008. I have a Windows Service application which creates Crystal Reports. This is a multi theaded application which can run several reports at one time. My problem - there is a memory leak someplace. I can not detect the memory leak by running several reports by hand, but when I run tha app as a servrice and process few hundred reports there is significant memory leak. The application can consume over 1GB of memory where it...
0
7965
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
7884
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
8380
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
8029
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
8258
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
6683
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
5845
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
3880
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
1
2394
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.