Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Delete a Python object and make it point to None

Here is my class definition :

class Playingsound:
    def ___init___(self):
        # blah

    def fadeout_and_stop(self):
        # do somthing (fadeout during 100 ms)
        del self

Here is my problem (similar to that one : Python object deleting itself) :

>>> a = Playingsound()
>>> time.sleep (1.0)
>>> a.fadeout_and_stop()
>>> time.sleep (1.0)    # after 1 second, the playback should be finished !
>>> a
<__main__.Playingsound instance at 0x01F23170>

Instead of this, I would like a to be totally destroyed after the call of fadeout_and_stop, and its reference to be None :

>>> a
<None>

How to do this with Python ?

like image 378
Basj Avatar asked Feb 25 '26 02:02

Basj


1 Answers

You cannot, not without looping through all references in the garbage collector and testing each and every one if it is a reference to this object, then setting that reference to None. You don't want to go there. Remember: you can have more than one reference to your object:

a = A()
b = a
a.finish()  # what should be set to `None` now? a, b or both?

Instead of a.finish(), do del a, perhaps combined with implementing a __del__ clean-up hook.

If you need to have your object cleaned up after a timeout, add your object to a global list, and remove it from that list when done playing. The list can be on the class itself:

class Playingsound:
    playing = []

    def fadeout_and_stop(self):
        Playingsound.playing.append(self)
        # do somthing (fadeout during 100 ms)
        Playingsound.playing.remove(self)

then if there are no other references to the instance Python will take care of cleaning it up for you:

a = Playingsound()
a.fadeout_and_stop()
del a

You can always access any sounds still playing via Playingsound.playing.

like image 178
Martijn Pieters Avatar answered Feb 27 '26 14:02

Martijn Pieters



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!