Linters Type Checkers And Formatters For Python Da
You know that sinking feeling. You have a data pipeline that started as a 50-line Jupyter notebook cell. It worked. Then someone asked for “just one more” feature. Now it’s a 2,000-line script that produces a report your team depends on every Monday. The numbers look right. But you’re terrified to touch anything. What if that “small refactor” silently breaks a calculation downstream? What if a column name changes in the source data and your script happily computes a mean of strings instead of floats, producing a number that looks plausible but is completely wrong?
This is the reality of data code: it has extremely high “correctness risk.” Unlike a web app that crashes with a 500 error when something goes wrong, a data pipeline often fails silently. A bug doesn’t stop execution — it just corrupts your output. And you, the exhausted data scientist, are left squinting at summary statistics, hoping nothing broke.
There are three families of tools that can give you a safety net. Type checkers catch logic errors before your code ever runs. Linters catch code smells and style violations that make your code hard to maintain. Formatters eliminate style debates entirely by rewriting your code to a consistent format automatically. In this article, we’ll focus on the three most established tools in the Python data ecosystem: mypy (type checker), pylint (deep linter), and flake8 (fast, modular linter). We’ll also explain where Black fits in, because formatters solve a different problem that’s often confused with linting.
Here’s a tiny, realistic data snippet with a subtle bug — exactly the kind of thing that keeps you up at night:
import pandas as pd
# Simulate loading a CSV where a numeric column accidentally contains strings
data = {
"product": ["A", "B", "C"],
"sales": ["100", "200", "invalid"] # strings from a messy CSV
}
df = pd.DataFrame(data)
# This function expects sales to be numeric, but it's not
def compute_average_sales(df):
return df["sales"].mean()
result = compute_average_sales(df)
print(f"Average sales: {result}")
This code runs without crashing. But the “average” it computes is meaningless — it’s concatenating strings or producing something weird, not a true numeric mean. This is the “before” picture. By the end of this article, you’ll have tools that catch this kind of bug before it ever reaches production.
The Three Families of Code Quality Tools (And Why You Need All Three)
Before we compare specific tools, we need a mental model. Think of your code as a document you’re writing. You want three kinds of help:
- A spell-checker that catches when you’ve used a word that doesn’t exist or doesn’t make sense in context. In code, this is a type checker. It answers: “Will this operation fail on this kind of data?” It reasons about types without running the code.
- A writing coach that flags run-on sentences, passive voice, or confusing structure. In code, this is a linter. It answers: “Is this code hard to read, likely buggy, or against best practices?” It checks style and structural patterns.
- An auto-formatter that fixes your margins, font, and spacing so the document looks consistent. In code, this is a formatter. It answers: “Does this code look consistent?” It rewrites code to a fixed style automatically — no human decisions needed.
Here’s the crucial distinction: linters and type checkers report problems for you to fix. Formatters fix problems themselves. Confusing these categories leads to frustration — like expecting your spell-checker to rewrite your paragraphs for you.
Let’s look at one messy code snippet that demonstrates all three problem categories at once. We’ll revisit this snippet throughout the article to see what each tool catches:
import pandas as pd
unused_variable = "nobody reads me"
def process_data(data, threshold):
# This line is way too long and has inconsistent spacing
result = data.groupby('category').apply(lambda x: x[x['value']>threshold]['value'].mean()).reset_index()
# Type error: threshold is a string, but we're comparing it to a numeric column
return result
# Calling with a string threshold — this will cause a silent logic error
sample_data = pd.DataFrame({'category': ['A', 'A', 'B', 'B'], 'value': [10, 20, 30, 40]})
output = process_data(sample_data, 'high') # 'high' is a string, not a number
In this snippet, we have:
- A type error: passing a string (
'high') where a number is expected forthreshold. - A style violation: a line that’s far too long and has inconsistent spacing.
- A code smell: an unused variable (
unused_variable) that clutters the namespace.
Now, let’s meet the tools that can catch these problems.
mypy: The Type Checker That Catches Silent Logic Errors
mypy is the tool that answers the question: “What if I pass the wrong kind of data?” This is the most dangerous class of bugs in data pipelines — the kind that produce plausible-looking numbers instead of crashes.
mypy is a static type checker. It reads your code and any type annotations you’ve added, then verifies consistency without executing anything. It implements PEP 484, the standard Python type hint syntax. Here’s what that means for you: type hints are completely optional and have zero effect at runtime. You can add them to one function at a time, and mypy will only check what you’ve annotated. This is called gradual typing — no all-or-nothing migration required.
For data scientists, the highest-value annotations are function signatures on data-transformation functions. These catch the “wrong column type” bugs that plague pandas pipelines. Let’s see it in action.
First, we’ll write a function with type hints that contains a type error:
import pandas as pd
def compute_metrics(df: pd.DataFrame) -> dict:
"""Compute summary metrics from a DataFrame."""
# Type error: .sum() on a string column doesn't make numeric sense
total = df["category"].sum()
return {"total": total}
# Create a DataFrame where 'category' is a string column
df = pd.DataFrame({"category": ["A", "B", "C"], "value": [1, 2, 3]})
result = compute_metrics(df)
print(result)
If we run this code normally, Python won’t complain — it’ll just concatenate the strings in the category column, producing 'ABC'. That’s a silent logic error. But if we run mypy on this file, here’s what we get:
$ mypy script.py
script.py:6: error: Incompatible types in assignment (expression has type "str", variable has type "int") [assignment]
Found 1 error in 1 file (checked 1 source file)
In plain English, mypy is telling us: “On line 6, you’re trying to sum a column of strings and treat the result as something numeric. That doesn’t make sense.” It caught the bug without us ever running the code.
What mypy does not do: it doesn’t check style, code complexity, or unused variables. It’s laser-focused on type correctness. You’ll still need a linter for those other concerns.
pylint: The Deep Code Analyst That Finds Hidden Bugs and Smells
pylint is the most ambitious of the three tools. It doesn’t just check surface-level style — it actually builds a semantic model of your code to reason about what it means. Understanding pylint’s semantic model is essential, so let’s use pylint’s own example.
Imagine you write: import logging as argparse. Later, you call argparse.error(). A simple pattern-matching linter might see that argparse is a module and assume everything is fine. But pylint understands that argparse is actually an alias for the logging module, so argparse.error() is really a logging call — and that might be a bug. This depth comes from pylint’s internal engine called astroid, which builds a semantic representation of your code.
This depth lets pylint catch bugs that simpler linters miss: redefined functions, arguments with the same name as builtins, methods that don’t call super(), and more. The tradeoff? pylint is slower than flake8 (noticeable on large codebases), and its default configuration is famously noisy. You’ll want to customize its rules for data-science workflows.
Let’s see pylint catch a subtle bug that a simpler linter would miss:
import pandas as pd
# Subtle bug: redefining a built-in name
list = [1, 2, 3] # 'list' is now a variable, shadowing the built-in list() function
# Unused import
import numpy as np
def process_data(data):
# This will fail if we try to use list() later
result = list(data) # Wait, is this the variable or the built-in?
return result
# Later in the code...
# new_list = list(range(10)) # This would crash because 'list' is now a list, not a function
Running pylint on this file:
$ pylint script.py
************* Module script
script.py:4:0: C0103: Constant name "list" doesn't conform to UPPER_CASE naming style (invalid-name)
script.py:4:0: W0622: Redefining built-in 'list' (redefined-builtin)
script.py:7:0: W0611: Unused import numpy (unused-import)
Let’s interpret each message in plain English:
- C0103: “Your variable name
listdoesn’t match the expected style.” Since it’s assigned at module level, pylint expectsUPPER_CASEfor constants. - W0622: “You’ve redefined the built-in
list.” This is the critical one — shadowing a built-in can cause incredibly confusing bugs later when you try to calllist()and get a TypeError becauselistis now a list object. - W0611: “You imported
numpybut never used it.” This is clutter that makes your code harder to read.
For data scientists, pylint’s default rules can be too strict. You’ll likely want to disable checks like missing-docstring on small helper functions or too-many-locals on data-transformation functions that naturally have many variables. We’ll cover configuration in a later section.
flake8: The Fast, Modular Style Enforcer (That’s Actually Three Tools in a Trenchcoat)
What’s actually going on here is that flake8 is not one tool. It’s a wrapper that glues together three separate checkers:
- pyflakes: checks for logical errors like unused imports and undefined names. It parses the source tree but does not import or execute your code, which makes it fast.
- pycodestyle (formerly called
pep8): checks adherence to PEP 8 style conventions — line length, whitespace, indentation. - mccabe: checks cyclomatic complexity, which measures how many branching paths your code has. High complexity means a function is hard to test and understand.
This modular design makes flake8 fast, predictable, and easy to extend with plugins. But it also means flake8 is less semantically deep than pylint — it won’t catch that list shadowing bug we just saw.
The plugin ecosystem is flake8’s superpower. There are plugins for docstring style (flake8-docstrings), import order (flake8-import-order), and even security checks (flake8-bandit). You can add exactly the checks you need without the overhead of pylint’s full semantic analysis.
Let’s run flake8 on our earlier messy snippet:
import pandas as pd
unused_variable = "nobody reads me"
def process_data(data, threshold):
# This line is way too long and has inconsistent spacing
result = data.groupby('category').apply(lambda x: x[x['value']>threshold]['value'].mean()).reset_index()
return result
sample_data = pd.DataFrame({'category': ['A', 'A', 'B', 'B'], 'value': [10, 20, 30, 40]})
output = process_data(sample_data, 'high')
Running flake8:
$ flake8 script.py
script.py:3:1: F841 local variable 'unused_variable' is assigned to but never used
script.py:7:80: E501 line too long (108 > 79 characters)
Now, let’s demystify those error codes:
| Prefix | Source Tool | What It Checks |
|---|---|---|
| E | pycodestyle | PEP 8 style errors (whitespace, line length, indentation) |
| W | pycodestyle | PEP 8 style warnings (less severe style issues) |
| F | pyflakes | Logical errors (unused imports, undefined names) |
| C | mccabe | Cyclomatic complexity (function is too complex) |
So F841 means pyflakes found an unused variable, and E501 means pycodestyle found a line that’s too long. flake8 is fast — it runs in under a second on most projects — and its output is predictable once you understand the error code prefixes.
Head-to-Head: What Each Tool Catches (And What It Misses)
Now here’s the interesting part. Let’s put all three tools side by side with a single, realistic data-science script that contains multiple classes of problems. We’ll run mypy, pylint, and flake8 on the same code and compare what they catch — and what they miss.
Here’s our test script with four deliberate problems clearly marked:
import pandas as pd
# PROBLEM 1: Unused import
import numpy as np
# PROBLEM 2: Redefined built-in
list = [1, 2, 3]
def compute_group_stats(df: pd.DataFrame, threshold) -> pd.DataFrame:
# PROBLEM 3: Type error — threshold is a string, but we compare it to numeric values
# PROBLEM 4: Complexity — deeply nested logic that's hard to follow
if threshold > 0:
if df is not None:
for col in df.columns:
if df[col].dtype == 'float64':
df[col] = df[col].fillna(0)
# PROBLEM 5: Style — this line is way too long
result = df.groupby('category').apply(lambda x: x[x['value'] > threshold]['value'].mean()).reset_index()
return result
# Create sample data
df = pd.DataFrame({'category': ['A', 'A', 'B', 'B'], 'value': [10.0, 20.0, 30.0, 40.0]})
output = compute_group_stats(df, 'high')
Let’s run each tool and see what happens.
mypy output:
$ mypy script.py
script.py:14: error: Unsupported operand types for > ("str" and "int") [operator]
script.py:17: error: Unsupported operand types for > ("str" and "float") [operator]
Found 2 errors in 1 file (checked 1 source file)
mypy catches the type errors on lines 14 and 17 — it sees that threshold is a string but is being compared to numbers. But it completely ignores the unused import, the redefined built-in, the style violation, and the complexity issue. mypy only cares about types.
pylint output:
$ pylint script.py
************* Module script
script.py:4:0: W0611: Unused import numpy (unused-import)
script.py:7:0: C0103: Constant name "list" doesn't conform to UPPER_CASE naming style (invalid-name)
script.py:7:0: W0622: Redefining built-in 'list' (redefined-builtin)
script.py:13:4: R1702: Too many nested blocks (6/5) (too-many-nested-blocks)
script.py:18:0: C0301: Line too long (108/100) (line-too-long)
pylint catches the unused import, the redefined built-in, the nested-block complexity, and the line-too-long style violation. But notice what it doesn’t catch: the type error. Without type annotations, pylint has no way to know that comparing a string to a number is wrong.
flake8 output:
$ flake8 script.py
script.py:4:1: F401 'numpy as np' imported but unused
script.py:18:80: E501 line too long (108 > 79 characters)
flake8 catches the unused import and the line-too-long violation. But it misses the redefined built-in (pyflakes doesn’t check for built-in shadowing) and the type error (flake8 doesn’t do type checking at all).
Here’s the key insight: these tools are complementary, not competitive. The question isn’t “which one should I use?” — it’s “in what order should I run them?” A production data pipeline should run all three. Here’s the summary:
| Problem Type | mypy | pylint | flake8 |
|---|---|---|---|
| Type error (string vs number) | ✓ | ✗ | ✗ |
| Unused import | ✗ | ✓ | ✓ |
| Redefined built-in | ✗ | ✓ | ✗ |
| Excessive nesting/complexity | ✗ | ✓ | ✗ (needs mccabe config) |
| Line too long | ✗ | ✓ | ✓ |
This comparison shows that no single tool catches every issue, making a multi-tool approach necessary for robust code quality.
Where Black Fits In: The Formatter That Ends Style Arguments Forever
We’ve been talking about tools that report problems. Black is different — it fixes them. Black is an opinionated, deterministic code formatter. When you run Black on a file, it rewrites the file in place to match its style rules. There’s no “maybe fix this” — it just fixes everything it can.
Black’s style is a strict subset of PEP 8, but more opinionated. It always uses double quotes. It always adds trailing commas. It always normalizes string prefixes. And it has very few configuration options by design — this is a feature, not a bug. The whole point is to eliminate style debates, and every configuration option is a potential debate.
For data science teams, running Black in a pre-commit hook or CI pipeline means no one ever has to comment on formatting in a code review again. This frees up mental energy for actual logic and data correctness.
Here’s a before-and-after example:
Before Black:
import pandas as pd
def process_data(df,threshold):
result=df.groupby('category').apply(lambda x: x[x['value']>threshold]['value'].mean()).reset_index()
return result
data = {'category': ['A','A','B','B'], 'value': [10,20,30,40]}
df = pd.DataFrame(data)
output = process_data(df, 'high')
After running black script.py:
import pandas as pd
def process_data(df, threshold):
result = (
df.groupby("category")
.apply(lambda x: x[x["value"] > threshold]["value"].mean())
.reset_index()
)
return result
data = {"category": ["A", "A", "B", "B"], "value": [10, 20, 30, 40]}
df = pd.DataFrame(data)
output = process_data(df, "high")
Notice the changes: single quotes became double quotes, inconsistent spacing was fixed, the long line was broken into readable chunks, and trailing commas were added. All of this happened automatically — no human decisions required.
One compatibility note: Black may produce line lengths that flake8’s pycodestyle complains about (E501). The standard fix is to configure flake8 to ignore E501 and let Black own line-length decisions, or to set both tools to the same max-line-length.
Putting It All Together: A Practical Configuration for Data Projects
Let’s translate all this knowledge into a concrete, copy-pasteable setup you can use today. We’ll create a pyproject.toml that configures all four tools to work together without conflicting.
The order matters. Here’s the pipeline we recommend:
- Black first — so formatting is consistent before anything else checks it.
- flake8 next — to catch remaining style issues and simple logic errors.
- mypy next — for type safety on annotated functions.
- pylint last — for deep code smells, once you’re comfortable customizing its rules.
This pipeline catches progressively deeper problems. Here’s the configuration:
# pyproject.toml — place this at the root of your project
[tool.black]
# Black's only real configuration: line length and Python version
line-length = 100
target-version = ['py310']
# Exclude directories that shouldn't be formatted
exclude = '''
/(
\.eggs
| \.git
| \.venv
| build
| dist
)/
'''
[tool.flake8]
# Let Black own line-length decisions — ignore E501
max-line-length = 100
extend-ignore = ["E203", "E501", "W503"]
# Exclude the same directories Black excludes
exclude = [".git", "__pycache__", ".venv", "build", "dist"]
[tool.mypy]
# Start with minimal strictness so you can add hints gradually
python_version = "3.10"
# Don't require type annotations on unannotated functions yet
check_untyped_defs = false
disallow_untyped_defs = false
# But DO warn about obvious type errors in annotated code
warn_return_any = true
warn_unused_configs = true
# Ignore missing imports for libraries without type stubs
ignore_missing_imports = true
[tool.pylint]
# Disable checks that don't apply to data-science workflows
[MESSAGES CONTROL]
disable = [
"missing-docstring", # Not every helper needs a docstring
"too-many-locals", # Data transforms often have many variables
"too-many-arguments", # Some functions genuinely need many parameters
"too-many-branches", # Data cleaning often has many conditions
"too-many-statements", # Pipeline functions can be long
"too-few-public-methods", # Data classes often have few methods
]
And here’s a simple pre-commit-config.yaml that runs all four tools automatically before every commit:
# .pre-commit-config.yaml — place this at the root of your project
repos:
- repo: https://github.com/psf/black
rev: 24.2.0
hooks:
- id: black
language_version: python3.10
- repo: https://github.com/pycqa/flake8
rev: 7.0.0
hooks:
- id: flake8
- repo: https://github.com/pre-commit/mirrors-mypy
rev: v1.8.0
hooks:
- id: mypy
additional_dependencies: [pandas-stubs]
- repo: https://github.com/pycqa/pylint
rev: v3.0.3
hooks:
- id: pylint
args: ["--disable=missing-docstring,too-many-locals"]
Each configuration choice has a plain-English reason:
- Black’s
line-length = 100: The default 88 is fine, but 100 is common in data science where pandas chains get long. - flake8’s
extend-ignore: We tell flake8 to stop complaining about things Black handles (line length, spacing around slices). - mypy’s
check_untyped_defs = false: You don’t have to annotate everything at once. Start with your most critical functions. - pylint’s disabled checks: Data-science code has different patterns than web apps. A function that cleans a DataFrame naturally has many local variables — that’s not a bug, it’s the nature of the work.
What About Ruff? (And Other Tools We Didn’t Cover)
You may have heard about Ruff, a newer tool written in Rust that aims to replace flake8, isort, and several plugins with a single, much faster tool. It’s promising — blazingly fast and increasingly popular. But it’s younger, with fewer plugins, less documentation, and a smaller community than the tools we’ve covered. If you’re starting fresh and want a single tool that does most of what flake8 does (and more), Ruff is worth investigating. But if you want the most StackOverflow answers, the most plugins, and the most battle-tested stability, flake8 + mypy + pylint is still the safe choice.
Other tools worth knowing about:
- pyright: Microsoft’s type checker, used by VS Code’s Pylance. It’s faster than mypy but has different strictness defaults and is less common in open-source data projects.
- bandit: A security linter that checks for things like using
pickleon untrusted data or hardcoded passwords. Worth adding to any project that handles sensitive data. - isort: Sorts your imports. If you’re using flake8 without an import-order plugin, isort fills that gap. (Black can also handle import sorting in some configurations.)
The goal isn’t to use every tool — it’s to build a pipeline that catches the problems you actually have. Start with the three we covered, then add specialized tools as you encounter specific needs.
Recap: What We Learned
- Type checkers (mypy) catch data-type errors before your code runs. They’re your first line of defense against silent logic bugs — the kind that produce plausible-looking numbers instead of crashes.
- Linters come in two flavors: deep semantic analyzers (pylint) that catch code smells and subtle bugs, and fast modular checkers (flake8) that enforce style and catch simple errors.
- Formatters (Black) eliminate style debates by rewriting code to a consistent format automatically. They don’t report problems — they fix them.
- These tools are complementary, not competitive. A production data pipeline should run all three categories. The question isn’t “which one?” but “in what order?”
- Start with flake8 for quick wins, add mypy for type safety as you annotate, then add pylint for deep analysis once you’re comfortable customizing its rules.
- Configuration matters — a poorly configured linter is worse than no linter because it trains you to ignore warnings. Use the
pyproject.tomlwe provided as a starting point.
Check Your Understanding
Remember: What are the three families of code quality tools, and what problem does each solve?
Understand: Why does mypy catch a type error in df["category"].sum() but pylint does not?
Apply: You have a 500-line data pipeline script with no type annotations. Which tool would you add first, and what’s the first annotation you’d write?
Analyze: A colleague says “I don’t need flake8 because I use Black.” What’s wrong with this statement?
Evaluate: You’re choosing between pylint and flake8 for a CI pipeline that must run in under 10 seconds on a 10,000-line codebase. Which do you choose and why?
Create: Write a pyproject.toml section that configures flake8 to ignore line-length checks (letting Black handle them) and to exclude a notebooks/ directory from all checks.
Apply What You Learned is for Supporter and Insider subscribers.
Subscribe to unlock the exercises on this post.
See plansRelated articles
- Python Engineering Under review
A Data Science Glossary 100 Terms Explained In Pla
Before we talk about models or metrics, we need to agree on what “data” actually looks like in Python. When you load a CSV file, you’re not staring at raw numbers — you’re staring at a carefully labeled structure.
- Python Engineering Under review
Sending Automated Emails And Reports From A Python
You just spent three hours building a beautiful pandas report. You cleaned the data, created a summary table, made a chart, and exported everything to a CSV file.
- Python Engineering Under review
Regular Expressions For Data Cleaning The Patterns
messy_data = pd.DataFrame({ 'name': ['Alice Johnson', 'Bob Smith ', ' Charlie Brown', 'Diana Prince', 'Eve Davis'], 'phone': ['(555) 123-4567', '555.123.
- Python Engineering Under review
Dask for Out-of-Core Data: When Your Dataset Doesn't Fit in Memory
You’ve just received a 20GB CSV file. Your laptop has 8GB of RAM. You fire up a Jupyter notebook and type `pd.read_csv('huge_file.csv')`. The kernel churns for a few seconds, then you see it: `MemoryError`.
Looking for something else?
Search every article by title, summary or topic.