制作一个装饰器,可以访问在 python 中作为输入的函数的参数

making a decorator that can access the arguments of the function that is taking as input in python

所以,我想编写一个装饰器,它接受一个函数,并根据该函数参数决定是否做某事。

想法是使用这个装饰器,函数支持这样的输入:

myFunction("a", "b", "c")

和这样的输入:

myFunction(["a", "b", "c"])


def accept_list_input(function):
   def wrapper(function):
      try:
         function()
      except typeError:
      # (function's argument that i don't know how to access)= function's argument that i don't know how to access[0]

   return wrapper


@accept_list_input
def myFunction(*arguments):
   #stuff

你可以在装饰器函数中使用myFunction(*args, **kwargs),这样编写装饰器函数:def decorator(func, *args, **kwargs)

在你的情况下,它会类似于:

myFunction(["a", "b", "c"])


def accept_list_input(function):
   def wrapper(*args, **kwargs):
      try:
         function(*args, **kwargs)
      except typeError:
      # (function's argument that i don't know how to access)= function's argument that i don't know how to access[0]

   return wrapper


@accept_list_input
def myFunction():
   #stuff

这就是我到目前为止的想法:

def accept_list_input(func, *args, **kwargs):
  def wrapper(func):
    try:
      func(args)
    except TypeError:
      for arg in args:
        if type(arg)== tuple:
          arg= arg[0]
        func(arg)
  return wrapper

更清晰的问题:

我再举一个例子,因为我知道这个问题不是最好的:

def add_numbers(*integer_numbers):
    sum= 0
    for integer in integer_numbers:
        sum+= integer
    return sum

# this is not the real method i am struggling on in my project, it's an example
# the function above takes an input formatted like this:
# add_numbers(1, 2, 3, 4, 5)
# i want the function to support both add_numbers(1, 2, 3, 4, 5) and add_numbers([1, 2, 3, 4, 5])


def accept_list_input(a_function, *args):
    def wrapper(func, args):
        try:
            a_function(args)
        except TypeError:
            for argument in args:
                if type(argument)== tuple:
                    argument= argument[0]
                    break
            a_function(args)
    return wrapper(a_function, args)