Python - Get Function Signature - GeeksforGeeks

29 Dec, 2020
Let’s consider a scenario where you have written a very lengthy code and want to know the function call details. So what you can do is scroll through your code each and every time for different functions to know their details or you can work smartly. You can create a code where you can get the function details without scrolling through the code. This can be achieved in two ways –
Using signature() function
Using decorators
We can get function Signature with the help of signature() Function. It takes callable as a parameter and returns the annotation. It raises a value Error if no signature is provided. If the Invalid type object is given then it throws a Type Error.
Syntax:
inspect.signature(callable, *, follow_wrapped=True)
Example 1:
from inspect import signature    # declare a function gfg with some# parameterdef gfg(x:str, y:int):    pass  # with the help of signature function# store signature of the function in# variable tt = signature(gfg)  # print the signature of the functionprint(t)  # print the annonation of the parameter# of the functionprint(t.parameters['x'])  # print the annonation of the parameter# of the functionprint(t.parameters['y'].annotation)
Output
(x:str, y:int)
x:str
<class 'int'>
To do this the functions in Python certain attributes. One such attribute is __code__ that returns the called function bytecode. The __code__ attributes also have certain attributes that will help us in performing our tasks. We will be using the co_varnames attribute that returns the tuple of names of arguments and local variables and co_argcount that returns the number of arguments (not including keyword-only arguments, * or ** args). Let’s see the below implementation of such decorator using these discussed attributes.
Example:
# Decorator to print function call # details def function_details(func):                     # Getting the argument names of the     # called function     argnames = func.__code__.co_varnames[:func.__code__.co_argcount]             # Getting the Function name of the     # called function     fname = func.__name__                     def inner_func(*args, **kwargs):                     print(fname, "(", end = "")                     # printing the function arguments         print(', '.join( '% s = % r' % entry             for entry in zip(argnames, args[:len(argnames)])), end = ", ")                     # Printing the variable length Arguments         print("args =", list(args[len(argnames):]), end = ", ")                     # Printing the variable length keyword         # arguments         print("kwargs =", kwargs, end = "")         print(")")                 return inner_func         # Driver Code @function_detailsdef GFG(a, b = 1, *args, **kwargs):     pass    GFG(1, 2, 3, 4, 5, d = 6, g = 12.9) GFG(1, 2, 3) GFG(1, 2, d = 'Geeks') 
Output:
GFG (a = 1, b = 2, args = [3, 4, 5], kwargs = {‘d’: 6, ‘g’: 12.9})GFG (a = 1, b = 2, args = [3], kwargs = {})GFG (a = 1, b = 2, args = [], kwargs = {‘d’: ‘Geeks’})
Python Decorators
Python function-programs
Python-Functions
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Read a file line by line in Python
How to Install PIP on Windows ?
Enumerate() in Python
Different ways to create Pandas Dataframe
Iterate over a list in Python
Python String | replace()
*args and **kwargs in Python
Reading and Writing to text files in Python
Create a Pandas DataFrame from Lists