logoalt Hacker News

notepad0x9004/21/20251 replyview on HN

outside of __init__, I thought it wasn't the pythonic way to directly invoke double underscore functions like closure? I recall reading that you should implement a class that overrides/implements such functions instead? I get why the author might be doing it this way to describe the topic of the post, but would calling __closure__() be acceptable in production code?


Replies

zahlman04/22/2025

First, `__closure__` is a plain data attribute, not a function. It isn't callable, and isn't being "called" here.

Further, in the cases you're talking about, the functions specifically are methods which you can implement in your own class. But you aren't doing this in order to avoid calling them directly; rather, you're doing them to implement functionality for that class (i.e., there's some other bit of syntax already which will call it indirectly for you). And `__init__` isn't much of an exception; normally you only call it explicitly where necessary for subclassing (because the corresponding syntax would create a separate base class instance instead of initializing the current base).

But the point here is to inspect an implementation detail, for pedagogical purposes. There isn't a better way to do it in this case, exactly because you aren't ordinarily supposed to care about that detail. There's no question about whether you'd inspect an object's `__closure__` directly in production code - because not only is there no alternative, but it would be extremely rare to have any reason to do so.

show 1 reply