Open In App

Python – Get Function Signature

Last Updated : 29 Dec, 2020
Improve
Improve
Like Article
Like
Save
Share
Report

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

Using signature() function

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
# parameter
def gfg(x:str, y:int):
    pass
  
# with the help of signature function
# store signature of the function in
# variable t
t = signature(gfg)
  
# print the signature of the function
print(t)
  
# print the annonation of the parameter
# of the function
print(t.parameters['x'])
  
# print the annonation of the parameter
# of the function
print(t.parameters['y'].annotation)


Output

(x:str, y:int)
x:str
<class 'int'>

Using Decorators

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_details
def 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’})



Previous Article
Next Article

Similar Reads

Function Signature in Perl
A Perl function or subroutine is a group of statements that together perform a specific task. In every programming language user want to reuse the code. So the user puts the section of code in function or subroutine so that there will be no need to write code again and again. In Perl, the terms function, subroutine, and method are the same but in s
4 min read
SymPy | Permutation.signature() in Python
Permutation.signature() : signature() is a sympy Python library function that returns the signature of the permutation needed to place the elements of the permutation in canonical order. Signature = (-1)^&lt;number of inversions&gt; Syntax : sympy.combinatorics.permutations.Permutation.signature() Return : signature of the permutation. Code #1 : si
1 min read
RSA Digital Signature Scheme using Python
RSA algorithm is an asymmetric cryptography algorithm. Asymmetric actually means that it works on two different keys i.e. Public Key and Private Key. As the name describes that the Public Key is given to everyone and the Private key is kept private. An example of asymmetric cryptography : A client (for example browser) sends its public key to the s
4 min read
Python | How to get function name ?
One of the most prominent styles of coding is following the OOP paradigm. For this, nowadays, stress has been to write code with modularity, increase debugging, and create a more robust, reusable code. This all encouraged the use of different functions for different tasks, and hence we are bound to know certain hacks of functions. This article disc
3 min read
How to get list of parameters name from a function in Python?
In this article, we are going to discuss how to get list parameters from a function in Python. The inspect module helps in checking the objects present in the code that we have written. We are going to use two methods i.e. signature() and getargspec() methods from the inspect module to get the list of parameters name of function or method passed as
2 min read
How to get the list of all initialized objects and function definitions alive in Python?
In this article, we are going to get the list of all initialized objects and function definitions that are alive in Python, so we are getting all those initialized objects details by using gc module we can get the details. GC stands for garbage collector which is issued to manage the objects in the memory, so from that module, we are using the get_
2 min read
Python Program For Writing A Function To Get Nth Node In A Linked List
Write a GetNth() function that takes a linked list and an integer index and returns the data value stored in the node at that index position. Example: Input: 1-&gt;10-&gt;30-&gt;14, index = 2 Output: 30 The node at index 2 is 30Recommended: Please solve it on "PRACTICE" first, before moving on to the solution. Algorithm: 1. Initialize count = 0 2.
4 min read
Get the Length of Text Without Using Inbuild Python Library Function
In Python, the length of a string can be calculated without using any library function by iterating through the characters of the string and counting them manually. This process involves creating a counter variable and incrementing it for each character encountered in the string. In this article, we will explore four different approaches to calcula
4 min read
Get Value From Generator Function in Python
Generator functions in Python are powerful tools for efficiently working with large datasets or generating sequences of values on the fly. They are different from regular functions as they use the yield keyword to produce a series of values, allowing the generator to pause its execution and resume where it left off when the next value is requested.
3 min read
Python Dictionary get() Method
Python Dictionary get() Method return the value for the given key if present in the dictionary. If not, then it will return None (if get() is used with only one argument). Python Dictionary get() Method Syntax: Syntax : Dict.get(key, default=None) Parameters: key: The key name of the item you want to return the value fromValue: (Optional) Value to
2 min read
three90RightbarBannerImg