2010-04-20 12 views
69

Dato un oggetto funzione, come posso ottenere la sua firma? Ad esempio, per:Come posso leggere la firma di una funzione compresi i valori degli argomenti predefiniti?

def myMethod(firt, second, third='something'): 
    pass 

Mi piacerebbe ottenere "myMethod(firt, second, third='something')".

+3

Puoi per favore approfondire la tua domanda specifica e magari dare un esempio con il risultato atteso? – jhwist

+0

Probabilmente sta cercando funzionalità in Python o librerie di terze parti che restituiscano la firma di un metodo (nomi e tipi di parametri e valore restituito) dato il nome del metodo. –

+1

Firma come in come chiamarlo e così? Prova 'help (yourmethod)' ad es. 'Help (mappa)' –

risposta

108
import inspect 

def foo(a, b, x='blah'): 
    pass 

print(inspect.getargspec(foo)) 
# ArgSpec(args=['a', 'b', 'x'], varargs=None, keywords=None, defaults=('blah',)) 

Tuttavia, si noti che è inspect.getargspec() Sconsigliato a partire da Python 3.0.

Python 3.0--3.4 raccomanda inspect.getfullargspec().

Python 3.5+ raccomanda inspect.signature().

+0

AttributeError: 'modulo' oggetto non ha attributo 'getargspec' –

+3

@Spi, stai chiamando 'inspect.getargspec' su un modulo, non una funzione. –

+0

Grazie, il problema è stato con Eclipse che non ha visto il modulo di ispezione –

7

provare a chiamare help su un oggetto per scoprire su di esso.

>>> foo = [1, 2, 3] 
>>> help(foo.append) 
Help on built-in function append: 

append(...) 
    L.append(object) -- append object to end 
12
#! /usr/bin/env python 

import inspect 
from collections import namedtuple 

DefaultArgSpec = namedtuple('DefaultArgSpec', 'has_default default_value') 

def _get_default_arg(args, defaults, arg_index): 
    """ Method that determines if an argument has default value or not, 
    and if yes what is the default value for the argument 

    :param args: array of arguments, eg: ['first_arg', 'second_arg', 'third_arg'] 
    :param defaults: array of default values, eg: (42, 'something') 
    :param arg_index: index of the argument in the argument array for which, 
    this function checks if a default value exists or not. And if default value 
    exists it would return the default value. Example argument: 1 
    :return: Tuple of whether there is a default or not, and if yes the default 
    value, eg: for index 2 i.e. for "second_arg" this function returns (True, 42) 
    """ 
    if not defaults: 
     return DefaultArgSpec(False, None) 

    args_with_no_defaults = len(args) - len(defaults) 

    if arg_index < args_with_no_defaults: 
     return DefaultArgSpec(False, None) 
    else: 
     value = defaults[arg_index - args_with_no_defaults] 
     if (type(value) is str): 
      value = '"%s"' % value 
     return DefaultArgSpec(True, value) 

def get_method_sig(method): 
    """ Given a function, it returns a string that pretty much looks how the 
    function signature would be written in python. 

    :param method: a python method 
    :return: A string similar describing the pythong method signature. 
    eg: "my_method(first_argArg, second_arg=42, third_arg='something')" 
    """ 

    # The return value of ArgSpec is a bit weird, as the list of arguments and 
    # list of defaults are returned in separate array. 
    # eg: ArgSpec(args=['first_arg', 'second_arg', 'third_arg'], 
    # varargs=None, keywords=None, defaults=(42, 'something')) 
    argspec = inspect.getargspec(method) 
    arg_index=0 
    args = [] 

    # Use the args and defaults array returned by argspec and find out 
    # which arguments has default 
    for arg in argspec.args: 
     default_arg = _get_default_arg(argspec.args, argspec.defaults, arg_index) 
     if default_arg.has_default: 
      args.append("%s=%s" % (arg, default_arg.default_value)) 
     else: 
      args.append(arg) 
     arg_index += 1 
    return "%s(%s)" % (method.__name__, ", ".join(args)) 


if __name__ == '__main__': 
    def my_method(first_arg, second_arg=42, third_arg='something'): 
     pass 

    print get_method_sig(my_method) 
    # my_method(first_argArg, second_arg=42, third_arg="something") 
+0

Qualche spiegazione su cosa dovrebbe fare? – grantmcconnaughey

+0

Aggiunti commenti all'esempio di codice, sperare che sia d'aiuto. –

+0

Bello, grazie! – grantmcconnaughey

21

Probabilmente il modo più semplice per trovare la firma di una funzione sarebbe help(function):

>>> def function(arg1, arg2="foo", *args, **kwargs): pass 
>>> help(function) 
Help on function function in module __main__: 

function(arg1, arg2='foo', *args, **kwargs) 

Inoltre, in Python 3 un metodo è stato aggiunto al modulo inspect chiamato signature, che è stato progettato per rappresentare il signature of a callable object and its return annotation:

>>> from inspect import signature 
>>> def foo(a, *, b:int, **kwargs): 
...  pass 

>>> sig = signature(foo) 

>>> str(sig) 
'(a, *, b:int, **kwargs)' 

>>> str(sig.parameters['b']) 
'b:int' 

>>> sig.parameters['b'].annotation 
<class 'int'> 
+1

Perfetto. Tutto quello che volevo veramente era di scaricare una firma leggibile dall'uomo per una funzione. – ArtOfWarfare

+2

'inspect.signature' è anche disponibile per Python 2 tramite il progetto backport' funcsigs': https://pypi.python.org/pypi/funcsigs – ncoghlan

5

Forse un po 'in ritardo alla festa, ma se anche si vuole mantenere l'ordine del un rguments e le loro impostazioni predefinite, quindi è possibile utilizzare il Abstract Syntax Tree module (ast).

Ecco una prova di concetto (attenzione il codice per ordinare gli argomenti e abbinarli ai valori predefiniti può sicuramente essere migliorato/reso più chiaro):

import ast 

for class_ in [c for c in module.body if isinstance(c, ast.ClassDef)]: 
    for method in [m for m in class_.body if isinstance(m, ast.FunctionDef)]: 
     args = [] 
     if method.args.args: 
      [args.append([a.col_offset, a.id]) for a in method.args.args] 
     if method.args.defaults: 
      [args.append([a.col_offset, '=' + a.id]) for a in method.args.defaults] 
     sorted_args = sorted(args) 
     for i, p in enumerate(sorted_args): 
      if p[1].startswith('='): 
       sorted_args[i-1][1] += p[1] 
     sorted_args = [k[1] for k in sorted_args if not k[1].startswith('=')] 

     if method.args.vararg: 
      sorted_args.append('*' + method.args.vararg) 
     if method.args.kwarg: 
      sorted_args.append('**' + method.args.kwarg) 

     signature = '(' + ', '.join(sorted_args) + ')' 

     print method.name + signature 
3

Se tutti si sta cercando di fare è stampare la funzione quindi usa pydoc.

import pydoc  

def foo(arg1, arg2, *args, **kwargs):                  
    '''Some foo fn'''                      
    pass                         

>>> print pydoc.render_doc(foo).splitlines()[2] 
foo(arg1, arg2, *args, **kwargs) 

Se si sta tentando di analizzare effettivamente la firma della funzione, utilizzare argspec del modulo di ispezione. Dovevo farlo quando convalidavo la funzione di script hook di un utente in un framework generale.

Problemi correlati