class Data:
    def __enter__(self):
        print('construct')
        class _Data:
            def __init__(self) -> None:
                self.file = open('foo.txt''w')
                pass
            def cleanup(self) -> None:
                print('file closing')
                self.file.close()
                pass
            def work(self) -> None:
                print('work')
                pass
        self.__data_obj = _Data()
        return self.__data_obj

    def __exit__(selfexc_typeexc_valuetraceback) -> None:
        print('destruct')
        self.__data_obj.cleanup()
        pass

if __name__ == "__main__":
    with Data() as d:
        d.work()

결과:
construct work destruct file closing