Prevent TextIOWrapper from closing on GC in a Py2/Py3 compatible way

前端 未结 4 647
面向向阳花
面向向阳花 2021-01-12 02:34

What I need to accomplish:

Given a binary file, decode it in a couple different ways providing a TextIOBase API. Ideally these subseque

4条回答
  •  花落未央
    2021-01-12 03:08

    Just detach your TextIOWrapper() object before letting it be garbage collected:

    def mangle(x):
        wrapper = io.TextIOWrapper(x)
        wrapper.detach()
    

    The TextIOWrapper() object only closes streams it is attached to. If you can't alter the code where the object goes out of scope, then simply keep a reference to the TextIOWrapper() object locally and detach at that point.

    If you must subclass TextIOWrapper(), then just call detach() in the __del__ hook:

    class DetachingTextIOWrapper(io.TextIOWrapper):
        def __del__(self):
            self.detach()
    

提交回复
热议问题