Search code examples
pythonfunctionargumentsdecorator

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


so, i want to write a decorator that takes in a function and based on that function arguments decides wether or not to do something.

the idea is that with this decorator the functions supports an input like this:

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

and an input like this:

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

Solution

  • You can use myFunction(*args, **kwargs) in the decorator function and write the decorator function like that: def decorator(func, *args, **kwargs)

    In your case it would by similar to this:

    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