Sub topic 4
Check that the symbol exists and the signature fits
This chapter assumes you can run Python 3.9 or later, read a traceback, and use pip in a virtual environment. Earlier chapters covered the failure modes and why generated code drifts from your installed version. Here you build the cheapest check: ask the interpreter whether a name exists and whether a call matches it.
Why ask the interpreter
Documentation can be wrong or for the wrong version. The installed library cannot be. Python lets you look up a dotted name and inspect the parameters of a function without running the code that uses it. That catches two common errors early:
- An invented symbol, such as
requests.get_json. - A real function called with arguments it does not accept, such as
os.makedirs(..., exists_ok=True).
Check that the symbol exists
The helper below imports the longest module prefix of a dotted name, then walks the remaining attributes with getattr.
import importlib
def resolve(dotted_name):
"""Return the object named by a dotted path, or raise if it does not exist."""
parts = dotted_name.split(".")
for i in range(len(parts), 0, -1):
try:
obj = importlib.import_module(".".join(parts[:i]))
except ModuleNotFoundError:
continue
for attr in parts[i:]:
obj = getattr(obj, attr) # AttributeError if the name is invented
return obj
raise ModuleNotFoundError(dotted_name)
print(resolve("os.path.join"))
# resolve("os.path.join_all") raises AttributeErrorAn AttributeError means the library has no such name in your installed version. A ModuleNotFoundError means the top-level package is not installed or does not exist. The second case is covered in the chapter on dependency verification.
Check that the signature fits
A name that exists can still be called wrongly. inspect.signature returns the parameters a callable accepts.
import inspect
import json
sig = inspect.signature(json.dumps)
print(sig)
print("indent" in sig.parameters) # True
print("pretty" in sig.parameters) # FalseListing parameters is useful when you want to see what is available. To test one specific call, use Signature.bind. It raises TypeError if the arguments cannot be matched to the parameters, and it does not call the function.
import inspect
import os
def fits(func, *args, **kwargs):
try:
inspect.signature(func).bind(*args, **kwargs)
except TypeError as exc:
return f"does not fit: {exc}"
return "fits"
print(fits(os.makedirs, "out", exist_ok=True))
print(fits(os.makedirs, "out", exists_ok=True))The first call prints fits. The second prints does not fit: got an unexpected keyword argument 'exists_ok'.
Limits of the signature check
Treat a passing bind as a necessary check, not proof that the call works.
- `kwargs
accepts anything.**json.dumpsdeclareskw, sobind(obj, pretty=True)succeeds. The extra keyword is forwarded toJSONEncoder, and the real call then fails withTypeError. When a signature ends inkwargs`, read the docs for what it forwards to. - Some callables have no signature.
inspect.signatureraisesValueErrorfor certain C-implemented builtins. Read their documentation instead. - Types and meaning are not checked.
bindconfirms the shape of the call. It does not confirm that a value has the right type, or that a parameter does what the generated code assumes. - Dynamic attributes can hide or fake names. Some libraries create attributes at runtime or through
__getattr__. A failed lookup is strong evidence only for ordinary modules.
Where to use these checks
Run them in a scratch shell on any call you do not recognize. For a whole change, list the unfamiliar calls and pass each through resolve and fits. The static analysis chapter automates a similar check across the whole codebase.
Exercise
A generated line calls json.dumps(data, pretty=True). "pretty" in inspect.signature(json.dumps).parameters is False, yet inspect.signature(json.dumps).bind(data, pretty=True) does not raise. Why, and what do you do next?
Show answer
json.dumps declares **kw, so bind accepts any extra keyword. The keyword is passed on to JSONEncoder, which rejects it with a TypeError at call time. Treat the parameter-name check as the more useful result here, and use indent=2 instead, which is a real parameter. Confirm the behavior in the docs for your installed version.