Skip to content
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

basedmypy 🎉 #51

Merged
merged 10 commits into from
Sep 21, 2024
Merged
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
5 changes: 4 additions & 1 deletion .github/workflows/ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ concurrency:
cancel-in-progress: true

env:
VERSION_UV: '0.4.10'
VERSION_UV: '0.4.13'

jobs:
lint:
Expand Down Expand Up @@ -52,6 +52,9 @@ jobs:
with:
plugins: sp-repo-review

- name: basedmypy
run: uv run mypy

- name: basedpyright
run: uv run basedpyright

Expand Down
2 changes: 2 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -9,8 +9,10 @@ dist/
site/

# Cache
.mypy_cache/
.pytest_cache/
.ruff_cache/
.tox/

# Environments
.env
Expand Down
9 changes: 8 additions & 1 deletion .pre-commit-config.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ ci:
- poetry-lock
- codespell
- ruff
- basedmypy
- basedpyright
- basedpyright-verifytypes

Expand Down Expand Up @@ -54,13 +55,19 @@ repos:
- tomli

- repo: https://github.com/astral-sh/ruff-pre-commit
rev: v0.6.3
rev: v0.6.6
hooks:
- id: ruff
args: [--fix, --show-fixes]

- repo: local
hooks:
- id: basedmypy
name: basedmypy
entry: uv run mypy
language: system
types_or: [python, pyi]

- id: basedpyright
name: basedpyright
entry: uv run basedpyright
Expand Down
1 change: 1 addition & 0 deletions .vscode/extensions.json
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
"davidanson.vscode-markdownlint",
"detachhead.basedpyright",
"editorconfig.editorconfig",
"ms-python.mypy-type-checker",
"ms-python.python"
],
"unwantedRecommendations": ["ms-python.vscode-pylance"]
Expand Down
1 change: 1 addition & 0 deletions .vscode/settings.json
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
"git.branchProtection": ["main"],
"git.defaultBranchName": "main",
"git.pullBeforeCheckout": true,
"mypy-type-checker.args": ["--ide"],
"python.testing.pytestEnabled": true,
"python.testing.unittestEnabled": false
}
4 changes: 2 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -33,12 +33,12 @@
src="https://img.shields.io/badge/pre--commit-enabled-orange?logo=pre-commit"
/>
</a>
<!-- <a href="https://github.com/KotlinIsland/basedmypy">
<a href="https://github.com/KotlinIsland/basedmypy">
<img
alt="mainpy - basedmypy"
src="https://img.shields.io/badge/basedmypy-checked-fd9002"
/>
</a> -->
</a>
<a href="https://detachhead.github.io/basedpyright">
<img
alt="mainpy - basedpyright"
Expand Down
17 changes: 10 additions & 7 deletions mainpy/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -27,11 +27,11 @@ def _infer_debug() -> bool:
if '--debug' in sys.argv[1:]:
return True

env_debug = os.environ.get('DEBUG', '0')
env_debug_str = os.environ.get('DEBUG', '0')
try:
env_debug = int(env_debug)
env_debug = int(env_debug_str)
except ValueError as e:
errmsg = f'Invalid value for `DEBUG` env var: {env_debug!r}'
errmsg = f'Invalid value for `DEBUG` env var: {env_debug_str!r}'
raise OSError(errmsg) from e

return bool(env_debug)
Expand Down Expand Up @@ -70,7 +70,10 @@ def callback(self, /) -> Callable[[], _R_co]: ...
def __call__(self, /) -> _R_co: ...


def _is_click_cmd(func: _F) -> TypeGuard[_HasCallbackFunction[_F]]:
def _is_click_cmd(
func: _HasCallbackFunction[object] | _F,
/,
) -> TypeGuard[_HasCallbackFunction[_F]]:
return func.__module__ == 'click.core' and hasattr(func, 'callback')


Expand All @@ -84,7 +87,7 @@ def _unwrap_click(func: _HasCallbackFunction[object] | _F, /) -> _F | object:
return func


def _is_main_func(func: Callable[..., object], /) -> bool:
def _is_main_func(func: Callable[[], object], /) -> bool:
return _unwrap_click(func).__module__ == '__main__'


Expand Down Expand Up @@ -163,15 +166,15 @@ def _main(_func: _F, /) -> _F:

return _main

if not callable(func):
if not callable(func): # type: ignore[redundant-expr]
errmsg = f'expected a callable, got {type(func)}'
raise TypeError(errmsg)

if not _is_main_func(func):
import inspect

frame = inspect.currentframe()
if not frame or frame.f_globals.get('__name__') != '__main__':
if not frame or frame.f_globals.get('__name__') != '__main__': # type: ignore[no-any-expr]
return func

if debug is None:
Expand Down
34 changes: 27 additions & 7 deletions pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -67,10 +67,11 @@ dev-dependencies = [
"typing_extensions>=4.12.2",
"uvloop; sys_platform != 'win32'",

"basedmypy>=2.6.0,<3",
"basedpyright>=1.17.5,<2",
"codespell>=2.3.0,<3",
"pytest>=8.3.3,<9",
"ruff>=0.6.5,<0.7",
"ruff>=0.6.6,<0.7",

"pre-commit>=3.8.0",
"tox>=4.20.0",
Expand Down Expand Up @@ -105,15 +106,35 @@ venvPath = "."
reportUnreachable = false # unavoidable with `sys.version_info` conditionals


[tool.mypy]
packages = ["mainpy", "tests"]
exclude = ["examples/"]
python_version = "3.9"

strict = true
warn_unreachable = false
# https://github.com/KotlinIsland/basedmypy/issues/765
disable_bytearray_promotion = true
disable_memoryview_promotion = true
# required by repo-review
enable_error_code = ["ignore-without-code", "redundant-expr", "truthy-bool"]

[[tool.mypy.overrides]]
module = ["tests.*"]
# blame pytest for these
disallow_any_expr = false
disallow_any_explicit = false
disallow_any_decorated = false


[tool.repo-review]
ignore = [
"PY004", # README.md >> docs/
"PC110", # optype's style >> (black | ruff-format)
"PC140", # (based)pyright >> mypy (by several orders of magnitude)
"PY004", # no docs
"PC110", # no autoformat
"PC140", # basedmypy > mypy
"PC170", # no .rst
"PC180", # no .css or .js
"MY", # (based)pyright >> mypy (by several orders of magnitude)
"RTD", # README.md >> rtd
"RTD", # no RTD
]


Expand Down Expand Up @@ -221,7 +242,6 @@ docstring-code-format = true
indent-style = "space"
line-ending = "lf"
quote-style = "single"
skip-magic-trailing-comma = true


[tool.tox]
Expand Down
5 changes: 4 additions & 1 deletion tests/test_integration.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,8 @@
# ruff: noqa: ERA001
import uuid
from collections.abc import Callable
from pathlib import Path
from typing import cast

import pytest

Expand Down Expand Up @@ -39,7 +42,7 @@ def test_output(pytester: pytest.Pytester, template: str):
output_expect = uuid.uuid4().hex
script = template.format(output_expect)

fh = pytester.makepyfile('test.py') # pyright: ignore[reportUnknownMemberType]
fh = cast(Callable[[str], Path], pytester.makepyfile)('test.py')
_ = fh.write_text(script)

result = pytester.runpython(fh)
Expand Down
17 changes: 12 additions & 5 deletions tests/test_mainpy.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,23 +4,30 @@
import asyncio
import importlib.util
import inspect
from typing import Any, Callable, TypeVar
from typing import TYPE_CHECKING, Callable, TypeVar

import pytest

import mainpy as mp


_F = TypeVar('_F', bound=Callable[..., Any])
if TYPE_CHECKING:
from collections.abc import Generator


def _patch_module(monkeypatch: pytest.MonkeyPatch, module: str):
_F = TypeVar('_F', bound=Callable[..., object])


def _patch_module(
monkeypatch: pytest.MonkeyPatch,
module: str,
) -> Callable[[_F], _F]:
# Patch the module name in the frame
frame = inspect.currentframe()
assert frame is not None
monkeypatch.setitem(frame.f_globals, '__name__', module)

def __patch_module(fn: _F) -> _F:
def __patch_module(fn: _F, /) -> _F:
# Patch the module name in the function
monkeypatch.setattr(fn, '__module__', module)
return fn
Expand All @@ -29,7 +36,7 @@ def __patch_module(fn: _F) -> _F:


@pytest.fixture()
def no_uvloop():
def no_uvloop() -> Generator[Callable[[], bool], None, None]:
orig = mp._infer_uvloop
mp._infer_uvloop = lambda: False

Expand Down
Loading