Get Function Signature - Python
Last Updated :
03 Mar, 2025
A function signature in Python defines the name of the function, its parameters, their data types , default values and the return type. It acts as a blueprint for the function, showing how it should be called and what values it requires. A good understanding of function signatures helps in writing clear, readable and efficient code.
Example:
Python
def add(a, b):
return a + b
print(add(4,5))
Explanation: In this example, the function add takes two parameters a and b, both of type int and returns an int.
Methods to retrieve function signature
Using inspect.signature()
inspect module offers a function called signature() that allows us to get the signature of any callable object in Python. This is a powerful tool for analyzing functions, methods, and even classes.
Syntax:
import inspect
inspect.signature(callable)
Example:
Python
import inspect
# function with parameters
def fun(arg1: int, arg2: str, *args: int, **kwargs: float) -> bool:
pass
# retrieve the function's signature
sig = inspect.signature(fun)
print(sig)
# Access specific parameter details
for param in sig.parameters.values():
print(f"Parameter: {param.name}")
print(f"Type: {param.annotation}")
print(f"Default: {param.default}")
print(f"Kind: {param.kind}")
print("---")
Output
(arg1: int, arg2: str, *args: int, **kwargs: float) -> bool
Parameter: arg1
Type: <class 'int'>
Default: <class 'inspect._empty'>
Kind: POSITIONAL_OR_KEYWORD
---
Parameter: arg2
Type: <class 'str'>
Default: <class 'inspect._empty'>
Kind: POSITIONAL_OR_KEYWORD
---
Parameter: args
Type: <class 'int'>
Default: <class 'inspect._empty'>
Kind: VAR_POSITIONAL
---
Parameter: kwargs
Type: <class 'float'>
Default: <class 'inspect._empty'>
Kind: VAR_KEYWORD
---
Explanation: Here, inspect.signature() provides the full signature, including positional parameters (arg1, arg2), variable positional arguments (*args) and keyword arguments (**kwargs). We can also access individual parameter details such as their types and default values.
Using inspect.getfullargspec()
Another useful function from the inspect module is getfullargspec(). It provides a comprehensive breakdown of the function's arguments, including default values for each parameter, the type annotations, and information about variable positional arguments (*args) and keyword arguments (**kwargs). Example:
Python
import inspect
def fun(arg1: int, arg2: str, *args: int, **kwargs: float) -> bool:
pass
argspec = inspect.getfullargspec(fun)
print(f"Arguments: {argspec.args}")
print(f"Default Values: {argspec.defaults}")
print(f"Annotations: {argspec.annotations}")
OutputArguments: ['arg1', 'arg2']
Default Values: None
Annotations: {'return': <class 'bool'>, 'arg1': <class 'int'>, 'arg2': <class 'str'>, 'args': <class 'int'>, 'kwargs': <class 'float'>}
Explanation: Here, argspec.args lists the positional arguments, argspec.defaults provides the default values (if any) and argspec.annotations includes the type annotations.
Using __code__Artibute
For more low-level access to function details, Python functions have a __code__ attribute, which contains bytecode information about the function. The co_varnames attribute lists the names of the function's variables and the co_argcount attribute provides the number of positional arguments. Example:
Python
def fun(a, b, *args, **kwargs):
pass
print(fun.__code__.co_varnames)
print(fun.__code__.co_argcount)
Output('a', 'b', 'args', 'kwargs')
2
Explanation: Here, co_varnames lists the function's variables and co_argcount indicates the number of positional arguments.
Using decorators
In addition to using the inspect module directly, decorators can be used to capture and display function signatures during runtime. This method allows you to add extra behavior, like logging function calls or debugging, without modifying the original function. Example:
Python
def function_details(func):
def wrapper(*args, **kwargs):
# Retrieve argument names using func.__code__
argnames = func.__code__.co_varnames[:func.__code__.co_argcount]
print(f"Function: {func.__name__}()")
# Print the arguments passed to the function
print(", ".join(f"{arg}={value}" for arg, value in zip(argnames, args)), end=" ")
# Print variable arguments
if args[len(argnames):]:
print(f"args={args[len(argnames):]}", end=" ")
# Print keyword arguments
if kwargs:
print(f"kwargs={kwargs}", end=" ")
print(")")
return func(*args, **kwargs)
return wrapper
# Applying the decorator
@function_details
def example_function(a, b=1, *args, **kwargs):
pass
example_function(10, 20, 30, 40, name="John", age=25)
OutputFunction: example_function()
a=10, b=20 args=(30, 40) kwargs={'name': 'John', 'age': 25} )
Explanation: This decorator prints the function’s name along with the arguments passed, including positional arguments, variable arguments and keyword arguments.
Similar Reads
Python Functions Python Functions is a block of statements that does a specific task. The idea is to put some commonly or repeatedly done task together and make a function so that instead of writing the same code again and again for different inputs, we can do the function calls to reuse code contained in it over an
9 min read
Python def Keyword Python def keyword is used to define a function, it is placed before a function name that is provided by the user to create a user-defined function. In Python, a function is a logical unit of code containing a sequence of statements indented under a name given using the âdefâ keyword. In Python def
6 min read
Difference between Method and Function in Python Here, key differences between Method and Function in Python are explained. Java is also an OOP language, but there is no concept of Function in it. But Python has both concept of Method and Function. Python Method Method is called by its name, but it is associated to an object (dependent).A method d
3 min read
First Class functions in Python First-class function is a concept where functions are treated as first-class citizens. By treating functions as first-class citizens, Python allows you to write more abstract, reusable, and modular code. This means that functions in such languages are treated like any other variable. They can be pas
2 min read
Assign Function to a Variable in Python In Python, functions are first-class objects, meaning they can be assigned to variables, passed as arguments and returned from other functions. Assigning a function to a variable enables function calls using the variable name, enhancing reusability.Example:Python# defining a function def a(): print(
3 min read
User-Defined Functions
Python User Defined FunctionsA User-Defined Function (UDF) is a function created by the user to perform specific tasks in a program. Unlike built-in functions provided by a programming language, UDFs allow for customization and code reusability, improving program structure and efficiency.Example:Python# function defination def
6 min read
Python User Defined FunctionsA User-Defined Function (UDF) is a function created by the user to perform specific tasks in a program. Unlike built-in functions provided by a programming language, UDFs allow for customization and code reusability, improving program structure and efficiency.Example:Python# function defination def
6 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
3 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
3 min read
Defining a Python Function at RuntimeOne amazing feature of Python is that it lets us create functions while our program is running, instead of just defining them beforehand. This makes our code more flexible and easier to manage. Itâs especially useful for things like metaprogramming, event-driven systems and running code dynamically
3 min read
Call a function by a String name - PythonIn this article, we will see how to call a function of a module by using its name (a string) in Python. Basically, we use a function of any module as a string, let's say, we want to use randint() function of a random module, which takes 2 parameters [Start, End] and generates a random value between
3 min read
Explicitly define datatype in a Python functionUnlike other programming languages such as Java and C++, Python is a strongly, dynamically-typed language. This means that we do not have to explicitly specify the data type of function arguments or return values. Python associates types with values rather than variable names. However, if we want to
4 min read
Built-in and Special Functions
Python Built in FunctionsPython is the most popular programming language created by Guido van Rossum in 1991. It is used for system scripting, software development, and web development (server-side). Web applications can be developed on a server using Python. Workflows can be made with Python and other technologies. Databas
6 min read
Python Lambda FunctionsPython Lambda Functions are anonymous functions means that the function is without a name. As we already know the def keyword is used to define a normal function in Python. Similarly, the lambda keyword is used to define an anonymous function in Python. In the example, we defined a lambda function(u
6 min read
filter() in pythonThe filter() method filters the given sequence with the help of a function that tests each element in the sequence to be true or not. Let's see a simple example of filter() function in python:Example Usage of filter()Python# Function to check if a number is even def even(n): return n % 2 == 0 a = [1
3 min read
Python map() functionThe map() function is used to apply a given function to every item of an iterable, such as a list or tuple, and returns a map object (which is an iterator). Let's start with a simple example of using map() to convert a list of strings into a list of integers.Pythons = ['1', '2', '3', '4'] res = map(
4 min read
reduce() in PythonThe reduce(fun,seq) function is used to apply a particular function passed in its argument to all of the list elements mentioned in the sequence passed along. This function is defined in "functools" module.Basic Example:Letâs start with a simple example where we sum up all numbers in a list.Pythonfr
4 min read
Global and Local Variables
Parameters and Arguments
Python Function Parameters and ArgumentsParameters are variables defined in a function declaration. This act as placeholders for the values (arguments) that will be passed to the function. Arguments are the actual values that you pass to the function when you call it. These values replace the parameters defined in the function. Although t
3 min read
Keyword and Positional Argument in PythonPython provides different ways of passing the arguments during the function call from which we will explore keyword-only argument means passing the argument by using the parameter names during the function call.Types of argumentsKeyword-only argumentPositional-only argumentDifference between the Key
4 min read
How to find the number of arguments in a Python function?Finding the number of arguments in a Python function means checking how many inputs a function takes. For example, in def my_function(a, b, c=10): pass, the total number of arguments is 3. Some methods also count special arguments like *args and **kwargs, while others only count fixed ones.Using ins
4 min read
Default arguments in PythonPython allows function arguments to have default values. If the function is called without the argument, the argument gets its default value.Default Arguments: Python has a different way of representing syntax and default values for function arguments. Default values indicate that the function argum
7 min read
Passing function as an argument in PythonIn Python, functions are first-class objects meaning they can be assigned to variables, passed as arguments and returned from other functions. This enables higher-order functions, decorators and lambda expressions. By passing a function as an argument, we can modify a functionâs behavior dynamically
5 min read
How to get list of parameters name from a function in Python?The task of getting a list of parameter names from a function in Python involves extracting the function's arguments using different techniques. These methods allow retrieving parameter names efficiently, whether from bytecode, introspection or source code analysis. For example, if a function fun(a,
4 min read
How to Pass Optional Parameters to a Function in PythonIn Python, functions can have optional parameters by assigning default values to some arguments. This allows users to call the function with or without those parameters, making the function more flexible. When an optional parameter is not provided, Python uses its default value. There are two primar
5 min read
Return Statements
How to Pass Optional Parameters to a Function in PythonIn Python, functions can have optional parameters by assigning default values to some arguments. This allows users to call the function with or without those parameters, making the function more flexible. When an optional parameter is not provided, Python uses its default value. There are two primar
5 min read
Returning Multiple Values in PythonIn Python, we can return multiple values from a function. Following are different ways 1) Using Object: This is similar to C/C++ and Java, we can create a class (in C, struct) to hold multiple values and return an object of the class. Python # A Python program to return multiple # values from a meth
4 min read
Python None KeywordNone is used to define a null value or Null object in Python. It is not the same as an empty string, a False, or a zero. It is a data type of the class NoneType object. None in Python Python None is the function returns when there are no return statements. Python3 def check_return(): pass print(che
2 min read
Returning a function from a function - PythonIn Python, functions are first-class objects, allowing them to be assigned to variables, passed as arguments and returned from other functions. This enables higher-order functions, closures and dynamic behavior.Example:Pythondef fun1(name): def fun2(): return f"Hello, {name}!" return fun2 # Get the
5 min read