python - Retain file pointer after function call, using the decorator pattern -
i need decorator (or other neat design pattern) functions dealing files. main purpose remain file pointer @ same position was, after function acts on file.
here code, including dummy tests. problem decorator doesn't work on instance methods, if pass args
, kwargs
it. not figure out how design code…
import unittest cstringio import stringio def remain_file_pointer(file_obj): def wrap(f): def wrapped_f(*args, **kwargs): old_position = file_obj.tell() f(*args, **kwargs) file_obj.seek(old_position, 0) homecoming wrapped_f homecoming wrap class testremainfilepointer(unittest.testcase): def test_remains_filepointer(self): dummy_file = stringio('abcdefg') @remain_file_pointer(dummy_file) def seek_into_file(dummy_file): dummy_file.seek(1, 0) self.assertequal(0, dummy_file.tell()) seek_into_file(dummy_file) self.assertequal(0, dummy_file.tell()) def test_remains_filepointer_in_class_method(self): class fileseekerclass(object): def __init__(self): self.dummy_file = stringio('abcdefg') @remain_file_pointer(self.dummy_file) def seek_into_file(self): self.dummy_file.seek(1, 0) fileseeker = fileseekerclass() self.assertequal(0, fileseeker.dummy_file.tell()) fileseeker.seek_into_file() self.assertequal(0, fileseeker.dummy_file.tell())
update: clarify basic idea:
the decorator should take argument, file handler , store position before actual function manipulates file. after that, pointer should set old position. , should work either standalone functions , methods.
my reply below fixes problem assuming lastly argument in function file handler.
i'll not mark final answer, since i'm pretty sure there improve design.
i came solution assumes lastly argument of data-manipulating function file handler , access via args[-1]
:
def remain_file_pointer(f): """remain file pointer position after calling decorated function decorator assumes lastly argument file handler. """ def wrapper(*args, **kwargs): file_obj = args[-1] old_position = file_obj.tell() return_value = f(*args, **kwargs) file_obj.seek(old_position, 0) homecoming return_value homecoming wrapper
python methods decorator
No comments:
Post a Comment