#Mypy

2026-02-07

Git-хуки, которые не дают коммитить плохой код

Здравствуйте, коллеги программисты! Большинство фейлов в CI — это мелочи: забытый console.log , форматирование, линт, сломанный импорт, файл без теста. Такие ошибки не должны доезжать до сборки или код-ревью. Git-хуки позволяют запускать проверки прямо во время git commit и блокировать коммит, если были обнаружены нарушения. В прошлой статье я рассказывал про скрипты, которые я использую для проверки качества кода в PHP/Laravel. В этой статье я хочу рассказать о скриптах для JavaScript/TypeScript и Python — линтинг, форматирование, тесты, статический анализ и проверка наличия тестов. Все скрипты описанные в статье находятся здесь - github.com/prog-time/git-hooks

habr.com/ru/articles/993870/

#линтер #git_hooks #javascript #python #eslint #prettier #tsc #vitest #mypy #pytest

2026-02-05

The only criticism I have of types in Python:

Python is a really good dynamically typed language. Since classes are themselves instances of a class-describing object, you can do what other languages have to do with text-transforming macros by just treating the class as mutable and dynamically adding things like methods.

... and then the type system kicks your ass for doing that, so you're left with a few not-great options.

#python #mypy

[Mypy에서 Ty로: Ruff 제작사가 만든 초고속 Rust 기반 Python 타입 체커 도입 가이드

Astral사는 새로운 Rust 기반 Python 타입 체커인 'ty'를 출시했습니다. 이 도구는 Mypy의 엄격 모드와 유사한 기능을 제공하며, 빠른 실행 속도를 자랑합니다. 설치 및 사용 방법, GitHub Actions와의 통합 방법, 그리고 커뮤니티 기반의 pre-commit 워크어라운드에 대한 가이드가 제공되었습니다.

news.hada.io/topic?id=25713

#python #typechecking #rust #ty #mypy

2026-01-09

Январский рефакторинг: 7 дней, чтобы почистить Python веб‑проект

Январь - самое удобное время разобрать завалы в проекте. Пол‑команды ещё в отпусках, pull‑реквестов меньше, product owner'ы только вспоминают, что планировали делать в этом году - можно спокойно пройтись по коду и навести порядок. В этой статье пойдёт речь о нескольких косметических действиях, которые, с одной стороны, почти не затрагивают логику программы и не вызывают ненависти у тестировщиков, а с другой - делают код чуть приятнее и дают темы для обсуждения на бэкенд‑созвонах. Мы разложим импорты, перенесём логику из роутов в контроллеры, а из контроллеров - в репозитории и сервисы, избавимся от requirements.txt в пользу нормального менеджера зависимостей и включим mypy.

habr.com/ru/articles/983172/

#python #backend #refactoring #architecture #linter #mypy #litestar

2025-12-29

I think that my Python code editor is ready for 2026!

Using Flycheck and happy about how simple it was to add a custom syntax checker. 👏

I've configured my Emacs to auto-switch between flake8 or ruff, and mypy or the brand new type checker "ty" depending on what's in the local environment.

Pull request to my emacs configuration with details about the implementation:
github.com/DavidVujic/my-emacs

#python #emacs #mypy #flake8 #ruff #ty #elisp #flycheck

洪 民憙 (Hong Minhee) :nonbinary:hongminhee@hollo.social
2025-12-27

With high-performance #Python type checkers like #Pyright, #Pyrefly, and #ty now available, what's the value proposition of #Mypy? Is it the reference implementation? Or does Mypy still have the most features? I'm not trying to knock Mypy, I'm genuinely asking because I don't know.

2025-12-23

ty: революция в тайп-чекинге

Всем привет! За последние пару лет компания Astral буквально разрывает Python-мир своими инструментами. Даже если вы не слышали это имя напрямую, с большой вероятностью вы уже пользовались их продуктами — ruff или uv . И это не преувеличение. И ruff , и uv сегодня фактически стали стандартом индустрии. Например, в свежем релизе PyCharm 2025.3 при создании нового проекта по умолчанию инициализируется именно окружение uv , а не привычный venv . Для open source-проекта — это очень серьёзный показатель доверия со стороны экосистемы. Открытый исходный код и массовое принятие инструментов Python-разработчиками дали Astral тот самый «кредит доверия», который компания, судя по всему, пока что уверенно оправдывает. И вот буквально на днях Astral объявили, что их новый «революционный» тайп-чекер ty переходит в стадию бета-тестирования. А если учитывать, что и uv , и ruff формально тоже всё ещё находятся в бете, то можно считать, что ty уже фактически вышел в релиз. Собственно, о нём и поговорим дальше. Если вам интересны подобные материалы — подписывайтесь на Telegram-канал «Код на салфетке» . Там я делюсь гайдами для новичков и полезными инструментами. А прямо сейчас у нас ещё и проходит новогодний розыгрыш.

habr.com/ru/articles/979752/

#uv #ruff #ty #mypy #type_checking #python #rust #astral

2025-12-20

I’ve published a PR that adds an `unsafe-subtype` error to mypy, primarily to address unsafe `date`/`datetime` use cases. I would appreciate any reviews or feedback. Thanks! github.com/python/mypy/pull/20 #python #typing #mypy

2025-12-18

I have been investigating this:
```Python
from numbers import Real
def positive(x: Real) -> bool:
return x > 0 # Type Check failed!
```

#PEP 484 said that one should use `float` instead, but this does not solve for other numerical types e.g. #GMP numbers or #NumPy numbers.

And I found some old threads like github.com/python/typing/issue
github.com/python/mypy/issues/
discuss.python.org/t/numeric-g
discuss.python.org/t/clarifyin

And it seems like none has make any real progress.

To my understanding, ABC should also provides a good protocol for typing, just like typeclasses in #Haskell.

#Python #Typing #MyPy #Pyright

N-gated Hacker Newsngate
2025-12-16

🚀🎉 Hold onto your keyboards, folks! has unleashed "ty," a lightning-fast , because, of course, we needed another one. Written in , because Python apparently wasn't fast enough for checking itself, "ty" is now in and ready to bravely enter a market already saturated with the likes of , , and other tools you didn't know you couldn't live without. 🌪️🔧
astral.sh/blog/ty

2025-11-12

I have a script called pyfix which runs mypy and ruff to

- have strong typing
- have a fixed and orderly import order
- have the file always formatted in the same way
- detect programming errors and redundancies.

Now I am working on gitlogui (codeberg.org/harald/gitlogui) the main script of which I called glu. So I am running

pyfix glu

all the time, which reads funny. 😀

#python #gitlogui #mypy #ruff #strongTyping #linting

Charles Tapley Hoytcthoyt@scholar.social
2025-10-03

have you ever annotated a TypedDict onto the **kwargs fuction and want Sphinx to automatically add it to the function's docstring?

class GreetingKwargs(TypedDict):
name: Annotated[str, Doc("the name of the person to greet")]

def greet(**kwargs: Unpack[GreetingKwargs]):
"""Greet a person.

:returns: A nice greeting
"""
return f"hello, {kwargs['name']}!"

i wrote a plugin for it github.com/cthoyt/sphinx-unpack

#python #sphinx #mypy #typing

Automatically generated documentation
2025-10-02

Python type-checkers should infer Final from all-caps named variables. github.com/python/mypy/issues/ Consider adding a thumb up :) #python #typing #mypy

