Question

I have this function and a decorator @decorator(integer)

def spam():
    return "ABCD EFG"

def decorator(number):
    def inside(function):
        *do something*
        return *somthing of type string*
    return inside

I want to make the decorator return FUNCTION, accepts integer and replaces every letter with the letter comming in number places afterwards. For example

@decorator(3)
def spam():
    return "ABCD EFG"

and

>>> print(spam())
"DEFG HIJ"
  • How do i make the decorator return a function and not a string ?
Was it helpful?

Solution

in order to define a decorator:

def decorator(number):
    def inner(f):
        def decorator_f(*args, **kwargs):
            result = f(*args, **kwargs)
            #make some manipulation on result
            return result
        return decorator_f
    return inner

Then you can use it like:

@decorator(3)
def spam():
    return "ABCD EFG"

OTHER TIPS

Why not just use normal methods:

def spam(number):
    s = "ABCD EFG"
    return ''.join(chr(ord(x)+number) if x.isalpha() else x for x in s)

If you have to use decorators, implement them as @Udy has shown and the line that I have provided above is how you can return the shifted values.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top