Skip to content

chore: improve type hints#2638

Merged
Kludex merged 1 commit intoKludex:masterfrom
waketzheng:master
May 31, 2025
Merged

chore: improve type hints#2638
Kludex merged 1 commit intoKludex:masterfrom
waketzheng:master

Conversation

@waketzheng
Copy link
Contributor

Summary

Only improve type hints, does not change any code logic.

Checklist

  • I understand that this PR may be closed in case there was no previous discussion. (This doesn't apply to typos!)
  • I've added a test for each change that was introduced, and I tried as much as possible to make a single atomic change.
  • I've updated the documentation accordingly.

Description

Changes are made by the following script:

# refactor.py
"""
Change typing import style for python files
    'import typing' -> 'from typing import Any,cast,...'
    'typing.Any' -> 'Any'
    'typing.cast' -> 'cast'
    'typing.ContextManager' -> 'contextlib.AbstractContextManager'
"""

import re
from pathlib import Path

for d in (Path().resolve().name, "tests"):
    for p in Path(d).rglob("*.py"):
        s = p.read_text()
        t = "import typing"
        if t not in s:
            continue
        pattern = re.compile(r"(\W?)typing\.(\w+)(\W)")
        ws = set([i[1] for i in pattern.findall(s)])
        imports = "from typing import "
        for cm in ("ContextManager", "AsyncContextManager"):
            if cm not in ws:
                continue
            # typing.ContextManager -> contextlib.AbstractContextManager
            # typing.AsyncContextManager -> contextlib.AbstractAsyncContextManager
            ws.remove(cm)
            imports = f"from contextlib import Abstract{cm}\n" + imports
            s = re.sub(rf"(\W?)typing\.({cm})(\W)", r"\1Abstract\2\3", s)
        s = pattern.sub(r"\1\2\3", s)
        imports += ", ".join(sorted(ws))
        s = s.replace(t, imports)
        p.write_text(s)
        print(p, "updated.")
  • Command line:
python refactor.py
./scripts/lint
./scripts/check

@Kludex Kludex merged commit ce129ff into Kludex:master May 31, 2025
16 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants