Search code examples
pythondockeroverridingpython-3.7super

Override method of nested class from method-created class instance


I'm using the Python Docker SDK to send commands to my local docker installation.

client = docker.from_env()
client.images.pull(repository=MY_IMAGE, tag="master")

What I would like to do is override the .pull method so I can add an option so it doesn't pull in some cases.

The easy way would be to add an if-statement before each .pull

enable_pull=True

if enable_pull:
    client.images.pull(...)
else:
    pass

... but I would like to leave the code as-is and just override the method somehow. I'd know how to do it for a "normal" configuration - for example overriding from_env() would be easy:

class MyClass(docker):
    def from_env(self, *args, **kwargs):
        # my code
        return super().from_env()

But how I don't know how I would override .pull since it is a method of .images.


Solution

  • You have a bit of a train-wreck here: (amplified to make a point)

    docker.from_env().images.pull(repository=MY_IMAGE, tag="master")
    

    So something like this should be hidden inside one of your own methods:

    def pull(self, *args, **kwargs):
        docker.from_env().images.pull(*args, **kwargs)
    

    and called like this:

    self.pull(repository=MY_IMAGE, tag="master")
    

    but you wanted an enable/disable, so:

    def pull(self, *args, **kwargs):
        if self.enable_pull:
            docker.from_env().images.pull(*args, **kwargs)