Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

I have a class that defines a __call__, but the when the user sees requests help for this "function" on the help return, they get the entire object and methods and it can be a bit daunting...I would like the help to look more like a function's help if possible.

I followed the trail in to the inspect module, but it seems that since I cannot inherit from function type and/or method type, then this may not be doable. Am I missing something or do I have to re-arrange the code such that I am dynamically building a true Python function object?

like image 618
KevinP Avatar asked Oct 05 '15 14:10

KevinP


1 Answers

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.

like image 89
Martijn Pieters Avatar answered Sep 21 '22 16:09

Martijn Pieters