2

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.

3
  • 1
    No, there are plenty of built-in functions where hooking makes no sense. chr() for example, or id(). Commented Feb 15, 2014 at 18:34
  • @MartijnPieters, It makes a decent bit of sense for chr, if you were making your own number type you wanted to be used wherever an int can be used. Commented Feb 15, 2014 at 18:45
  • @MikeGraham Actually, that can be done by defining __int__, which is much more appropriate for that purpose. Commented Feb 15, 2014 at 19:19

3 Answers 3

4

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.

Sign up to request clarification or add additional context in comments.

2 Comments

"any() expects an *iterator argument" No, any expects an iterable argument.
@MikeGraham: indeed, iter() is called on it, so a iterable is enough. For some reason I still use the terms interchangeable but there is a difference that I should pay attention to more..
1

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.)

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.