CARVIEW |
Select Language
HTTP/2 200
date: Sat, 11 Oct 2025 19:52:46 GMT
server: Fly/6f91d33b9d (2025-10-08)
content-type: text/html; charset=utf-8
content-encoding: gzip
via: 2 fly.io, 2 fly.io
fly-request-id: 01K7ADADRENPEF4X2A27SREDQP-bom
Introspecting Python function parameters | Simon Willison’s TILs
Introspecting Python function parameters
For https://github.com/simonw/datasette/issues/581 I want to be able to inspect a Python function to determine which named parameters it accepts and send only those arguments.
Python 3.3 added an inspect.signature() function that can be used for this.
Here's a function I wrote to take advantage of that and solve my problem:
def call_with_supported_arguments(fn, **kwargs):
parameters = inspect.signature(fn).parameters.keys()
call_with = []
for parameter in parameters:
if parameter not in kwargs:
raise TypeError("{} requires parameters {}".format(fn, tuple(parameters)))
call_with.append(kwargs[parameter])
return fn(*call_with)
And here's an illustrative unit test:
def test_call_with_supported_arguments():
def foo(a, b):
return "{}+{}".format(a, b)
assert "1+2" == utils.call_with_supported_arguments(foo, a=1, b=2)
assert "1+2" == utils.call_with_supported_arguments(foo, a=1, b=2, c=3)
with pytest.raises(TypeError):
utils.call_with_supported_arguments(foo, a=1)
Related
- python Decorators with optional arguments - 2020-10-28
- python Checking if something is callable or async callable in Python - 2023-08-04
- python Understanding option names in Click - 2020-09-22
- pytest Quick and dirty mock testing with mock_calls - 2021-11-02
- gpt3 Using OpenAI functions and their Python library for data extraction - 2023-07-09
- python How to call pip programatically from Python - 2020-08-11
- python Find local variables in the traceback for an exception - 2021-08-09
- python __init_subclass__ - 2021-12-03
- jinja Custom Jinja template tags with attributes - 2023-07-01
- python Annotated explanation of David Beazley's dataklasses - 2021-12-19
Created 2020-05-27T15:43:05-07:00 · Edit