[Python-ideas] __getattr__ bouncer for modules

Chris Angelico rosuav at gmail.com
Sat Apr 16 23:47:08 EDT 2016


On Sun, Apr 17, 2016 at 1:40 PM, Nathaniel Smith <njs at pobox.com> wrote:
> However, starting in 3.5 cpython allows __class__ assignment on
> modules, so you can implement custom __getattr__ on a module with:
>
>   class ModuleWithMyGetattr(types.ModuleType):
>       def __getattr__(self, name):
>           # .. whatever you want ...
>
>   sys.modules[__name__].__class__ = ModuleWithMyGetattr
>
> The advantage of doing it this way is that you can also implement
> other things like __dir__ (so tab completion on your new attributes
> will work).
>

Oooh! I did not know that. That's pretty much what I was thinking of -
you can have the class in the module that it's affecting. Coolness!

And inside that class, you can toss in @property and everything, so
it's exactly as clean as it wants to be. I like! Thanks Nathaniel.

ChrisA


More information about the Python-ideas mailing list