Sub topic 6
Let type checkers and linters flag missing attributes
Previous chapters showed how to check a symbol by hand with introspection and documentation. This chapter moves that check into tools that run on every file. I assume you can run Python 3.10 or later, install packages with pip, and read a pyproject.toml. You don't need prior experience with type annotations.
Why static tools catch invented APIs
A type checker reads your source without running it. It resolves each imported name to a module, class, or function definition, and then verifies every attribute access and call against that definition. If an assistant writes requests.get_json(...), the checker looks inside requests, finds no get_json, and reports an error. No network call, test, or runtime failure is needed.
A linter is a simpler tool. It matches syntax patterns and names inside the file. It doesn't know what requests contains, but it can still flag undefined names, unused imports, and call patterns that its authors know are deprecated.
The two tools find different problems, so you normally run both.
| Tool type | Examples | Good at | Blind to |
|---|---|---|---|
| Type checker | mypy, pyright | Missing module attributes, unknown keyword arguments, wrong argument counts, deprecated markers | Anything typed as `Any`, libraries without type information |
| Linter | ruff, flake8 | Undefined names, known-deprecated patterns such as `datetime.utcnow()` | Whether a library function actually exists |
| Runtime introspection | `inspect`, `importlib` | Real state of the installed package | Only checks what you explicitly ask |
A missing attribute, caught
Save this file as fetch.py. It contains the invented call from the earlier chapters.
import requests
def fetch(url: str) -> dict:
return requests.get_json(url)Install the checker and the stub package for requests. Stubs are separate packages that hold type information for libraries that don't ship their own.
python -m pip install mypy types-requests
python -m mypy fetch.pyMypy reports an error similar to this:
fetch.py:5: error: Module has no attribute "get_json" [attr-defined]
Found 1 error in 1 file (checked 1 source file)Pyright reports the same defect with different wording: "get_json" is not a known attribute of module "requests" (reportAttributeAccessIssue). The error code in brackets or parentheses is useful. attr-defined in mypy and reportAttributeAccessIssue in pyright are the codes that mean "this name does not exist on that object". You can watch for these codes in CI output and in review comments.
The same mechanism covers classes. Consider the removed DataFrame.append method from pandas 2.0:
import pandas as pd
rows = [{"id": 1}, {"id": 2}]
df = pd.DataFrame()
for row in rows:
df = df.append(row, ignore_index=True)With pandas-stubs installed at a version that matches your pandas 2.x, mypy reports "DataFrame" has no attribute "append" [attr-defined]. The checker enforces the library as it exists today, so the checker's own stubs must match the version you run. A mismatched stub package gives you wrong answers in both directions.
Wrong keyword arguments
Type checkers also compare a call's arguments to the function's declared parameters. Take this call:
import requests
response = requests.get("https://example.com/api", timeouts=10)The correct keyword is timeout. The types-requests stub declares get with explicit keyword parameters, so mypy reports Unexpected keyword argument "timeouts" for "get" [call-arg]. Without the checker, this call fails only when the line executes, and in some libraries it is silently swallowed by a **kwargs parameter.
That last case is a real limitation. Look at json.dumps:
import json
print(json.dumps({"a": 1}, pretty=True))The standard library's type stubs declare json.dumps with a trailing **kwds: Any, because extra keywords are forwarded to the encoder class. The checker therefore accepts pretty=True. At runtime the call raises TypeError, because the encoder's constructor doesn't accept pretty. This is the reason the introspection check from the previous chapter doesn't become redundant. A function that accepts arbitrary keywords gives a static checker nothing to compare against.
Configure the tools
Checkers are only useful if they are strict enough to see the problem. Put the configuration in pyproject.toml so that every developer and CI job uses it.
[tool.mypy]
python_version = "3.12"
warn_unused_ignores = true
warn_return_any = true
disallow_any_generics = true
enable_error_code = ["deprecated"]
[[tool.mypy.overrides]]
module = ["some_untyped_library.*"]
ignore_missing_imports = true
[tool.ruff.lint]
select = ["F", "UP", "DTZ", "NPY", "PD"]
[tool.pyright]
pythonVersion = "3.12"
typeCheckingMode = "standard"
reportDeprecated = "error"The settings that matter most for this chapter:
python_versionandpythonVersiontell the checker which version's standard library to use. Typeshed, the bundled standard-library stubs, marks some functions as deprecated only for newer versions. For example,datetime.utcnow()is flagged only when the target is 3.12 or later.enable_error_code = ["deprecated"]in mypy, andreportDeprecatedin pyright, turn use of functions marked deprecated into errors. The mypy error code requires a recent mypy release (1.14 or later), so check your version if the option is rejected.warn_unused_ignoresmakes mypy report# type: ignorecomments that no longer suppress anything. This keeps stale suppressions from hiding new problems.- The
ignore_missing_importsoverride is scoped to one named module. Setting it globally makes every third-party import resolve toAny, and the checker then stops catching invented attributes on those libraries.
Ruff rule groups are chosen by prefix. F covers undefined names and unused imports (for example F821, undefined name). UP suggests modern syntax for your target version. DTZ flags naive datetime calls such as datetime.utcnow() (rule DTZ003). NPY covers NumPy deprecations, and PD includes pandas-specific checks. Ruff doesn't import your libraries, so these rules only work for patterns that its maintainers added by hand. Treat them as a fast first filter, not a complete check.
Run the tools over generated code
When an assistant produces a patch, run all tools on the changed files before reading the diff in detail.
python -m ruff check .
python -m mypy src tests
python -m pyrightPick one type checker and run it consistently, or run both if you can afford the time. They resolve some situations differently. Pyright generally infers more types for unannotated code, so it reports more problems in loosely typed projects. Mypy skips the body of functions with no annotations unless you pass --check-untyped-defs, which matters a lot for assistant-written helper code.
What the checkers can't see
Understanding the blind spots is part of using these tools correctly.
- Untyped libraries. If a package ships no inline types and no stubs exist, imports resolve to
Any. Every attribute access on anAnyvalue is accepted. Mypy tells you with animport-untypederror, and pyright reports a missing stub as a warning. Treat both messages as a signal that the library is unchecked, and don't silence them blindly. - Dynamic attributes. A class that defines
__getattr__, or builds methods at runtime, accepts any attribute name as far as the checker can tell. Many API client libraries work this way. Verify names in those libraries with the documentation. - Stub drift. Stub packages are versioned separately from the libraries. If
pandas-stubsis older or newer thanpandas, the checker may flag valid code or accept removed code. Pin stub versions next to the library versions in your requirements. - Suppression comments. An assistant sometimes adds
# type: ignoreor# noqato make an error go away. Search the diff for these comments, and treat each one as a claim that needs a reason. - Behavior changes. If a function still exists but now returns something different, or a default argument changed meaning, the types may be unchanged. Tests and changelogs cover this case.
A review loop for a flagged error
Use the same short routine each time a checker reports an attribute or call error in generated code.
- Read the error code and the name it complains about.
- Confirm the installed version of the library with
importlib.metadata.version. - Check that stub packages, if any, match that version.
- Look up the name in the documentation for that version. If it was removed, find the replacement in the changelog.
- Edit the code to use the supported call, then rerun the checker.
- Only if the checker is demonstrably wrong, for example because of a stub bug, add a narrow suppression with a comment that names the reason.
This keeps the checker's output tied to evidence. It also stops the loop in which an assistant "fixes" one error by introducing another invented name.
Summary of the main points
- Type checkers resolve names against real definitions, so invented module attributes and unknown keyword arguments become errors before the code runs.
- Linters match known patterns and undefined names, but they don't inspect the installed library.
- Set the target Python version, enable deprecation reporting, and check untyped function bodies, or deprecated and invented calls slip through.
Any,**kwargs,__getattr__, untyped libraries, mismatched stubs, and suppression comments all reduce what a checker can see.- A passing run narrows the risk but doesn't remove it. Tests and documentation checks cover the rest.
Exercise
An assistant writes result = json.dumps(data, pretty=True). Mypy reports no error, but the program raises TypeError when it runs. Why does the checker accept the call, and what two checks would catch the mistake before running the program in production?
Show answer
The standard-library stub declares json.dumps with a trailing **kwds: Any, so the checker accepts any extra keyword name. The call fails at runtime because the encoder rejects pretty. You can catch it by inspecting the real parameters with inspect.signature(json.dumps) or the documentation, which list indent as the supported option, or by running a test that exercises the line.
Exercise
A project sets ignore_missing_imports = true globally in its mypy configuration. A generated patch calls somelib.fetch_all(), which does not exist, and mypy reports no error. Explain why, and describe a better configuration.
Show answer
The global setting makes every import that mypy can't resolve type information for become Any, and any attribute access on Any is accepted, so the missing fetch_all goes unnoticed. A better configuration leaves the setting off globally and adds a [[tool.mypy.overrides]] entry that sets ignore_missing_imports only for the specific modules known to lack types. Install stub packages such as types-requests where they exist, so more libraries are actually checked.