Question

Consider the following code Here I have not used the @ symbol for decoration

import math

def isOddMy(func):
    def innerOdd(x):
        y = func(x)
        if math.fmod(y, 2) == 0 :
            return 0
        else:
            if y is not None:
                return y
            else:
                return 0
    return innerOdd

#@isOddMy
def fib(n):
    #print n,
    if n == 0 :
        return 0
    elif n == 1 :
        return 1
    else:
        return fib(n-2) + fib(n-1)


def main():
    #oddFibi = isOdd(fib)
    #print [i for i in oddFibi(100)]
    for i in range(1,10):
        print fib(i),

    print
    fib1 = isOddMy(fib)
    for i in range(1,10):
        print fib1(i),

if __name__ == '__main__':
    main()

and the result is

1 1 2 3 5 8 13 21 34

1 1 0 3 5 0 13 21 0

whereas below i have used @ symbol but the result is 1 1 0 1 1 0 1 1 0

Why is this so??

import math

def isOddMy(func):
    def innerOdd(x):
        y = func(x)
        if math.fmod(y, 2) == 0 :
            return 0
        else:
            if y is not None:
                return y
            else:
                return 0
    return innerOdd

@isOddMy
def fib(n):
    #print n,
    if n == 0 :
        return 0
    elif n == 1 :
        return 1
    else:
        return fib(n-2) + fib(n-1)


def main():
    #oddFibi = isOdd(fib)
    #print [i for i in oddFibi(100)]
    for i in range(1,10):
        print fib(i),

    '''print
    fib1 = isOddMy(fib)
    for i in range(1,10):
        print fib1(i),'''

if __name__ == '__main__':
    main()

Thanks.

Was it helpful?

Solution

The difference is probably to do with the recursive call. When fib calls fib, that name is looked up in module scope. If you use the @ decorator syntax, the decorated function is found with name fib. If you just do fib1 = isOddMy(fib), the undecorated function is found with name fib.

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