473,796 Members | 2,520 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Unbound names in __del__

Hallöchen!

When my __del__ methods are called because the program is being
terminated, I experience difficulties in calling functions that I
need for a clean shutdown of my instances. So far, there has been
only one of these functions, and a class-local alias solved the
problem. However, now there are many of them.

Is there a way to detect whether the program is being terminated?
(In this case, I wouldn't care and return from __del__ immediately.)

Or do you know a cleaner solution? For example, if I have

import vpp43

would it help to say

def __init__(self):
__vpp43 = vpp43
...

to guarantee that I can access all the routines in vpp43 in the
__del__ method?

Tschö,
Torsten.

--
Torsten Bronger, aquisgrana, europa vetus
Jul 19 '05 #1
13 1410

"Torsten Bronger" <br*****@physik .rwth-aachen.de> wrote in message
news:m3******** ****@bob.ipv.kf a-juelich.de...
Is there a way to detect whether the program is being terminated?


See atexit module to register cleanup functions that run *before* the
interpreter starts haphazardly deleting stuff.

Terry J. Reedy


Jul 19 '05 #2
Hallöchen!

"Terry Reedy" <tj*****@udel.e du> writes:
"Torsten Bronger" <br*****@physik .rwth-aachen.de> wrote:
Is there a way to detect whether the program is being terminated?


See atexit module to register cleanup functions that run *before*
the interpreter starts haphazardly deleting stuff.


So I could register a function that sets a global variable called
"shutdown_has_b egun" to "True". Then I say

def __del__(self):
if shutdown_has_be gun: return
...

Alternatively, I could enclose every __del__ contents block with a
"try" whithout catching anything, just to suppress the error
messages.

However, all of this is not pretty pythonic in my opinion. Is it
that exotic to want to call functions from within __del__?

Tschö,
Torsten.

--
Torsten Bronger, aquisgrana, europa vetus
Jul 19 '05 #3
Torsten Bronger wrote:
When my __del__ methods are called because the program is being
terminated, I experience difficulties in calling functions that I
need for a clean shutdown of my instances. So far, there has been
only one of these functions, and a class-local alias solved the
problem. However, now there are many of them.
__del__ is messy and I avoid it whenever possible. Make sure you read
all the caveats and warnings on these pages:

http://www.python.org/doc/ref/customization.html
http://www.python.org/doc/lib/module-gc.html

Most importantly, "It is not guaranteed that __del__() methods are
called for objects that still exist when the interpreter exits."
Or do you know a cleaner solution? For example, if I have

import vpp43

would it help to say

def __init__(self):
__vpp43 = vpp43
...

to guarantee that I can access all the routines in vpp43 in the
__del__ method?


A similar idiom is found in the standard library (e.g. tempfile.py):

# Cache the unlinker so we don't get spurious errors at
# shutdown when the module-level "os" is None'd out. Note
# that this must be referenced as self.unlink, because the
# name TemporaryFileWr apper may also get None'd out before
# __del__ is called.
unlink = _os.unlink

def close(self):
if not self.close_call ed:
self.close_call ed = True
self.file.close ()
self.unlink(sel f.name)

def __del__(self):
self.close()
--
Michael Hoffman
Jul 19 '05 #4
Torsten Bronger wrote:
However, all of this is not pretty pythonic in my opinion. Is it
that exotic to want to call functions from within __del__?


Yes, I think it probably is. In the few hundred thousand lines of
Python code I've played a role in developing, we've used __del__ once,
to my knowledge, and I believe it was not a critical use, just an
expedient one.

And I don't recall the last time I saw a __del__ in third-party code I
was examining.

What's your use case for del?

-Peter
Jul 19 '05 #5
Hallöchen!

Peter Hansen <pe***@engcorp. com> writes:
[...]

What's your use case for del?


Every instance represents a "session" to a measurement instrument.
After the instance is deleted, the session should be closed to free
resources.

If the program exists, this is actually not necessary, because then
all resources are freed anyway. __del__ is called nevertheless.

Tschö,
Torsten.

--
Torsten Bronger, aquisgrana, europa vetus
Jul 19 '05 #6
Torsten Bronger wrote:
Peter Hansen <pe***@engcorp. com> writes:
What's your use case for del?


Every instance represents a "session" to a measurement instrument.
After the instance is deleted, the session should be closed to free
resources.


You mean like GPIB devices? We've written a lot of software that talks
to instruments, as well as pumps, motors, and sensors of all kinds. I
haven't even needed to "free resources", other than by closing a serial
port, for example. Such simple operations don't require the use of
__del__ and can easily be done with simple .close() type calls as the
application shuts itself down or finishes a test sequence or other
operation.

Use of __del__ is, in my opinion, a bit of a crutch (meaning it seems to
make life easier, but then you start relying on it and find it hard to
do without). Given that it isn't really reliable in non-trivial
situations, I'd recommend pretending __del__ does not exist and
restructuring your system to close these sessions explicitly, under your
direct control, at the appropriate point. This has worked very well for
us so far.

-Peter
Jul 19 '05 #7
Hallöchen!

Peter Hansen <pe***@engcorp. com> writes:
Torsten Bronger wrote:
Peter Hansen <pe***@engcorp. com> writes:
What's your use case for del?
Every instance represents a "session" to a measurement instrument.
After the instance is deleted, the session should be closed to free
resources.


You mean like GPIB devices?


Yes.
We've written a lot of software that talks to instruments, as well
as pumps, motors, and sensors of all kinds. I haven't even needed
to "free resources", other than by closing a serial port, for
example. [...]
I've just finished a thin-wrappers implementation of VISA in Python,
see <http://pyvisa.sf.net/>. It calls functions in a proprietary
VISA DLL/SO. The next step is to build a simple-to-use OO layer on
top of it. Therefore, we don't communicate with the device
directly, but via sessions (=handles) within the DLL.

These sessions should be freed when the object instance representing
the device is destroyed by Python. Using the __del__ method is the
natural choice for this in my opinion.
[...] I'd recommend pretending __del__ does not exist and
restructuring your system to close these sessions explicitly,
under your direct control, at the appropriate point. This has
worked very well for us so far.


I'd find this quite sad because so far it's drop-dead simple to use
the OO layer, and I may even convince our in-house HT Basic fans of
Python:

keithley = GpibInstrument( 14)
keithley.write( "*IDN?")
print keithley.read()

A keithley.close( ) would be a wart in my opinion; instead I want to
hide the whole session thing from the programmer. Besides, I
haven't yet given up the hope that the issues with __del__ can be
tackled.

Tschö,
Torsten.

--
Torsten Bronger, aquisgrana, europa vetus
Jul 19 '05 #8
Torsten Bronger wrote:
keithley = GpibInstrument( 14)
keithley.write( "*IDN?")
print keithley.read()

A keithley.close( ) would be a wart in my opinion; instead I want to
hide the whole session thing from the programmer. Besides, I
haven't yet given up the hope that the issues with __del__ can be
tackled.


At least one alternative comes to mind. Have the GpibInstrument class
(or its module) register an atexit() method, and have the constructor
for that class track all instances. On shutdown, the atexit method goes
through all instruments that are still open and issues the .close()
requests, or whatever you do in the __del__ now.

In other words, it would be indistinguishab le from __del__ from the
users' point of view, at the cost of a little extra code to make things
explicit, instead of relying on the implicit and, unfortunately,
unreliable nature of __del__. (Which is probably the real wart in
Python, unfortunately.)

-Peter
Jul 19 '05 #9
Hallöchen!

Peter Hansen <pe***@engcorp. com> writes:
Torsten Bronger wrote:
keithley = GpibInstrument( 14)
keithley.write( "*IDN?")
print keithley.read()

A keithley.close( ) would be a wart in my opinion; instead I want
to hide the whole session thing from the programmer. Besides, I
haven't yet given up the hope that the issues with __del__ can be
tackled.


At least one alternative comes to mind. Have the GpibInstrument
class (or its module) register an atexit() method, and have the
constructor for that class track all instances. On shutdown, the
atexit method goes through all instruments that are still open and
issues the .close() requests, or whatever you do in the __del__
now.


However, this doesn't close sessions while the program is running.
If the programmer has the above code in a function which is called
repeatedly, he may run into trouble. IIRC my current VISA DLL has
only 256 session slots.

Tschö,
Torsten.

--
Torsten Bronger, aquisgrana, europa vetus
Jul 19 '05 #10

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

Similar topics

0
2476
by: seth | last post by:
Last week I encountered an AttributeError in my unit tests that I wasn'table to catch with an "except AttributeError" statement. The problem stemmed from a class that raised an error inside __init__and defined a __del__ method to clean up resources. I then discovered asimilar problem in the shelve module. This led me to two importantdiscoveries: 1. Attributes defined in __init__ after an error is raised will not be apart of the...
2
1645
by: Kepes Krisztian | last post by:
Hi ! I very wonder, when I get exp. in java with GC. I'm Delphi programmer, so I get used to destructorin objects. In Java the final method is not same, but is like to destructor (I has been think...). And then I try with some examples, I see, that the Java GC is
6
2594
by: Peter Abel | last post by:
I have an application, which is an instance of a class with a deeply nested object hierarchy. Among others one method will be executed as a thread, which can be stopped. Everything works fine except that when deleting the main instance - after the thread has been stopped - the __del__ method will not be carried out. Tough a simple example works as expected: >>> class A: .... def __init__(self):
13
2038
by: Emmanuel | last post by:
Hi, I run across this problem, and couldn't find any solution (python 2.2.2) : Code : =========== from __future__ import generators >>> class titi:
1
2028
by: schwerdy | last post by:
Hello developers! I'm using Python 2.3.4 under debian Sarge and want to write a small logger class. My source code reads: #*************************************************** import sys, time from fcntl import * class Log(object): """
2
2086
by: Mike C. Fletcher | last post by:
I'm looking at rewriting parts of Twisted and TwistedSNMP to eliminate __del__ methods (and the memory leaks they create). Looking at the docs for 2.3's weakref.ref, there's no mention of whether the callbacks are held with a strong reference. My experiments suggest they are not... i.e. I'm trying to use this pattern: class Closer( object ): """Close the OIDStore (without a __del__)""" def __init__( self, btree ): """Initialise the...
1
1491
by: Erwan Adam | last post by:
Hello all, Can someone reproduce this bug ... I use : python Python 2.4.3 (#2, Sep 18 2006, 21:07:35) on linux2 Type "help", "copyright", "credits" or "license" for more information. First test :
6
2876
by: George Sakkis | last post by:
I'm baffled with a situation that involves: 1) an instance of some class that defines __del__, 2) a thread which is created, started and referenced by that instance, and 3) a weakref proxy to the instance that is passed to the thread instead of 'self', to prevent a cyclic reference. This probably sounds like gibberish so here's a simplified example: ==========================================
6
2691
by: Volker Neurath | last post by:
Hi all, I have a Problem with combobox-property "NotInList" and an unbound Form. The situation: On my main form i have three comboboxes for data-exchange (here: Names of distributor, reseller and final customers, the whole database is made for storing information about quotatations - no, not for quoting itself) ut the boxes actually may not contain all our distributors and reseller's
0
10457
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
10013
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
9054
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
7550
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
6792
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
5443
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...
0
5576
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
4119
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
3
2927
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

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.