Python Decorator重新创建Locals()

时间:2015-06-29 18:47:42

标签: python python-decorators

我的一些函数使用“fail_silently”标志。它按以下方式使用:

def test(a, b, c=1, fail_silently = False)
    try:
        return int(a) + c
    except:
       if fail_silently:
           return None
       raise

因此,如果出现错误,我们会抓住它并优雅地失败。这里的关键是它可以被任何调用它的人动态切换。

我将它用于许多不同的函数和类方法,并认为它是装饰器。

有一些问题:

  1. 我希望能够将标志命名为“raise_exception”或“fail_silently”或“其他”......
  2. 该标志可能有也可能没有默认值
  3. 该旗帜可能会或可能不会传入(通常不会)
  4. 它也需要使用类方法
  5. 因此我的装饰者需要寻找(假设该标志被称为“fail_silently”) 按此顺序在以下位置的标志

    1. ** kwargs(传入函数参数),简单字典get on flag
    2. * args - 获取标志的位置参数,然后扫描args中的索引(可能不存在)
    3. 从函数
    4. 获取标志的默认值

      问题是代码现在变得非常混乱并且有许多失败点。

      def try_except_response(parameter = 'fail_silently'):
          def real_decorator(func):
              @functools.wraps(func)
              def wrapper(*args, **kwargs):
                  try:
                      return func(*args, **kwargs) # the function itself, 
                  except: # if it raises an Exception!
                      # check to see if the Flag is in passed in kwargs!
                      if kwargs.get(parameter)== True: 
                          return None
                      elif kwargs.get(parameter) == False:
                          raise
                      else:
                          # Flag is not in kwargs, check to see if it is in args
                          function_args, vargs, kewords, defaults = inspect.getargspec(func) # get the index of argument of interest
                          try:
                              argument_index = function_args.index(parameter)  # get the index of argument of interest
                          except ValueError:
                              raise ValueError('The inputted decorator for "fail_silently" was not found!  The behavior will not work.')
      
                          if len(args) > argument_index: # check to see if it is inputted
      
                              keyword = args[argument_index] # get the value!!
                              if keyword == True: 
                                  return None
                              elif kwargs == False:
                                  raise
                              else:
                                  raise ValueError('The "fail_silently" flag did not return a value that we understand.  Must be True or False')
      
                          else:
                              # not in args either! let's go get the default value.
                              # TODO MORE STUFF!!!
                              raise
                          raise
                      raise
              return wrapper
      

      清理它的最佳方法是什么?还是替代品?我正在考虑实现一个版本的locals(),它将创建一个传递给函数的所有参数的字典,然后从那里检查......

0 个答案:

没有答案
相关问题