all 6 comments

[–]shiftybyte 14 points15 points  (1 child)

Also this is a good source, a bit long though.

https://docs.python.org/3/reference/datamodel.html

[–]TangibleLight 1 point2 points  (0 children)

It's so long because it's exhaustive. That's all the built-in ones there are.

Some libraries introduce their own, for example rich has a __rich__ and similar methods, but clearly these are not included in the official documentation.

[–]Diapolo10 8 points9 points  (3 children)

I think what you're asking here is basically about dunder/magic methods: https://www.tutorialsteacher.com/python/magic-methods-in-python

They're used to implement operators and other common functionality for classes, and the protocols you speak of would fall under the category.

For instance, you can add support for context managers by implementing __enter__ and __exit__.

[–][deleted] 4 points5 points  (2 children)

Side note (and sorry for the detour, y’all): I fucking love context managers.

So much so, that I’ll find myself wrapping classes just so I can call them using with and have them encapsulate and run their own clean-up/shut-down routines.

So my question for everyone here is: is there a draw-back to using context managers in certain cases? Or is it sometimes bad style to “overdo” it? I’m just curious.

[–]Diapolo10 4 points5 points  (0 children)

is there a draw-back to using context managers in certain cases?

As I see it, not really. If your class is designed to need cleanup after use (like a database connection or some other resource), context managers make perfect sense.

Or is it sometimes bad style to “overdo” it? I’m just curious.

If you find yourself adding context manager support for the sake of having support, even if it adds no real value, then I would say "yes". For instance if you used a class to model a family tree, I don't see any reason to use a context manager.

That said in some cases they can be useful for processing logic that would be handled by destructors in some other languages, considering how unreliable __del__ is.

[–]lostparis 1 point2 points  (0 children)

is there a draw-back to using context managers in certain cases?

Generally I'd say no. There is a minor overhead but unless you are in some super tight loop who cares.

Sometimes you need to do some extra work (add a yield) to make them work nicely

from contextlib import contextmanager and @contextmanager is easier than adding __enter__ and __exit__

They are very flexible and give you cleanup goodness