Skip to content

add mypy support #106

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 5 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions copier.yml
Original file line number Diff line number Diff line change
Expand Up @@ -151,11 +151,11 @@ use_precommit:
default: "{% if template_mode != 'minimal' %}yes{% else %}no{% endif %}"
help: "Do you want to pre-commit hooks to format your code on save?"

use_types:
use_mypy:
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I originally went with use_types, as folks might want to run pyright or another alternative to mypy. It's fair to commit to mypy, though, especially as this is targeted more at beginners.

when: "{{ template_mode == 'custom' }}"
type: bool
default: "{% if template_mode != 'minimal' %}yes{% else %}no{% endif %}"
help: "Do you want to use typing annotations and type check your code?"
help: "Do you want to use mypy to check type annotations?"

############### All things related to testing ###################

Expand Down
2 changes: 1 addition & 1 deletion includes/pyproject/deps-pep-621.toml.jinja
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@ style = [
"ruff",
]
{% endif %}
{%- if use_types -%}
{%- if use_mypy -%}
types = [
"mypy",
]
Expand Down
1 change: 1 addition & 0 deletions pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,7 @@ ignore = [
"S602",
"S603",
"S607",
"FBT001", # boolean positional arguments are fine always but especially in tests
]

[tool.ruff.lint.isort]
Expand Down
36 changes: 14 additions & 22 deletions template/pyproject.toml.jinja
Original file line number Diff line number Diff line change
Expand Up @@ -45,7 +45,7 @@ classifiers = [
{% endif -%}
"Operating System :: OS Independent",
"Programming Language :: Python :: 3 :: Only",
{%- if use_types %}
{%- if use_mypy %}
"Typing :: Typed",
{%- endif %}
]
Expand All @@ -72,7 +72,7 @@ dev = [
{%- if documentation!="" %}docs,{% endif -%}
{%- if use_test %}tests,{% endif -%}
{%- if use_lint %}style,{% endif -%}
{%- if use_types %}types,{% endif -%}
{%- if use_mypy %}types,{% endif -%}
audit]",
{%- endif %}
]
Expand Down Expand Up @@ -179,7 +179,7 @@ lines-after-imports = 1

[tool.pydoclint]
style = "numpy"
{%- if use_types %}
{%- if use_mypy %}
arg-type-hints-in-signature = true
{%- else %}
arg-type-hints-in-signature = false
Expand All @@ -192,24 +192,16 @@ exclude = "_version.py"
{%- endif %}
{%- endif %}

{%- if use_types %}
# TODO: Adjust mypy configuration.
#[tool.mypy]
#plugins = [
# "pydantic.mypy",
#]

# Stop mypy from complaining about missing types from imports.
#[[tool.mypy.overrides]]
#module = [
# "pandas",
#]
#ignore_missing_imports = true

#[tool.pydantic-mypy]
#init_forbid_extra = true
#init_typed = true
#warn_required_dynamic_aliases = true
{%- if use_mypy %}
[tool.mypy]
packages = ["{{ package_name }}"]
warn_redundant_casts = true
warn_unused_ignores = true
show_error_context = true
show_column_numbers = true
show_error_code_links = true
pretty = true
color_output = true
{%- endif %}

