i want define class attaches filehandle class. example, can define class instance variable file handler object, not safe when object dereferenced.
class customloggingclass(object): def __init__(self, *args, **kwargs): self.filehandle = open("logfile.json", "w+")
how implement in safe way logfile.json closed properly?
probably simplest thing create helper context manager function thecontextlib.contextmanager
decorator , use in conjunction awith
statement. example:
class customloggingclass(object): def __init__(self, *args, **kwargs): self.filehandle = open("logfile.json", "w+") def close(self): self.filehandle.close() import contextlib @contextlib.contextmanager def cm_logger(): logger = customloggingclass() yield logger logger.close() if __name__ == '__main__': cm_logger logger: # stuff logger, customloggingclass instance pass
the with
statement , context managers discussed in pep 343.
Comments
Post a Comment