1

I need to extend an external class to my (It's a class of a package from PyPI).

This class has a method which define a function inside it:

class MyClass(object):
    def mymethod(self, *args, **kwargs):
        def aux_function(self, params):
            # Do something

        # Do something and call aux_function

I want to override the aux_function inside the instance method but I want to keep the rest of the code inside the method.

Is there any way to override the function inside the method and use super() to run the code from the original class?

Garet
  • 365
  • 2
  • 13
  • take a look over the inspect module you may find something to play with: https://docs.python.org/2/library/inspect.html – Netwave Nov 05 '15 at 08:54

1 Answers1

2

There is no way to do this, no. aux_function() is a local variable inside mymethod(), nothing more, you cannot override it in a subclass. You'll have to redefine the whole method in the subclass.

You can patch that function, see Can you patch *just* a nested function with closure, or must the whole outer function be repeated?, but that's not quite the same thing.

Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
  • Yes, I know the concept of monkeypatch. I asked it thinking about could be any obscure way to do it. – Garet Nov 03 '15 at 19:51
  • Of course this is a design problem. I'll try to do a pull request putting away the aux_function as an instance method to be easily "overwritable": def _aux_function(self, ...) – Garet Nov 03 '15 at 19:54
  • @Garet: yes, moving the nested function *out* of the method into its own method would make this whole problem neatly go away. – Martijn Pieters Nov 03 '15 at 19:55