MAX_SIZE = 9000
MAX_SIZE += 1  # Error reported by type checker
# (code snippet that illustrates the idea)
2025-09-29

Introducting: `stormcheck mypy --edu` , type check your code, and learn #Python fundamentals at the same time!

The error messages themselves are ordered by difficulty level, and each category has a dedicated tutorial built-in to the CLI!

My goal was to create a tool that can teach beginners as they work, but still be useful to professionals who already know their craft.

We call this Compassion-Driven-Development

Once finished, I plan on putting this on all my open-source projects to help contributors who are new to Python.

Soon: RUFF checking as well?? What else would a tool like this benefit from?

#OpenSource #CLI #mypy #education #programming #teaching #learning

2025-09-24

I have a Python static typing conundrum. I'd like a solution that works with mypy.

I have a function which fills out a list, albeit not "in order", so it's inconvenient to write it as a list comprehension or similar.

So, I fill the list with [None] and assert that all the Nones are gone by the time it returns.

However, the assertion I wrote does NOT convince mypy that the type of result now matches the return type of f, and I get a diagnostic: Incompatible return value type (got "list[int | None]", expected "list[int]")

def f() -> list[int]:
result: list[int|None] = [None] * 3
result[0] = 1
result[2] = 2
result[1] = 3
assert not any(i is None for i in result)
return result

Any hints? Can I do something besides cast the return value?

Solution: I used TypeGuard (python 3.10+) as suggested in replies. I can accept the runtime overhead.

#askMastodon #python #mypy #answered

Luke T. Shumakerlukeshu@social.coop
2025-08-16

At this point, I think writing #Python without #mypy --strict is insane.

And a side-effect is that if you add a new dependency, there's a solid chance you have to spend a day writing stubs for it. Helps keep bloat down and also means you get a decent tour of the library.

Glyphglyph
2025-08-04

Okay, so, fans of the help me out here:

I am mucking around with writing a simple new thing that, in order to have type annotations that aren't *completely* useless, needs to deal with the fact that Protocol and Factory aren't annotated.

But adding annotations makes the entire framework notice that the pattern of paired-Protocol-and-Factory subclasses are inherently LSP violations, because .protocol and .factory are writable attributes and thus invariant.

2025-08-03

The pythonbuilder got a few improvements. Apart from introducing ruff as a consistent python code formatter and for linting in addition to mypy, it got a new module pbpython.py which wraps

- ruff check
- ruff format
- mypy

calls for easy use as target builders.

codeberg.org/harald/pythonbuil

#pythonbuilder
#buildmachine
#bashbuilder
#buildsystem
#buildtool
#softwaredevelopment
#programming
#python
#ruff
#mypy

2025-07-31

I have been addicted to #mypy type checking my #python projects over the last week. After creating several helper scripts for the process of getting from >1000 errors to 0, I am working on making a centralized library to #opensource !

If you use the `--edu` flag, the system will show you educational guidance, and also showcase tutorials that are built-in to the CLI! (That feature isn't in yet, but I am excited to build it)

All of the lessons I have learned from making my projects MyPy Compliant, I hope I can use this tool to teach others, and also help myself with all my future Python Projects!

#programming #development

Client Info

Server: https://mastodon.social
Version: 2025.07
Repository: https://github.com/cyevgeniy/lmst