Python Function Links

I am trying to make fun of a function and beautify its behavior. To do this, I need to get the original behavior of the function, save it and add it to the transfer function. It should look like this:

@classmethod
def setUpClass(cls):
    def wrap_function(arg):
        return "potato" + original_function(arg)

    package.original_function = Mock(wraps= wrap_function)

This code works, but none of the following does.

1)

@classmethod
def setUpClass(cls):
    def wrap_function(arg):
        return "potato" + package.original_function(arg)

    original_function = Mock(wraps= wrap_function)

2)

@classmethod
def setUpClass(cls):
    def wrap_function(arg):
        return "potato" + package.original_function(arg)

    package.original_function = Mock(wraps= wrap_function)

3)

@classmethod
def setUpClass(cls):
    def wrap_function(arg):
        return "potato" + original_function(arg)

    original_function = Mock(wraps= wrap_function)

I imported as

import package
from package import original_function

Can someone explain to me why the first one works and the rest does not?

+4
source share
1 answer

Why does the first one work?

This works because you deactivate the function at the module level, and this modified value will remain until the module remains at sys.modules.

Basically, when you do:

from package import original_function

original_function , - :

package.original_function = 1

, original_function 1, , original_function .

?

  • original_function = Mock(wraps= wrap_function) package.original_function, original_function.

  • package.original_function = Mock(wraps= wrap_function): , , , wrap_function.

  • original_function = Mock(wraps= wrap_function): , 1, , wrap_function, .

+2

Source: https://habr.com/ru/post/1685670/


All Articles