DEV Community

Cover image for Аннотация типов в миксинах
Гимаев Наиль
Гимаев Наиль

Posted on • Edited on

1

Аннотация типов в миксинах

При написании кода я стараюсь устранить все замечания линтера PyCharm. Но с миксинами сделать это не так просто
Возьмём для примера, вот такой миксин:

Image description
Линтер не доволен, т.к. не понимает при чём тут self.request. Этот вопрос я решал просто, я просто затыкал рот линтеру.
image
Линтер доволен и молчит, даже если есть явная проблема.
В конце концов, безмолвный линтер стал проблемой, и я решил разобраться в вопросе. Я заглянул в документацию mypy из которой узнал, как можно решить множество замечаний линтера связанные с типами и аннотацией, но не для миксинов. К счастью, я не первый кто задумался об этом, и хоть не с первого раза, я нашёл ответ на StackOverflow, но вам я его не покажу, т.к. не могу найти его снова. Зато я могу показать, как выглядит то, что в итоге получилось:

from typing import TypeVar

T = TypeVar('T')


def mixin_for(_: T) -> T:
    return object
Enter fullscreen mode Exit fullscreen mode

Функция mixin_for позволяет сказать линтеру к какому классу будет подмешиваться миксин.
image
Заодно получаем автодополнение кода.

На этом всё.

Глоссарий

  • миксин - mixin, примесь
  • линтер - linter, статический анализатор кода

Quadratic AI

Quadratic AI – The Spreadsheet with AI, Code, and Connections

  • AI-Powered Insights: Ask questions in plain English and get instant visualizations
  • Multi-Language Support: Seamlessly switch between Python, SQL, and JavaScript in one workspace
  • Zero Setup Required: Connect to databases or drag-and-drop files straight from your browser
  • Live Collaboration: Work together in real-time, no matter where your team is located
  • Beyond Formulas: Tackle complex analysis that traditional spreadsheets can't handle

Get started for free.

Watch The Demo 📊✨

Top comments (0)

Image of PulumiUP 2025

Let's talk about the current state of cloud and IaC, platform engineering, and security.

Dive into the stories and experiences of innovators and experts, from Startup Founders to Industry Leaders at PulumiUP 2025.

Register Now

AWS Security LIVE!

Hosted by security experts, AWS Security LIVE! showcases AWS Partners tackling real-world security challenges. Join live and get your security questions answered.

Tune in to the full event

DEV is partnering to bring live events to the community. Join us or dismiss this billboard if you're not interested. ❤️