0
votes

I am reading about decorators and have learned quite a bit from Simeons blog I had success before when there was no arguments passed in the function like this: decorator(func). I think my issue is decorator(func(args)). I think my issue is func(args) is executing and passing its return value to the decorator instead of the function itself. How can I pass a function & argument in a decorator (example B) and not use the @decorator_name 'decoration' style (example A).

Edit: I would like example B to produce the same result as example A.

user_input = input("Type what you want:  ")

def camel_case(func):
   def _decorator(arg):
      s = ""
      words = arg.split()
      word_count = len(words)
      for i in range(word_count):
         if i >0:
            s += words[i].title()
         else:
            s += words[i].lower()
      return func(s)
   return _decorator

Example A: This works

@camel_case
def read(text):
   print("\n" + text" )

read(user_input)

Example B: This does not work

def read(text):
   print("\n" + text" )

camel_case(read(user_input))
2
What are you trying to achieve? - Lev Levitsky
What you should do: camel_case(read)(user_input) - Moses Koledoye
Just edited the question. I would like both example B to produce the same result as example A. - Michael Bruce

2 Answers

2
votes

THe decorator takes a function: camel_case(read). If you're trying to apply camel_case to the read(user_input) function, try this:

camel_case(read)(user_input)

camel_case(read) returns the decorated function, which you then call with (user_input).

0
votes

Give the function to the decorator as an argument; the decorator returns a new function; then call this returned function with user_input as an argument:

camel_case(read)(user_input)