PetterKraabol / Twitch-Python

Object-oriented Twitch API for Python developers
https://pypi.org/project/twitch-python
MIT License
214 stars 37 forks source link

Poor shut-down behaviour. #36

Open Julian-O opened 3 years ago

Julian-O commented 3 years ago

This package often will not cleanly shutdown, leaving a thread running in the background. There are two parts to the problem.

I suspect the root cause is that C++ destructor techniques are being applied to Python code, which has a different model.

  1. There is no way to cleanly shut down a Chat instance.

There is a __del__ method on Chat which sets its local IRC instance to not be active. In Python, the __del__ operation is not automatically called when an object is deleted. It might be called by the garbage collector, sometime later. The garbage collector is not required to run at all, especially at shut-down.

Instead, a close() methods should be defined to all the user to call it. The __del__ method could be defined, and made to call the close() method, but it cannot be relied upon and adds little value here, so I would remove it.

  1. Sometimes programs crash, and don't cleanly shut-down. The program should terminate and not hang.

There is a separate clean-up mechanism available for threads that is appropriate here: daemon threads. The IRC thread should be defined as a daemon thread - if the main thread finishes and the only remained threads are all daemon threads, they will be terminated. This is appropriate for a library such as this one.

I changed IRC.py, line 12, from:

    super().__init__()

to:

    super().__init__(daemon=True)

and my shut-down issues disappeared.