How to use the context manager to avoid the use of __del__ in python?

前端 未结 3 1518
刺人心
刺人心 2020-12-31 11:17

As it is common knowledge, the python __del__ method should not be used to clean up important things, as it is not guaranteed this method gets called. The alter

3条回答
  •  佛祖请我去吃肉
    2020-12-31 12:04

    I'm not quite sure what you're asking. A context manager instance can be a class member - you can re-use it in as many with clauses as you like and the __enter__() and __exit__() methods will be called each time.

    So, once you'd added those methods to MyWrapper, you can construct it in MyClass just as you are above. And then you'd do something like:

    def my_method(self):
        with self.mydevice:
            # Do stuff here
    

    That will call the __enter__() and __exit__() methods on the instance you created in the constructor.

    However, the with clause can only span a function - if you use the with clause in the constructor then it will call __exit__() before exiting the constructor. If you want to do that, the only way is to use __del__(), which has its own problems as you've already mentioned. You could open and close the device just when you need it using with but I don't know if this fulfills your requirements.

提交回复
热议问题