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.

PythonData Integrity

Code

pythonsnippet
38 lines
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("[email protected]", "Welcome", retries=5)
    bound.apply_defaults()
    print("arguments:", dict(bound.arguments))

    try:
        signature.bind("[email protected]")
    except TypeError as error:
        print("missing argument:", error)

    try:
        signature.bind("[email protected]", "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

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.