{%- if use_hatch_envs %}
Expand Down Expand Up @@ -242,7 +234,7 @@ extra-dependencies = [
[tool.hatch.envs.audit.scripts]
check = ["pip-audit"]

{%- if use_types %}
{%- if use_mypy %}
[tool.hatch.envs.types]
description = """Check the static types of the codebase."""
dependencies = [
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -67,7 +67,7 @@ jobs:
- name: Check dependencies
run: hatch run audit:check

{%- if use_types %}
{%- if use_mypy %}
- name: Check types
run: hatch run types:check
{%- endif %}
Expand All @@ -82,4 +82,27 @@ jobs:
run: bash <(curl -s https://codecov.io/bash)
{%- endraw %}
{%- endif %}
{%- else %}

- name: Install package
run: python -m pip install '.[dev]'

- name: Check dependencies
run: python -m pip-audit

{%- if use_mypy %}

- name: Check types
run: python -m mypy
{%- endif %}

{%- if use_test %}

- name: Run tests
run: python -m pytest --cov={{ package_name }} --cov-report=term-missing

- name: Report coverage
shell: bash
run: bash <(curl -s https://codecov.io/bash)
{%- endif %}
{%- endif %}
3 changes: 2 additions & 1 deletion tests/conftest.py
Original file line number Diff line number Diff line change
@@ -1,8 +1,9 @@
"""Provide fixtures to the entire test suite."""

import shutil
from collections.abc import Generator
from pathlib import Path
from typing import TYPE_CHECKING, Generator
from typing import TYPE_CHECKING

import pytest
from _pytest.monkeypatch import MonkeyPatch
Expand Down
53 changes: 51 additions & 2 deletions tests/test_template_init.py
Original file line number Diff line number Diff line change
Expand Up @@ -22,8 +22,10 @@
import os
import subprocess
import sys
import venv
from datetime import datetime, timezone
from pathlib import Path
from textwrap import dedent
from typing import Callable

import pytest
Expand Down Expand Up @@ -196,7 +198,7 @@ def test_docs_build(documentation: str, generated: Callable[..., Path], use_hatc
)
run_command("sphinx-apidoc -o docs/api src/alien_clones", project)
# prepend pythonpath so we don't have to actually install here...
run_command(f"PYTHONPATH={str(project/'src')} sphinx-build -W -b html docs docs/_build", project)
run_command(f"PYTHONPATH={project/'src'!s} sphinx-build -W -b html docs docs/_build", project)

run_command("pre-commit run --all-files -v check-readthedocs", project)

Expand Down Expand Up @@ -229,7 +231,7 @@ def test_non_hatch_deps(
project = generated(
use_hatch_envs=False,
use_lint=True,
use_types=True,
use_mypy=True,
use_test=True,
use_git=False,
documentation=documentation,
Expand All @@ -254,3 +256,50 @@ def test_non_hatch_deps(
if documentation != "no":
assert "docs" in optional_deps
assert any(dep.startswith(documentation) for dep in optional_deps["docs"])

@pytest.mark.parametrize("use_hatch_envs", [True, False])
@pytest.mark.parametrize("valid", [True, False])
def test_mypy(generated: Callable[..., Path], use_hatch_envs: bool, valid: bool, tmp_path: Path):
"""Mypy type checking works out of the box."""
if valid:
module = dedent("""
def f1(value: int, other: int = 2) -> int:
return value * other

def f2(value: int) -> float:
return f1(value, 5) / 2
""")
else:
module = dedent("""
def f1(value: int, other: int = 2) -> int:
return value * other

def f2(value: str) -> str:
return f1(value, 5) / 2
""")

root = generated(use_hatch_envs=use_hatch_envs, use_mypy=True)
pkg_path = root / "src" / "alien_clones"
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Can the name be gotten from the generated project somehow? Would be better than hard-coding it here.

module_path = pkg_path / "typechecking.py"
with module_path.open("w") as f:
f.write(module)

if use_hatch_envs:
command = "hatch run types:check"
else:
venv_path = tmp_path / ".venv"
if sys.platform == "win32":
mypy_path = venv_path / "Scripts" / "mypy.exe"
python_path = venv_path / "Scripts" / "python.exe"
else:
mypy_path = venv_path / "bin" / "mypy"
python_path = venv_path / "bin" / "python"
venv.EnvBuilder(with_pip=True).create(venv_path)
run_command(f'{python_path!s} -m pip install -e ".[types]"', root)
command = f"{mypy_path!s} {pkg_path!s}"

if valid:
run_command(command, root)
else:
with pytest.raises(subprocess.CalledProcessError):
run_command(command, root)