Sub topic 4
Check that the symbol exists and the signature fits
This chapter assumes you can run Python 3.9 or later, use pip in a virtual environment, and read a function signature such as f(a, b=1, *, c=None). Earlier chapters covered how to find your installed versions. Here you check, in code, whether a name an assistant wrote exists in those versions and whether the call matches what the function accepts.
Three questions, asked in order
A generated call can fail in three ways. Each needs a different check, and the cheap ones come first.
| Question | Example failure | Check |
|---|---|---|
| Does the name exist? | `requests.get_json(...)` | Import and `getattr` |
| Does the call fit the signature? | `json.dumps(x, pretty=True)` | `inspect.signature` and `bind` |
| Does it do what the code assumes? | A parameter changed meaning between versions | Docs, changelog, tests (later chapters) |
This chapter covers the first two. Both run in milliseconds and need no network, so you can run them on every suggestion.
Check that the name exists
Take a typical suggestion. The commented-out line looks plausible but requests has no get_json.
import requests
# Invented API: the requests module has no get_json function.
# data = requests.get_json("https://example.com/api")
# Real API: call get, then decode the body with Response.json().
response = requests.get("https://example.com/api", timeout=10)
data = response.json()Nothing fails when the file is read. The error appears only when that line executes, possibly in production. Resolving the name first moves the failure to review time.
A dotted name such as os.path.join mixes module imports and attribute lookups, and you cannot tell which part is which by looking at it. The helper below imports the longest module prefix it can, then walks the remaining parts as attributes.
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 AttributeErrorFor os.path.join_all, the full import fails, os.path imports, and getattr(os.path, "join_all") raises AttributeError. That error is the signal you want.
Where existence checks mislead
- Swallowed import errors. If a real module fails because one of its own dependencies is missing, it raises
ModuleNotFoundErrortoo. The helper then falls back to a shorter prefix and may report a misleadingAttributeError. Read the traceback before concluding that the name is invented. - Lazy submodules.
import xmldoes not makexml.domavailable, so a plainhasattr(xml, "dom")isFalse. The helper avoids this by importing prefixes, but a barehasattrdoes not. - Catch-all
__getattr__. Some objects, such as mocks, answer any attribute lookup. A pass on those proves nothing. - Existing is not current. A deprecated function still resolves. Deprecation is handled in a later chapter.
Suggest the real name
When a lookup fails, the assistant usually meant something nearby. dir() lists names and difflib ranks them.
import difflib
import requests
print(difflib.get_close_matches("pos", dir(requests))) # 'post' is among the matchesTreat the result as a lead to confirm in the docs, not as a fix to apply blindly.
Check imports in a whole snippet
Reviewing one call at a time is slow. Python's ast module can find every import in generated code, so you can check them all at once.
import ast
import importlib
def check_imports(source):
"""Return a list of problems found in the import statements of source."""
problems = []
for node in ast.walk(ast.parse(source)):
if isinstance(node, ast.Import):
for alias in node.names:
try:
importlib.import_module(alias.name)
except ModuleNotFoundError:
problems.append(f"missing module: {alias.name}")
elif isinstance(node, ast.ImportFrom) and node.module and node.level == 0:
try:
module = importlib.import_module(node.module)
except ModuleNotFoundError:
problems.append(f"missing module: {node.module}")
continue
for alias in node.names:
if alias.name == "*" or hasattr(module, alias.name):
continue
try:
importlib.import_module(f"{node.module}.{alias.name}")
except ModuleNotFoundError:
problems.append(f"missing name: {node.module}.{alias.name}")
return problems
snippet = "from json import dumps, pretty_print\nimport nothing_here\n"
print(check_imports(snippet))This prints ['missing name: json.pretty_print', 'missing module: nothing_here']. The second from check matters because from package import submodule is valid even when submodule is not an attribute until it is imported.
Check that the signature fits
Once a name resolves, ask whether the call is accepted. inspect.signature reads the parameters of a callable.
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, but Signature.bind is stronger. It applies Python's real argument-matching rules to the arguments the generated code passes, without calling the function.
import inspect
import shutil
def check_call(func, *args, **kwargs):
"""Report whether a call would be accepted by func's signature."""
try:
signature = inspect.signature(func)
except (TypeError, ValueError):
return "no signature available"
try:
signature.bind(*args, **kwargs)
except TypeError as exc:
return f"signature mismatch: {exc}"
return "ok"
print(check_call(shutil.copyfile, "a.txt", "b.txt"))
print(check_call(shutil.copyfile, "a.txt", "b.txt", follow=True))The first call prints ok. The second prints a mismatch such as got an unexpected keyword argument 'follow', because the real parameter is follow_symlinks. Bind also catches missing required arguments, too many positional arguments, and keyword-only parameters passed by position.
Where signature checks mislead
- `kwargs
hides mistakes.**json.dumpsacceptskwand forwards it to the encoder.bindtherefore acceptspretty=True, and the real call fails later with aTypeErrorfrom inside the encoder. When a signature ends inkwargs, a passingbind` says little about keyword names. Check the documentation for the accepted keys. - Wrappers. A decorator written with
functools.wrapsexposes the original signature. One written without it shows(*args, **kwargs), which accepts everything. - Builtins. Some C-implemented callables raise
ValueErrorfrominspect.signature. Fall back tohelp()or the docs. - Classes and methods. For a class, the signature describes the constructor and does not include
self. For a method accessed through the class,selfis included. Through an instance, it is not. - Types and meaning.
bindchecks the shape of the call, not the argument values. Passing a string where a path object is expected still binds.
A worked review
Suppose an assistant writes:
import json
text = json.dumps(data, pretty=True)resolve("json.dumps")succeeds, so the name exists."pretty" in inspect.signature(json.dumps).parametersisFalse.- The signature ends in
**kw, sobindwould accept the call and not warn you. TheFalsefrom step 2 is the useful result. - The docs for your Python version list
indentfor formatting output, so the fix isjson.dumps(data, indent=2).
The existence check passed and the keyword check caught the problem. Neither check alone was enough here.
Exercise
An assistant writes shutil.copy_tree("src", "dst", overwrite=True). Describe which of the checks from this chapter you would run, in what order, and what each result would tell you.
Show answer
First run resolve("shutil.copy_tree"). It raises AttributeError, because the real function is shutil.copytree, so the name is invented or misremembered. Use difflib.get_close_matches on dir(shutil) to find copytree. Then run check_call(shutil.copytree, "src", "dst", overwrite=True). It reports a mismatch because copytree has no overwrite parameter (the closest real one is dirs_exist_ok). Confirm that parameter's behavior in the docs for your Python version, because bind only checks the shape of the call, not its meaning.
Exercise
Why can inspect.signature(f).bind(...) succeed for a call that fails when it runs? Give two causes.
Show answer
Any two of these: the function accepts **kwargs and passes unknown keywords on to code that rejects them later; a decorator without functools.wraps replaces the signature with (*args, **kwargs); bind does not check argument types or values, so a value of the wrong type can still raise inside the function.