Search code examples
pythoncpython

Is there a point to setting __all__ and then using leading underscores anyway?


I've been reading through the source for the cpython HTTP package for fun and profit, and noticed that in server.py they have the __all__ variable set but also use a leading underscore for the function _quote_html(html).

Isn't this redundant? Don't both serve to limit what's imported by from HTTP import *?

Why do they do both?


Solution

  • Aside from the "private-by-convention" functions with _leading_underscores, there are:

    • Quite a few imported names;
    • Four class names;
    • Three function names without leading underscores;
    • Two string "constants"; and
    • One local variable (nobody).

    If __all__ wasn't defined to cover only the classes, all of these would also be added to your namespace by a wildcard from server import *.

    Yes, you could just use one method or the other, but I think the leading underscore is a stronger sign than the exclusion from __all__; the latter says "you probably won't need this often", the former says "keep out unless you know what you're doing". They both have their place.