473,785 Members | 2,400 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Generator inside a class prevent __del__ ??

Hi,

I run across this problem, and couldn't find any solution (python 2.2.2)
:

Code :
===========
from __future__ import generators
class titi: def __init__(self):
print "init"
def __del__(self):
print "del"
def Gen(self):
yield 1
c = titi() init c = [] del
==============
Here, everything is normal...
But creating a generator :

Code :
===========
class toto: def __init__(self):
print "init"
self.Coroutine = self.Gen()
def __del__(self):
print "del"
def Gen(self):
yield 1
a = toto() init c = []

<--- Nothing there !!!
==============

I can't understand why the destructor is not called when a generator is
created, and what I should do to have a "correct" behavior.
(perhaps I missed something obvious, but I can't find it )
Thank you for any help,

Emmanuel


Jul 18 '05
13 2035
On Thu, Apr 22, 2004 at 01:26:18AM +0200, Emmanuel wrote:


Andrew Bennetts a écrit :
On Wed, Apr 21, 2004 at 02:53:33PM +0200, Emmanuel wrote:

Trouble is, I _would_ like not to care about the lifetime of the object, and I
don't know where it will be destroyed.
Then don't use __del__. Python can and will automatically collect cycles
when the objects *don't* define __del__ methods.

Out of curiousity, why are you defining __del__ anyway?

-Andrew.


I don't want to use __del__, but I suspected I had an issue with the destruction of
my objects, and used a log in __del__ to monitor the destruction.


Except that __del__ affects how they are destructed :)

Weakrefs are probably a better choice for this, as they don't interfere with
the lifecycle of the object you're interested in, unlike __del__.
But defining __del__ has also a lot of valuable utilisation, or so I think...


It's only very very rarely useful, in my experience. Again, weakrefs are
probably more useful for what you have in mind.

-Andrew.
Jul 18 '05 #11


Andrew Bennetts a écrit :
On Thu, Apr 22, 2004 at 01:26:18AM +0200, Emmanuel wrote:


Andrew Bennetts a écrit :
On Wed, Apr 21, 2004 at 02:53:33PM +0200, Emmanuel wrote:
>
> Trouble is, I _would_ like not to care about the lifetime of the object, and I
> don't know where it will be destroyed.

Then don't use __del__. Python can and will automatically collect cycles
when the objects *don't* define __del__ methods.

Out of curiousity, why are you defining __del__ anyway?

-Andrew.


I don't want to use __del__, but I suspected I had an issue with the destruction of
my objects, and used a log in __del__ to monitor the destruction.


Except that __del__ affects how they are destructed :)

Weakrefs are probably a better choice for this, as they don't interfere with
the lifecycle of the object you're interested in, unlike __del__.
But defining __del__ has also a lot of valuable utilisation, or so I think...


It's only very very rarely useful, in my experience. Again, weakrefs are
probably more useful for what you have in mind.

-Andrew.


Ok, I think I don't understand anything anymore...

I thought __del__ was the destructor of the object, like the object::~object in C++ ( my
experience in programming is mainly from C++ ), and so __del__ shouldn't affect when they
are destructed.
And I thought weakref is a way to control the lifetime, ie when the ref count is
decremented, and when to call __del__.

From what you ( and others ) are saying, I'm proven wrong...

Do you know where I can find more information, beside python doc ?

Thanks,

Emmanuel
Jul 18 '05 #12


Terry Reedy a écrit :
"Emmanuel" <ea*****@free.f r> wrote in message
news:40******** *******@free.fr ...


Terry Reedy a écrit :
> >>> class toto:
> def __init__(self):
> print "init"
> self.Coroutine = self.Gen()

This creates a reference loop. Delete this (and correct typo below) and 'problem' will disappear.

To amplify: the usual idiom for an instance-associated generator is to name
the generator function (method) __iter__ (with one param, self) and to
create and get a reference to the generator via iter() or let the for loop
mechanism do so for you.

c = C(*args)
cgen =iter(c)

Then there is no reference loop. And you can pass around the cgen object
just like any other. If you only need the instance after initialization to
get the generator and you only need one generator for the instance, then
combine the two lines into

cgen = iter(C(*args))

and the *only* reference to the instance is the one in the generator, which
will disappear at the end of a for loop or with an explicit 'del cgen'.


But I obviously need other references to my object in my code, my object isn't
modified by the generator only.
I want to resume my generator from time to time during the execution of my app,
and to modify the members of the objects somewhere else ( interaction between
my objects ).
Doing this result in my nicer programmation style than without generators.



There is also the question whether you actually *need* to get rid of the
object while the program is still running instead of just letting the
program finish and clean up.


