2

I have I small module that I use inside one of my projects. Now I decided to place it on github so now I am writing some docstrings and cleaning the code.

I have a composition of 2 classes so the initialization looks like this:

foo = Class_1()
bar = Class_2(param1=foo)

I know that the first argument to the Class_2 has to be an instance of Class_1 or the code won't work. But it may be clear only for me as I wrote code of Class_2, but when using module as API it may be unclear for a user that param1 has to be an instance of Class_1. If someone will use bar = Class_2(param1='foo'). The trackback will be bad and it will be impossible to understand what happened. So the question is: do I need to check in my __init__ that isinstance(param1, Class_1) and if no raise an excaption with an appropriate message, or writing good documentation is enough?

pythad
  • 3,968
  • 1
  • 13
  • 39
  • 1
    Since at least X% of your users won't read the documentation, and since good code should be both self-documenting and prevent users from wrong usage - it's much preferable to change your algorithm to prevent *known* bugs. We have enough *unknown* bugs to worry of. – boardrider Jun 04 '17 at 09:12

1 Answers1

0

This is very opinion-based (not great for StackOverflow in particular) - but in my opinion, you should do both.

On the one hand, using isinstance() and exception-handling are both good defensive-coding practices.

On the other hand, inline documentation is nice. Per the Python developer guide:

The markup used for the Python documentation is reStructuredText, developed by the docutils project, amended by custom directives and using a toolset named Sphinx to post-process the HTML output.

Some IDEs, such as JetBrains PyCharm, are configured to automatically pick up well-formed reST docstrings and perform automated type-checking based on those conventions (which I've found to be really useful). See also: PEP 257 and What is the standard Python docstring format? for details.

alex
  • 4,689
  • 8
  • 43
  • 83