decorating a method in python -


i making little wrapper module public library, library has lot of repetition, after object creation, maybe methods require same data elements.

i have pass same data in wrapper class, don't want pass same thing on , over. store data in wrapper class , apply if not included in method. if things hairy down road, want method arguments overwrite class defaults. here code snippet illustrates goals.

class stackoverflow():     def __init__(self,**kwargs):         self.gen_args = {}         #optionally add repeated element object          if 'index' in kwargs:             self.gen_args['index'] = kwargs['index']         if 'doc_type' in kwargs:             self.gen_args['doc_type'] = kwargs['doc_type']      #this problem             def gen_args(fn):         def inner(self,*args,**kwargs):             kwargs.update(self.gen_args)             return fn(*args,**kwargs)         return inner      #there bunch of these do_stuffs require index , doc_type     @gen_args     def do_stuff(self,**kwargs):         print(kwargs['index'])         print(kwargs['doc_type'])  #just send arguments method print("case a")         = stackoverflow() a.do_stuff(index=1,doc_type=2)  #add them class , have methods use them without having specify  #them each time print("case b")   b = stackoverflow(index=1,doc_type=2) b.do_stuff()  #the arguments specified in method should overwrite class values print("case c")   c = stackoverflow(index=1,doc_type=2) c.do_stuff(index=3,doc_type=4) 

edit:

so question is, how fix gen_args or there better way this? specific error code is: return fn(*args,**kwargs) typeerror: do_stuff() missing 1 required positional argument: 'self'

i might use definition of inner:

    def inner(self,*args,**kwargs):         return fn(self, *args,**dict(self.gen_args, **kwargs)) 

notes:

  • this version provides self, missing in version.
  • this gives priority passed-in kwargs.

Popular posts from this blog

c# - ODP.NET Oracle.ManagedDataAccess causes ORA-12537 network session end of file -

matlab - Compression and Decompression of ECG Signal using HUFFMAN ALGORITHM -

utf 8 - split utf-8 string into bytes in python -