I have a _lot_ of objects created whenever they want, and I don't know where
they will finish their job.
Additionnaly, I'm not developping only on PC, but also on platforms where there
is not so much memory avalaible.

By the way, it seems I still have a lot to understand on this subject.
Do you know any link, example, or whatever, that I could have a look at ?

Thank you very much for your answers,

Emmanuel
Jul 18 '05 #13
On Thu, Apr 22, 2004 at 11:12:27AM +0200, Emmanuel wrote:

Ok, I think I don't understand anything anymore...

I thought __del__ was the destructor of the object, like the object::~object in C++ ( my
experience in programming is mainly from C++ ), and so __del__ shouldn't affect when they
are destructed.
__del__ unfortunately *does* impact the lifetime of the object, at least in
CPython:
http://docs.python.org/lib/module-gc.html#l2h-403
http://docs.python.org/ref/customization.html#l2h-175

It's main use used to be to break reference cycles, because before Python
2.0 (or perhaps 1.6?), it couldn't automatically collect reference cycles
because it used a purely ref-count based approach. Now that cycles are
automatically collected, there's not much point in defining __del__ (and it
can actually have unexpected results).
And I thought weakref is a way to control the lifetime, ie when the ref count is
decremented, and when to call __del__.


No -- weakref doesn't affect the lifetime, that's it's point. It's a way to
have a reference to an object that doesn't keep the object alive if nothing
else is. As the documentation at
http://docs.python.org/lib/module-weakref.html says:

A weak reference to an object is not enough to keep the object alive:
when the only remaining references to a referent are weak references,
garbage collection is free to destroy the referent and reuse its memory
for something else.
From what you ( and others ) are saying, I'm proven wrong...


Do you know where I can find more information, beside python doc ?


Try googling for tutorials and things, there's probably stuff out there.
The Python docs are pretty good, though... the weakref module has pretty
comprehensive documentation, and the description of __del__ in the language
reference has big note that mentions that garbage-collection of cycles
doesn't work when __del__ methods are involved.

I've also found books such as Python in a Nutshell and the Python Essential
Reference to be quite good at pointing this sort of thing out, when I've
looked. I usually rely on the official Python docs, though.

-Andrew.
Jul 18 '05 #14

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

Similar topics

17
2444
by: Andrae Muys | last post by:
Found myself needing serialised access to a shared generator from multiple threads. Came up with the following def serialise(gen): lock = threading.Lock() while 1: lock.acquire() try: next = gen.next() finally:
1
4816
by: Rajorshi | last post by:
Hi, I have two classes, say, Base1 and Base2. Now Derv is a class derived from both like class Derv(Base1,Base2)..... In the destructor of the derived class, if I write something like this def __del__(self): for b in self.__class__.__bases__: b.__del__(self)
4
2355
by: Wai Yip Tung | last post by:
I'm attempting to turn some process than uses callback to return result into a more user friendly generator. I'm hitting some road block so any pointer would be appriciated. Let say there is an existing method producer(x, cb). It calls the supplied cb() every time when there is data available. The definititon of cb should be: def cb(data)
45
3047
by: Joh | last post by:
hello, i'm trying to understand how i could build following consecutive sets from a root one using generator : l = would like to produce : , , , ,
4
6540
by: Baoqiu Cui | last post by:
Today I was playing with a small Python program using Python 2.4 on Cygwin (up-to-date version, on Windows XP), but ran into a strange error on the following small program (named bug.py): ------------------------------- #!/usr/bin/python class Person: population = 0 def __del__(self):
2
27975
by: Kiran | last post by:
Hi, We would like to develop a product in VB.Net. This is the first time I'm involving in such type of practice. Can any one please provide the information about the fallowing??? 1. How to generate Licence Key(s) for the product? Are there any components available to do so? 2. Since the product is distributed thru CDs, what is the process to provide licence keys for the clients? Please help.
11
1751
by: vbgunz | last post by:
I am afraid that this is the first time in which I would probably need something explained to me as if I were a little child. I am having a hard time getting this through my thick skull. What in the world is wrong with this!? ''' ########################################################### ''' def generatorFunction(sequence=): for item in sequence: yield item
10
3193
by: Max Yuzhakov | last post by:
Hello! It is correct behaviour for python to call __del__ on some identity of a class object more than once? In brief I shall describe a situation. Sorry for my english. For debugin purposes I'm put in my module global counters for counting __init__ and __del__ calls.
2
2132
by: Spes | last post by:
Hi, I have this simple code: | #!/usr/bin/python | import codecs | import re | from copy import deepcopy | | class MyClass(object): | def __del__(self):
0
9646
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
10346
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
10157
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...
0
8982
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
7504
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
6742
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5386
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
4055
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
2
3658
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

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.