inspect.signature Binds And Validates Arguments
Read a signature with inspect.signature, bind positional and keyword arguments, apply defaults, and report missing or extra parameters.
Code
import inspect
def send_email(
to: str,
subject: str,
*,
cc: str | None = None,
retries: int = 3,
) -> None:
print("sending to", to, "subject", subject, "cc", cc, "retries", retries)
def main() -> None:
signature = inspect.signature(send_email)
print("parameters:", list(signature.parameters))
print("return:", signature.return_annotation)
bound = signature.bind("ada@example.com", "Welcome", retries=5)
bound.apply_defaults()
print("arguments:", dict(bound.arguments))
try:
signature.bind("ada@example.com")
except TypeError as error:
print("missing argument:", error)
try:
signature.bind("ada@example.com", "Hi", "extra")
except TypeError as error:
print("too many positional:", error)
kinds = [parameter.kind.name for parameter in signature.parameters.values()]
print("parameter kinds:", kinds)
if __name__ == "__main__":
main()How it works
inspect.signature Binds And Validates Arguments keeps everything in the functions send_email and main.
Watch out for
- Dependency check:
inspect— not built-in, must be present in the project.
Putting it to use
Entry signature: def send_email( to: str, subject: str, *, cc: str | None = None, retries: int = 3, ) -> None
The run emits 7 labeled sections — sending to, parameters:, return:, arguments:, missing argument:, too many positional:, parameter kinds: — one per step.
Core lines
except TypeError as error:
print("missing argument:", error)
except TypeError as error:
print("too many positional:", error)
def send_email(
to: str,
subject: str,
*,
cc: str | None = None,
retries: int = 3,
) -> None:
Interactive Tools for This Topic
JSON to Zod Schema ConverterInfer typed Zod z.object schemas from JSON payloads locally, supporting nested objects, merged array shapes, enums, nullable fields, and JSDoc comments.JSON Schema ValidatorValidate JSON data against a JSON Schema definition and get detailed error reports. Supports type checking, required fields, and common constraint validation.JSONL / NDJSON InspectorValidate NDJSON and JSON Lines line-by-line, pinpoint syntax errors by line number, analyze key frequencies and types, and export a pretty JSON array.Credit Card Brand DetectorIdentify the card network from a number's prefix and length, validate the Luhn checksum, and show a masked form and the issuer identification number.
FAQ
- Do I need to install anything before running this?
- Yes: `inspect` must be present in the project or the import fails at load time.
Report a problem with this exampleOpens a pre-filled issue on GitHub.