Empty class with comment same as pass?

No, they're not equivalent.

Since the implementation of PEP 257, if the first expression in a module, function, or class is a string, that string will be assigned to that module/function/class's __doc__ attribute:

A docstring is a string literal that occurs as the first statement in a module, function, class, or method definition. Such a docstring becomes the __doc__ special attribute of that object.

Functionally, the classes are equivalent. However, the difference between having a docstring and not having a docstring can surface when you're creating documentation for your code. Tools like sphinx-autodoc can pick up the docstring and generate documentation for your class, and you'll end up with something like this in your documentation:

class Empty()

This class intentionally left blank

For this reason, it's generally preferable not to use a docstring for this kind of thing. Instead, it would be better to use a comment:

class Empty:
    pass  # This class intentionally left blank

Your two codes are almost equivalent, but not quite. pass is just a no-op. The docstring is almost a no-op as well, but it adds a __doc__ attribute to your class object, so there is a small difference.

A version that would be functionally equivalent to using pass would be to use Ellipsis a.k.a. ...:

class Empty: ...

There is nothing special about ... in this case. Any pre-existing object that you don't assign will work just as well. For example, you could replace ... with None, 1, True, etc. The choice of ... is a popular alternative because it is much more aesthetically pleasing. By convention, it means a stub that is to be filled in, while pass usually indicates a deliberate no-op.

Using ... like that will raise a SyntaxError in Python 2. You can use the named Ellipsis object instead, but that is not nearly as pretty.

You may also find this question about the equivalence of pass and return None in functions interesting.

Tags:

Python