Last modified: Nov 19, 2026
Python Inspect Function Signature Guide
You often need to know what arguments a function expects. Python gives you a built-in tool for this. The inspect module lets you read a function's signature at runtime.
This is called introspection. Your code can look at itself and learn about its own functions. It is a powerful skill for debugging, testing, and building tools.
In this guide, you will learn how to inspect a function signature step by step. We will cover parameters, defaults, annotations, and practical use cases.
Why Inspect a Function Signature?
Function signatures tell you how to call a function correctly. They show the parameter names, order, and default values. They also reveal keyword-only and positional-only arguments.
Inspecting signatures is useful in many situations. Frameworks use it to validate arguments. Test tools use it to generate calls. Documentation tools use it to build reference pages.
You may also use it to write decorators that preserve the original function's metadata. This keeps your code clean and predictable.
Getting Started with the inspect Module
The inspect module is part of the standard library. No installation is needed. Just import it and call the right function.
The core function is signature. It takes any callable and returns a Signature object. That object holds all the details about the parameters.
import inspect
def greet(name, greeting="Hello"):
return f"{greeting}, {name}!"
sig = inspect.signature(greet)
print(sig)
(name, greeting='Hello')
The output is short and clear. It shows both parameter names and the default value for greeting. This is the same format you see in help pages.
Reading the Parameters
The Signature object has a parameters attribute. It is an ordered mapping of parameter names to Parameter objects. You can loop over it easily.
Each Parameter object tells you the name, kind, default, and annotation. This gives you full control over the details.
import inspect
def connect(host, port=5432, *, timeout=30, retries=3):
pass
sig = inspect.signature(connect)
for name, param in sig.parameters.items():
print(name, "|", param.kind, "|", param.default)
host | POSITIONAL_OR_KEYWORD |
port | POSITIONAL_OR_KEYWORD | 5432
timeout | KEYWORD_ONLY | 30
retries | KEYWORD_ONLY | 3
Notice the inspect._empty value. It means the parameter has no default. You must pass a value for it when calling the function.
The kind field is also important. It shows whether a parameter is positional, keyword-only, or variadic. We will look at kinds next.
Parameter Kinds Explained
Python has five parameter kinds. Each one behaves differently when you call the function. The inspect module names them clearly.
POSITIONAL_ONLY parameters must be passed by position. POSITIONAL_OR_KEYWORD parameters can be passed either way. VAR_POSITIONAL captures extra positional arguments as a tuple.
KEYWORD_ONLY parameters must be passed by name. VAR_KEYWORD captures extra keyword arguments as a dict.
import inspect
def sample(a, /, b, *args, c, **kwargs):
pass
sig = inspect.signature(sample)
for name, param in sig.parameters.items():
print(f"{name:8} -> {param.kind.name}")
a -> POSITIONAL_ONLY
b -> POSITIONAL_OR_KEYWORD
args -> VAR_POSITIONAL
c -> KEYWORD_ONLY
kwargs -> VAR_KEYWORD
This mapping is very helpful. It lets you build tools that call functions correctly, no matter how complex their signatures are.
If you combine this with other standard tools, you can write clean and flexible code. For example, caching wrappers often need to know argument names. Learn more in this guide on Python caching with functools.
Checking Defaults and Annotations
Defaults tell you which arguments are optional. Annotations tell you the expected types. Both are available on each Parameter object.
You can check if a parameter has a default with a simple comparison. If the default is inspect.Parameter.empty, the argument is required.
import inspect
def register(user: str, age: int = 18, active: bool = True) -> bool:
return active
sig = inspect.signature(register)
for name, param in sig.parameters.items():
has_default = param.default is not inspect.Parameter.empty
print(f"{name}: default={has_default}, annotation={param.annotation}")
print("Return annotation:", sig.return_annotation)
user: default=False, annotation=
age: default=True, annotation=
active: default=True, annotation=
Return annotation: This is the same information used by type checkers. Reading it at runtime opens up many options for dynamic code.
Decorators commonly use this data. They can wrap functions while keeping the original signature intact. If you use functools.wraps, the metadata is preserved automatically. See how it works in Python functools: lru_cache and partial.
Inspecting Built-in and Class Methods
You can inspect more than plain functions. Methods, classes, and even some built-in callables work too. The results depend on what information Python exposes.
For classes, signature usually reflects the __init__ method. For methods, the self parameter is included unless you use a bound method.
import inspect
class Account:
def __init__(self, owner, balance=0):
self.owner = owner
self.balance = balance
print(inspect.signature(Account))
account = Account("Ana")
print(inspect.signature(account.__init__))
(owner, balance=0)
(balance=0)
The bound method drops self from the signature. This makes sense because the instance is already attached.
Some built-in functions have no Python-level signature. Calling signature on them may raise a ValueError. Always wrap such calls in a try block when you are unsure.
Using Signatures to Validate Arguments
You can use a Signature object to bind arguments yourself. The bind method checks whether a call is valid. It raises a TypeError when something is wrong.
This is helpful when you build your own dispatch systems or command handlers.
import inspect
def send_email(to, subject, cc=None):
pass
sig = inspect.signature(send_email)
# Valid call
bound = sig.bind("[email protected]", "Hi")
print(bound.arguments)
# Invalid call: missing required argument
try:
sig.bind("[email protected]")
except TypeError as e:
print("Error:", e)
{'to': '[email protected]', 'subject': 'Hi'}
Error: missing a required argument: 'subject'
This pattern is common in web frameworks. A router reads the handler signature and maps request data to the right parameters. The same idea appears in many other tools.
When you combine signature binding with lazy data sources, things get even more interesting. Generators are a good example, as explained in Python yield vs return: key differences.
Practical Tips and Common Pitfalls
Keep a few things in mind when you inspect signatures. First, defaults are evaluated once at function definition time. The signature shows the stored value, not a fresh one.
Second, string annotations may appear if you use from __future__ import annotations. You can resolve them with typing.get_type_hints when needed.
Third, decorated functions can hide the real signature. If a decorator does not use functools.wraps, the signature may show *args and **kwargs instead of the original parameters.
Finally, avoid calling signature in tight loops. Cache the result if you use it often. It is fast, but not free.
Conclusion
Inspecting a Python function signature is simple once you know the tools. Use inspect.signature to get a Signature object. Then read its parameters, defaults, kinds, and annotations.
This skill helps you debug faster. It also lets you build decorators, validators, and frameworks that adapt to any function. Start with small examples, and you will master it quickly.
Try it on your own code today. Pick one function and print its signature. You may be surprised by what you learn.