1

Given methods:

def foo(bar):
    bar.buzz()
    bar.blep()

def bla(bee):
    bee.buzz()

Now, we know that bar has to have buzz and blep methods. But the clients of the code does not know that unless they open the implementation and read through it (which can be easy in this example but can be tricky in the real world).

One solution is to define an ABC, like so:

def BuzzBlepable(ABC):
    @abstractmethod
    def buzz():
        pass

    @abstractmethod
    def blep():
        pass

Now we can have the code:

def foo(bar: BuzzBlepable):
    bar.buzz()
    bar.blep()

def bla(bee: BuzzBlepable):
    bee.buzz()

The problem with this is that bla method doesn't really need the bee parameter to implement blep method, but we will be forcing the client to do so anyway. This begs a question, is there any good practice to tell the client which interface the parameter has to conform to? Like, auto-generated method documentation or something? Has anyone any ideas?

Arsen Simonean
  • 362
  • 2
  • 17

1 Answers1

2

This begs a question, is there any good practice to tell the client which interface the parameter has to conform to? Like, auto-generated method documentation or something?

I think you want to use docstrings. Docstrings can be used to describes modules, classes and methods. So you could describe the type of parameter the functions expects in a docstring and then describe the methods of a class in the docstring of this class. There are a couple of different sytles for docstrings, you can find a discussion on them here.

Using the google style, you could do something like this:

def foo(param1):
    """
    Description of the method

    Args:
        param1: Description of the param 

    """

The user can then use either foo.__doc__ or help(foo) to see the documentation. IDEs like PyCharm also have the ability to generate this docstring automatically. Alternatively, you can use tools like Pyment to automatically generate your docstrings.

Nils Schlüter
  • 1,418
  • 1
  • 19
  • 30
  • Thx for the Pyment suggestion, reading about it now. I think it is possible to automate it into creating the doctrings on every build. Although this wouldn't really solve the interface issue. – Arsen Simonean Feb 04 '18 at 12:06