meaning of `__all__` inside Python class

Question:

I am aware of the use of __all__ at module scope. However I came across the usage of __all__ inside classes. This is done e.g. in the Python standardlib:

class re(metaclass=_DeprecatedType):
    """Wrapper namespace for re type aliases."""

    __all__ = ['Pattern', 'Match']
    Pattern = Pattern
    Match = Match

What does __all__ achieve in this context?

Asked By: maxbachmann

||

Answers:

The typing module does some unorthodox things to patch existing modules (like re). Basically, the built-in module re is being replaced with this class re defined using a custom metaclass that intercepts attribute lookups on the underlying object. __all__ doesn’t really have any special meaning to the class (it’s just another class attribute), but it effectively becomes the __all__ attribute of the re module. It’s the metaclass’s definition of __getattribute__ that accomplishes this.

Answered By: chepner
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.