The Python Oracle

Is there a way to define the docstring for a python object that defines __call__?

--------------------------------------------------
Rise to the top 3% as a developer or hire one of them at Toptal: https://topt.al/25cXVn
--------------------------------------------------

Music by Eric Matyas
https://www.soundimage.org
Track title: Puzzle Game 5 Looping

--

Chapters
00:00 Is There A Way To Define The Docstring For A Python Object That Defines __call__?
00:42 Accepted Answer Score 6
01:29 Thank you

--

Full question
https://stackoverflow.com/questions/3295...

--

Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...

--

Tags
#python #callable

#avk47



ACCEPTED ANSWER

Score 6


What you want is not doable no. The help() information (and inspect information, etc.) will show it as a class with a __call__ method, not a function.

If the object you produce doesn't have to support anything other than calling, you could use a closure to return an actual function:

def produce_callable(*args, **kw):
    instance = YourClass(*args, **kw)
    def callable_function(*args, **kw):
        """Docstring here"""
        return instance(*args, **kw)
    return callable_function

So rather than return your custom class instance, you return a wrapper function that'll call the class instance. help() information will be given for that function.

I used the *args and **kw wildcard arguments in the callable_function() signature, but if you know what arguments are accepted by the __call__ method, you can hard-code those in the function you produce.