[Python-Dev] Updated PEP 362 (Function Signature Object)

Yury Selivanov yselivanov.ml at gmail.com
Wed Jun 6 16:20:32 CEST 2012


On 2012-06-06, at 2:48 AM, Nick Coghlan wrote:
> However, looking at the code, I think the split that makes sense is
> for a lower level functools.signature to *only* support real function
> objects (i.e. not even method objects).
> 
> At the inspect layer, inspect.signature could then support retrieving
> a signature for an arbitrary callable roughly as follows:
> 
>    def signature(f):
>        try:
>            # Real functions are handled directly by functools
>            return functools.signature(f)
>        except TypeError:
>            pass
>        # Not a function object, handle other kinds of callable
>        if isclass(f):
>            # Figure out a Signature based on f.__new__ and f.__init__
>            # Complain if the signatures are contradictory
>            # Account for the permissive behaviour of object.__new__
> and object.__init__
>            return class_signature
>        if ismethod(f):
>                f = f.__func__
>        elif not isfunction(f):
>                try:
>                    f = f.__call__
>                except AttributeError:
>                    pass
>        return signature(f) # Use recursion for the initial
> implementation sketch
> 
> That code is almost certainly wrong, but it should be enough to give
> the general idea. The short version is:
> 
> 1. Provide a functools.signature that expects ordinary function
> objects (or objects with a __signature__ attribute)
> 2. Provide an inspect.signature that also handles other kinds of callable

I like the idea of making 'signature' capable of introspecting any callable, 
be it a class, an object with __call__, a method, or a function.

However, I don't think we should have two 'signature'-related mechanisms 
available in two separate modules.  This will inevitably raise questions
about which one to use, and which is used in some piece of code you're
staring at ;)

I agree, that we shouldn't make 'functools' be dependent on 'inspect' module.
Moreover, this is not even currently possible, as it creates an import-loop 
that is hard to untie.  But how about the following:

1. Separate 'Signature' object from 'inspect' module, and move it to a 
private '_signature.py' (that will depend only on 'collections.OrderedDict',
'itertools.chain' and 'types')

2. Publish it in the 'inspect' module

3. Make 'signature' method to work with any callable

4. Make 'Signature' class to accept only functions

5. Import '_signature' in the 'functools', and use 'Signature' class
directly, as it will accept just plain functions.

Would this work?

-
Yury



More information about the Python-Dev mailing list