python - Should I decorate a function? -
trying determine if should try use decorator or other pythonic way reduce code many of functions doing. these functions able call maybe 1 other function @ start of each function or somehow "decorate" start of each function. have never used decorator before , struggling implement decorate idea in pythonic way reduce common set of share code @ each function.
i have many functions perform same set of steps @ start of function. however, there structure concerns of common code makes "decorator" idea difficult :
the functions in child class of parent class.
the common commands between functions reference variable names specific function (but subset of function name).
the common commands need return caller , not execute more of child function if condition met. ("if jobj : " block in sample code)
for variable/attribute examples, child function get_nas_server(self) utilize "nas_server" variable variants in common set of code. subtracting get_ function name reveals base of variable name used in common set of code. example variables names , object attributes derived "get_nas_server" function name:
nas_server
nas_server.json
self.nas_server (attribute)
here common code 1 of functions:
#################################################################### def get_nas_server(self): #################################################################### """\ngets command nas_server , places data self.nas_server""" try: self.nas_server return self.nas_server except attributeerror: pass self.get_file_cmd('nas_server') jobj = self.fresh_json('nas_server.json') if jobj : self.nas_server = jobj return self.nas_server self.get_file_cmd('get_nas_server')
everything below code above in function specific function purpose , not appropriate discussion here. trying make code above reusable in functions, code has have variables , attribute changed depending on function name.
thanks reading if got far , help.
seems define helper method in parent class:
class parent(object): def _get_something(name): try: return getattr(self, name) except attributeerror: pass self.get_file_cmd(name) jobj = self.fresh_json(name+'.json') if jobj : setattr(self, name, jobj) return jobj self.get_file_cmd('get_'+name)
as snippet demonstrates, can use getattr()
, setattr()
, hasattr()
functions reference object attributes name.
Comments
Post a Comment