Search code examples
pythonpydoc

__doc__ in python and using help() on a class


I recently went to an interview and did some little programming test where they had a simple two class script that would calculate the area, side length, etc.. Of a shape it looked something like this:

class Shape(object):

    def __init__(self, side1, side2, side3, side4):
        self.side1 = side1
        ...

    @abstractmethod
    def calc_area(self):
        pass

class Triangle(Shape):

    def calc_area(self):
        ... etc..

One of the questions they asked me was, if we ran help(Shape(3, 5, 5, 6)) what would happen assuming all objects have been initialized? my answer was, nothing because there's no docstring or __doc__. It appears that I was marked down on this answer and I can't seem to understand why? Was I incorrect in thinking that nothing would happen when running help()?


Solution

  • If you look at the source of pydoc.Helper class (especially its help() method), which is essentially what you get when you call help(), you'll see that it will still get the basic structure of your object using the inspect module and a couple of other tricks.

    The goal being, of course, to provide at least object/function signature to other developers if the original code writers didn't bother with writing the docs. Personally, I don't see the reason of help() existing in the global namespace anyway, but I understand why they've placed it both from a historical and philosophical perspective.

    That being said, whoever interviewed you was, IMO, a jerk - this doesn't really have to do much with programming but with nitpicking which is, may I say, quite un-Pythonic. That is, assuming that they weren't trying to get you on the @abstractmethod descriptor, of course, which might be a valid question.