Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can we design any function using a decorator?

During my interview they asked me a implement a function to reverse each word in a sentence and create final sentence from it. For example:

s = 'my life is beautiful'
output - `ym efil si lufituaeb` 

I know the question is pretty simple so solved it in few minutes:

s = 'my life is beautiful'

def reverse_sentence(s):

    string_reverse = []

    for i in s.split():
        string_reverse.append("".join(list((reversed(i)))))

    print " ".join(string_reverse)

reverse_sentence(s)

Then they asked to implement the same function using a decorator, and I got confused here. I know the basics of decorator how it used, and when it used. They didn't mention what part of the function they want to wrap using decorator. They told me to implement this using args and kwargs, and I was not able to solve it. Could anyone help me here? How can I convert any function into decorator?

As my per knowledge, you use decorator when you want to wrap your function or you want to modify the some functionality. Is my understanding correct?

like image 387
python Avatar asked Dec 28 '25 18:12

python


2 Answers

def reverse_sentence(fn): # a decorator accepts a function as its argument
    def __inner(s,*args,**kwargs): #it will return this modified function
       string_reverse = []
       for i in s.split():
           string_reverse.append("".join(list((reversed(i)))))          
       return fn(" ".join(string_reverse),*args,**kwargs) 
    return __inner # return the modified function which does your string reverse on its first argument

I guess...

@reverse_sentence
def printer(s):
    print(s)

printer("hello world")
like image 163
Joran Beasley Avatar answered Dec 30 '25 07:12

Joran Beasley


Here is a different take -- it defines a decorator which takes a function which sends strings to strings and returns another function which maps the passed function over a split string and then rejoins:

def string_map(f): #accepts a function on strings, splits the string, maps the function, then rejoins
    def __f(s,*args,**kwargs):    
       return " ".join(f(t,*args,**kwargs) for t in s.split()) 
    return __f

@string_map
def reverse_string(s):
    return s[::-1]

typical output:

>>> reverse_string("Hello World")
'olleH dlroW'
like image 32
John Coleman Avatar answered Dec 30 '25 06:12

John Coleman



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!