diff options
| author | Florian Fischer <florian.fischer@muhq.space> | 2023-09-18 17:44:12 +0200 |
|---|---|---|
| committer | Florian Fischer <florian.fischer@muhq.space> | 2023-09-18 17:44:12 +0200 |
| commit | 2f2b51e40c7027d80bf4a6741f2063e2c224f938 (patch) | |
| tree | d9558ede8f4615bb6d86c50360524b15f7ddf63f /geldschieberbot.py | |
| parent | a68565accffba8590bc539fb937a1adfcf7891ab (diff) | |
| download | geldschieberbot-2f2b51e40c7027d80bf4a6741f2063e2c224f938.tar.gz geldschieberbot-2f2b51e40c7027d80bf4a6741f2063e2c224f938.zip | |
make Geldschieberbot a context manager
Previosuly there was the problem that the state was saved when the
bot object was destructed.
When there was an unhandled exception it was possible for the builtins
to be cleanedup before the bot's destructor was executed resulting
in yet another exception because the open builtin was no longer
available.
This is no longer possible when the bot is used as a context manager
python guarantees that the __exit__ code is executed before leaving
the with block.
This allows us prevent the state from beeing saved when there was an
exception to prevent invalid states.
Diffstat (limited to 'geldschieberbot.py')
| -rw-r--r-- | geldschieberbot.py | 11 |
1 files changed, 7 insertions, 4 deletions
diff --git a/geldschieberbot.py b/geldschieberbot.py index 046d543..ff859f0 100644 --- a/geldschieberbot.py +++ b/geldschieberbot.py @@ -1009,8 +1009,6 @@ class Geldschieberbot: self.dry_run = dry_run # Run without changing the stored state self.record_changes = True # Should changes be recorded - self.load_state() - # Command dispatch table self.cmds = { 'reg': self.register, @@ -1046,8 +1044,13 @@ class Geldschieberbot: 'thanks': self.thanks, } - def __del__(self): - self.save_state() + def __enter__(self): + self.load_state() + return self + + def __exit__(self, exc_type, exc_value, exc_tb): + if not exc_type: + self.save_state() def enable_dry_run(self) -> bool: """Enable dry run""" |
