Search code examples
pythonmethodscallmagic-methods

Python __call__ special method practical example


I know that __call__ method in a class is triggered when the instance of a class is called. However, I have no idea when I can use this special method, because one can simply create a new method and perform the same operation done in __call__ method and instead of calling the instance, you can call the method.

I would really appreciate it if someone gives me a practical usage of this special method.


Solution

  • Django forms module uses __call__ method nicely to implement a consistent API for form validation. You can write your own validator for a form in Django as a function.

    def custom_validator(value):
        #your validation logic
    

    Django has some default built-in validators such as email validators, url validators etc., which broadly fall under the umbrella of RegEx validators. To implement these cleanly, Django resorts to callable classes (instead of functions). It implements default Regex Validation logic in a RegexValidator and then extends these classes for other validations.

    class RegexValidator(object):
        def __call__(self, value):
            # validation logic
    
    class URLValidator(RegexValidator):
        def __call__(self, value):
            super(URLValidator, self).__call__(value)
            #additional logic
    
    class EmailValidator(RegexValidator):
        # some logic
    

    Now both your custom function and built-in EmailValidator can be called with the same syntax.

    for v in [custom_validator, EmailValidator()]:
        v(value) # <-----
    

    As you can see, this implementation in Django is similar to what others have explained in their answers below. Can this be implemented in any other way? You could, but IMHO it will not be as readable or as easily extensible for a big framework like Django.