Question

Python supports a lot of magic methods for implementing custom functionality in objects, such as __lt__, __getattr__, etc. There are even magic methods that affect the way certain built-in functions perform, such as __len__ and __instancecheck__. But are there magic methods for all the built-in functions in python?

For example, if I wanted to change the way the any function would perform on a certain class, could I specify an __any__ magic method in that class? If that isn't an option, is there any way that I could specifically affect the way any applies to that class? (I realize that if I wanted special functionality for the way any receives the items from the iterable I could define __iter__, but that's not what I am looking to do)

Note that my desire to implement custom functionality for any is just an example, I don't explicitly want to define custom functionality for any.

Was it helpful?

Solution

The special method's let you hook into concepts, not so much built-in functions or other things.

__len__ is a container length, not specifically a hook for the len() function. It just happens that the len() function is the visible API for that functionality.

any() expects an iterable argument, the concept you are looking for here is the Iterator type methods; it's not the function that is hooked, it is that concept.

You may want to study the default type abstract base classes to see what methods Python types implement; here many special methods are grouped together in a readable overview.

OTHER TIPS

No, only for lots of them, as practicality demands.

(Specifically for __any__, it has been discussed before, but ultimately, it wasn't considered to be needed.)

No. The list of special methods a class can implement are documented in section 3.3.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top