Search code examples
pythonpython-3.xobjectcallbackdel

Is there a way to let an object call a function after ist own destruction? [python3]


I want a callback function on del object


Explanation

I have a Player Class.

And a Player can have objects of Card in his Player.hand = []

Card instances can be destroyed via del <card_instance>

If a Player has no Cards in his hand , the game is over.

To check that only when necessary, I want a Card to call a Player.check_status() fuction, that checks if the game is over after its own destruction.

Is that possible?


Code

class Player:
     self.hand = [...<Cards>...]

    def check_status(self):
         if self.hand == []:
             print("--- GAME OVER ---")

class Card:
     self.player = <Player_instance>

     def __del__(self):
          del self
          self.player.check_status() # <----- I want to do something like this

Solution

  • Unless your object is tied to some external state that needs cleanup no matter what (like a file handle/socket), using __del__ usually isn't the right choice. It's a sign you might be doing something wrong. For example if you wrapped your del in a try...except, then do something else assuming the hand has been changed you'd be wrong. Objects can be (temporarily) kept alive by a try..except block. del card is not the same thing as card.__del__(), it does NOT guarantee __del__ will be called.

    Likewise, usually you want your parent to manage it's children, not the other way around. Player's control their cards, cards don't control the player.

    Just be explicit with your actions:

    class Player:
        def __init__(self):
            self.hand = []
    
        def add_card(self, card):
            self.hand.append(card)
    
        def remove_card(self, card):
            self.hand.remove(card)
            if not self.hand:
                print('--- GAME OVER ---')