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

1
  • 1
    Look for decorators , those are intended as function wrappers Commented Jul 19, 2018 at 12:24

2 Answers 2

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

Sign up to request clarification or add additional context in comments.

1 Comment

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.
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()

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.