#mypy — Public Fediverse posts
Live and recent posts from across the Fediverse tagged #mypy, aggregated by home.social.
-
3 ошибки при работе с dataclasses в Python
Dataclasses появились в Python 3.7 и быстро стали стандартом: меньше бойлерплейта, чем у обычных классов, проще, чем attrs, и не требуют зависимостей. Выглядят настолько просто, что кажется, что ломаться там нечему. Но у них есть три ловушки, которые не видны при написании. Разобрать ошибки
https://habr.com/ru/companies/otus/articles/1034394/
#python #типизация_Python #наследование_классов #dataclasses #mypy #ошибки_python
-
Практики разработки на Python
Привет, Хабр! Меня зовут Роман, я программист в команде «Гравитон» и моя задача в компании — разработка API/CLI интерфейсов и приложений на языке Python. Цель данной статьи в том, чтобы показать как через внедрение «типовых подходов» и вспомогательных библиотек/утилит очень сильно упрощается поддержка проекта в настоящем (при передаче другому человеку или разработке в команде) и в будущем (возобновили проект спустя время). Первое, что нужно сказать — проект на Python это не только сам Python , но и множество технологий используемых вместе (Git, Docker, и т.д.). В этой статье мы сконцентрируемся на самом проекте, а именно с чего начать, что прикрутить, что учитывать при разработке.
-
When installing dependencies, formatting code, linting it, type-checking it, and building docs with #Poetry or #PDM, #Black, #Flake8, #Mypy and #MkDocs would previously take from 2min to several more, it now takes less than 15 seconds for the whole thing, thanks to #uv, #Ruff, #ty and #Zensical.
This is for 5 #Python versions (3.10 to 3.15).
The DX got much better 🥰
-
When installing dependencies, formatting code, linting it, type-checking it, and building docs with #Poetry or #PDM, #Black, #Flake8, #Mypy and #MkDocs would previously take from 2min to several more, it now takes less than 15 seconds for the whole thing, thanks to #uv, #Ruff, #ty and #Zensical.
This is for 5 #Python versions (3.10 to 3.15).
The DX got much better 🥰
-
When installing dependencies, formatting code, linting it, type-checking it, and building docs with #Poetry or #PDM, #Black, #Flake8, #Mypy and #MkDocs would previously take from 2min to several more, it now takes less than 15 seconds for the whole thing, thanks to #uv, #Ruff, #ty and #Zensical.
This is for 5 #Python versions (3.10 to 3.15).
The DX got much better 🥰
-
When installing dependencies, formatting code, linting it, type-checking it, and building docs with #Poetry or #PDM, #Black, #Flake8, #Mypy and #MkDocs would previously take from 2min to several more, it now takes less than 15 seconds for the whole thing, thanks to #uv, #Ruff, #ty and #Zensical.
This is for 5 #Python versions (3.10 to 3.15).
The DX got much better 🥰
-
Is there any way linter/type checker for #Python that can find expressions that never will evaluate to anything other than False based on the type information? E.g. checking if a variable of the type `int` exists within a list of the type `list[str]`? I do use #mypy but it doesn't seem to catch this.
-
Git-хуки, которые не дают коммитить плохой код
Здравствуйте, коллеги программисты! Большинство фейлов в CI — это мелочи: забытый console.log , форматирование, линт, сломанный импорт, файл без теста. Такие ошибки не должны доезжать до сборки или код-ревью. Git-хуки позволяют запускать проверки прямо во время git commit и блокировать коммит, если были обнаружены нарушения. В прошлой статье я рассказывал про скрипты, которые я использую для проверки качества кода в PHP/Laravel. В этой статье я хочу рассказать о скриптах для JavaScript/TypeScript и Python — линтинг, форматирование, тесты, статический анализ и проверка наличия тестов. Все скрипты описанные в статье находятся здесь - https://github.com/prog-time/git-hooks
https://habr.com/ru/articles/993870/
#линтер #git_hooks #javascript #python #eslint #prettier #tsc #vitest #mypy #pytest
-
Git-хуки, которые не дают коммитить плохой код
Здравствуйте, коллеги программисты! Большинство фейлов в CI — это мелочи: забытый console.log , форматирование, линт, сломанный импорт, файл без теста. Такие ошибки не должны доезжать до сборки или код-ревью. Git-хуки позволяют запускать проверки прямо во время git commit и блокировать коммит, если были обнаружены нарушения. В прошлой статье я рассказывал про скрипты, которые я использую для проверки качества кода в PHP/Laravel. В этой статье я хочу рассказать о скриптах для JavaScript/TypeScript и Python — линтинг, форматирование, тесты, статический анализ и проверка наличия тестов. Все скрипты описанные в статье находятся здесь - https://github.com/prog-time/git-hooks
https://habr.com/ru/articles/993870/
#линтер #git_hooks #javascript #python #eslint #prettier #tsc #vitest #mypy #pytest
-
Git-хуки, которые не дают коммитить плохой код
Здравствуйте, коллеги программисты! Большинство фейлов в CI — это мелочи: забытый console.log , форматирование, линт, сломанный импорт, файл без теста. Такие ошибки не должны доезжать до сборки или код-ревью. Git-хуки позволяют запускать проверки прямо во время git commit и блокировать коммит, если были обнаружены нарушения. В прошлой статье я рассказывал про скрипты, которые я использую для проверки качества кода в PHP/Laravel. В этой статье я хочу рассказать о скриптах для JavaScript/TypeScript и Python — линтинг, форматирование, тесты, статический анализ и проверка наличия тестов. Все скрипты описанные в статье находятся здесь - https://github.com/prog-time/git-hooks
https://habr.com/ru/articles/993870/
#линтер #git_hooks #javascript #python #eslint #prettier #tsc #vitest #mypy #pytest
-
Git-хуки, которые не дают коммитить плохой код
Здравствуйте, коллеги программисты! Большинство фейлов в CI — это мелочи: забытый console.log , форматирование, линт, сломанный импорт, файл без теста. Такие ошибки не должны доезжать до сборки или код-ревью. Git-хуки позволяют запускать проверки прямо во время git commit и блокировать коммит, если были обнаружены нарушения. В прошлой статье я рассказывал про скрипты, которые я использую для проверки качества кода в PHP/Laravel. В этой статье я хочу рассказать о скриптах для JavaScript/TypeScript и Python — линтинг, форматирование, тесты, статический анализ и проверка наличия тестов. Все скрипты описанные в статье находятся здесь - https://github.com/prog-time/git-hooks
https://habr.com/ru/articles/993870/
#линтер #git_hooks #javascript #python #eslint #prettier #tsc #vitest #mypy #pytest
-
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.
-
Январский рефакторинг: 7 дней, чтобы почистить Python веб‑проект
Январь - самое удобное время разобрать завалы в проекте. Пол‑команды ещё в отпусках, pull‑реквестов меньше, product owner'ы только вспоминают, что планировали делать в этом году - можно спокойно пройтись по коду и навести порядок. В этой статье пойдёт речь о нескольких косметических действиях, которые, с одной стороны, почти не затрагивают логику программы и не вызывают ненависти у тестировщиков, а с другой - делают код чуть приятнее и дают темы для обсуждения на бэкенд‑созвонах. Мы разложим импорты, перенесём логику из роутов в контроллеры, а из контроллеров - в репозитории и сервисы, избавимся от requirements.txt в пользу нормального менеджера зависимостей и включим mypy.
https://habr.com/ru/articles/983172/
#python #backend #refactoring #architecture #linter #mypy #litestar
-
ty: революция в тайп-чекинге
Всем привет! За последние пару лет компания Astral буквально разрывает Python-мир своими инструментами. Даже если вы не слышали это имя напрямую, с большой вероятностью вы уже пользовались их продуктами — ruff или uv . И это не преувеличение. И ruff , и uv сегодня фактически стали стандартом индустрии. Например, в свежем релизе PyCharm 2025.3 при создании нового проекта по умолчанию инициализируется именно окружение uv , а не привычный venv . Для open source-проекта — это очень серьёзный показатель доверия со стороны экосистемы. Открытый исходный код и массовое принятие инструментов Python-разработчиками дали Astral тот самый «кредит доверия», который компания, судя по всему, пока что уверенно оправдывает. И вот буквально на днях Astral объявили, что их новый «революционный» тайп-чекер ty переходит в стадию бета-тестирования. А если учитывать, что и uv , и ruff формально тоже всё ещё находятся в бете, то можно считать, что ty уже фактически вышел в релиз. Собственно, о нём и поговорим дальше. Если вам интересны подобные материалы — подписывайтесь на Telegram-канал «Код на салфетке» . Там я делюсь гайдами для новичков и полезными инструментами. А прямо сейчас у нас ещё и проходит новогодний розыгрыш.
-
🚀🎉 Hold onto your keyboards, folks! #Astral has unleashed "ty," a lightning-fast #Python #type #checker, because, of course, we needed another one. Written in #Rust, because Python apparently wasn't fast enough for checking itself, "ty" is now in #Beta and ready to bravely enter a market already saturated with the likes of #mypy, #Pyright, and other tools you didn't know you couldn't live without. 🌪️🔧
https://astral.sh/blog/ty #ty #HackerNews #ngated -
🚀🎉 Hold onto your keyboards, folks! #Astral has unleashed "ty," a lightning-fast #Python #type #checker, because, of course, we needed another one. Written in #Rust, because Python apparently wasn't fast enough for checking itself, "ty" is now in #Beta and ready to bravely enter a market already saturated with the likes of #mypy, #Pyright, and other tools you didn't know you couldn't live without. 🌪️🔧
https://astral.sh/blog/ty #ty #HackerNews #ngated -
🚀🎉 Hold onto your keyboards, folks! #Astral has unleashed "ty," a lightning-fast #Python #type #checker, because, of course, we needed another one. Written in #Rust, because Python apparently wasn't fast enough for checking itself, "ty" is now in #Beta and ready to bravely enter a market already saturated with the likes of #mypy, #Pyright, and other tools you didn't know you couldn't live without. 🌪️🔧
https://astral.sh/blog/ty #ty #HackerNews #ngated -
🚀🎉 Hold onto your keyboards, folks! #Astral has unleashed "ty," a lightning-fast #Python #type #checker, because, of course, we needed another one. Written in #Rust, because Python apparently wasn't fast enough for checking itself, "ty" is now in #Beta and ready to bravely enter a market already saturated with the likes of #mypy, #Pyright, and other tools you didn't know you couldn't live without. 🌪️🔧
https://astral.sh/blog/ty #ty #HackerNews #ngated -
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 (https://codeberg.org/harald/gitlogui) the main script of which I called glu. So I am running
pyfix glu
all the time, which reads funny. 😀
-
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 (https://codeberg.org/harald/gitlogui) the main script of which I called glu. So I am running
pyfix glu
all the time, which reads funny. 😀
-
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 (https://codeberg.org/harald/gitlogui) the main script of which I called glu. So I am running
pyfix glu
all the time, which reads funny. 😀
-
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 (https://codeberg.org/harald/gitlogui) the main script of which I called glu. So I am running
pyfix glu
all the time, which reads funny. 😀
-
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 (https://codeberg.org/harald/gitlogui) the main script of which I called glu. So I am running
pyfix glu
all the time, which reads funny. 😀
-
Okay, so, fans of the #TwistedFramework 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.
-
Okay, so, fans of the #TwistedFramework 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.
-
Okay, so, fans of the #TwistedFramework 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.
-
Okay, so, fans of the #TwistedFramework 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.
-
Okay, so, fans of the #TwistedFramework 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.
-
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
- mypycalls for easy use as target builders.
https://codeberg.org/harald/pythonbuilder
#pythonbuilder
#buildmachine
#bashbuilder
#buildsystem
#buildtool
#softwaredevelopment
#programming
#python
#ruff
#mypy -
I'm familiar with #protocol s in #Swift, but just recently discovered #protocol classes in #Python. Like in #Swift they allow for structural subtyping. Now you can require that a parameter passed to a function must conform to a given protocol and #mypy will statically check that for you. You get the best of both worlds -- the safety of static typing and the convenience of duck typing.
-
A Python Language Server, Mypy-compatible
#HackerNews #Python #Language #Server #Mypy-compatible #Programming #Development #Tech #News
-
Redid my #neovim config to keep up with the times (I used many deprecated
plug-ins, and didn't use #lua).I haven't the faintest idea what I'm doing, I just followed a tutorial, got #lazyVim, and a few plug-ins, and I am utterly stomped by how to set up the #python lsp, especially as I want to include #mypy type checking.
The duality of #documentation is that I either get a tutorial that explains nothing and expects you to copy paste, or a manual that goes waaaay over my head.
-
@seungjin I write #python code every day, and type hints are a "syntactic sugar" and are not required at all from the interpreter point of view.
For large projects, it's useful to add hints to "follow" what you are doing, and type checkers like #pyright or #mypy can help to find some bugs, by example when calling a method with wrong parameters types.
It also help for the readability of the code.
-
#ty #mypy - but mypy already compiles itself to c via #mypyc so being faster isn't what I'd be expecting, it will be different and probably find different typing errors since for all the type checkers, it comes down to a matter of opinion. Do you think that will be a runtime error? That's in the future, who knows man.
-
#ty #mypy - but mypy already compiles itself to c via #mypyc so being faster isn't what I'd be expecting, it will be different and probably find different typing errors since for all the type checkers, it comes down to a matter of opinion. Do you think that will be a runtime error? That's in the future, who knows man.
-
#ty #mypy - but mypy already compiles itself to c via #mypyc so being faster isn't what I'd be expecting, it will be different and probably find different typing errors since for all the type checkers, it comes down to a matter of opinion. Do you think that will be a runtime error? That's in the future, who knows man.
-
#ty #mypy - but mypy already compiles itself to c via #mypyc so being faster isn't what I'd be expecting, it will be different and probably find different typing errors since for all the type checkers, it comes down to a matter of opinion. Do you think that will be a runtime error? That's in the future, who knows man.
-
#ty #mypy - but mypy already compiles itself to c via #mypyc so being faster isn't what I'd be expecting, it will be different and probably find different typing errors since for all the type checkers, it comes down to a matter of opinion. Do you think that will be a runtime error? That's in the future, who knows man.
-
Аннотации типов в Python: коротко о главном
Привет, Хабр! Сегодня рассмотрим, как Python, оставаясь динамически типизированным, может приближаться к строгой типизации. Всё дело в аннотациях типов , которые позволяют явно указывать, какие данные ожидаются в переменных, аргументах функций и возвращаемых значениях. Аннотации сами по себе не заставляют Python проверять типы во время выполнения, но их можно использовать вместе с инструментами статического анализа. В первую очередь мы будем работать с mypy — популярным инструментом, который выявляет ошибки до запуска программы.