1

I can figure out the behaviour of python. Here is code example:

def foo():
    print('hello from initial foo')
def using_foo():
    foo()
def wrapper(func):
    def foo():
        print('Now is overload foo')
    print('Hello from wrapper')
    func()
using_foo()
wrapper(using_foo)

This will print:

hello from initial foo

Hello from wrapper

hello from initial foo

But I expect:

hello from initial foo

Hello from wrapper

Now is overload foo

Because next one works fine:

def foo():                                                                         
    print('Hello from initial foo')                                                
def using_foo():                                                                   
    foo()                                                                          
using_foo()                                                                        
if True:                                                                           
    def foo():                                                                     
        print('now it is overload foo')                                            
    using_foo()

Output:

Hello from initial foo

now it is overload foo

2 Answers2

1

You just mistyped func() instead of foo():

def foo():
    print('hello from initial foo')
def using_foo():
    foo()
def wrapper(func):
    def foo():
        print('Now is overload foo')
    print('Hello from wrapper')
    foo()
using_foo()
wrapper(using_foo)

output:

hello from initial foo
Hello from wrapper
Now is overload foo

DDS
  • 2,340
  • 16
  • 34
  • in using_foo() (which to be mentioned inside wrapper as func()), i use foo(), but it seems that redefinition of foo() inside wrapper() namespace has no influence on func definition. – D.Shaulskii Jul 19 '18 at 16:47
0

You can also return your inner function and call it from outside. For your current example, it might be an overkill. But this technique will surely be helpful when you get deeper into decorators.

def foo():
    print('hello from initial foo')
def using_foo():
    foo()
def wrapper(func):
    def foo():
        print('Now is overload foo')
    print('Hello from wrapper')
    return foo
using_foo()
call_inner_foo = wrapper(using_foo)
call_inner_foo()
sjaymj62
  • 386
  • 2
  • 18