Plugin for mypy to support zope.interface

Overview

Plugin for mypy to support zope.interface

Build Status Coverage Status Checked with mypy

The goal is to be able to make zope interfaces to be treated as types in mypy sense.

Usage

Install both mypy and mypy-zope:

pip install mypy-zope

Edit mypy.ini file in your project to enable the plugin:

[mypy]
namespace_packages=True
plugins=mypy_zope:plugin

You're done! You can now check your project with mypy:

mypy your-project-dir

What is supported?

You can browse sample files to get some sense on what features are supported and how they are handled.

Interface declarations

You can define the interface and provide implementation:

class IAnimal(zope.interface.Interface):
    def say() -> None:
        pass

@zope.interface.implementer(IAnimal)
class Cow(object):
    def say(self) -> None:
        print("Moooo")

animal: IAnimal = Cow()
animal.say()

The interface IAnimal will be treated as superclass of the implementation Cow: you will be able to pass an implementation to functions accepting an interface and all the usual polymorphism tricks.

It is also possible to declare the implementation using classImplements function with the same effect as @imlementer decorator. This is useful if you do not control the code that defines the implementation class.

classImplements(Cow, IAnimal)

animal: IAnimal = Cow()

Schema field type inference

A limited support for defining attributes as zope.schema.Fields is supported too:

class IAnimal(zope.interface.Interface):
    number_of_legs = zope.schema.Int(title="Number of legs")

@zope.interface.implementer(IAnimal)
class Cow(object):
    number_of_legs = 4

In context of an interface, some known zope.schema field types are automatically translated to python types, so the number_of_legs attributes is getting the type int in the example above. That means mypy will report an error if you try to assign string to that attribute on an instance of IAnimal type. Custom fields or fields not recognized by plugin are given type Any.

Field properties

Support for zope.schema.FieldProperty is limited, because type information is not transferred from an interface to implementation attribute, but mypy doesn't report errors on sources like this:

class IAnimal(zope.interface.Interface):
    number_of_legs = zope.schema.Int(title="Number of legs")

@zope.interface.implementer(IAnimal)
class Cow(object):
    number_of_legs = zope.schema.FieldProperty(IAnimal['number_of_legs'])

The type of Cow.number_of_legs will become Any in this case, even though IAnimal.number_of_legs would be inferred as int.

Adaptation pattern

Zope interfaces can be "called" to lookup an adapter, like this:

class IEUPowerSocket(zope.interface.Interface):
    def fit():
        pass

adapter = IEUPowerSocket(us_plug)
adapter.fit()

Type of the adapter variable will be set to IEUPowerSocket.

Conditional type inference

When using zope.interface's implementedBy() and providedBy() methods in an if statement, mypy will know which type it is inside those statements.

if IAnimal.providedBy(ob):
    ob.number_of_legs += 2

Declaration of overloaded methods in interfaces

Similarly to regular overloaded functions, @overload declarations are supported in interfaces as well:

class IAnimal(zope.interface.Interface):
    @overload
    def say() -> str:
        ...

    @overload
    def say(count: int) -> List[str]:
        ...

    def say(count: int = None) -> Union[str, List[str]]:
        pass


@zope.interface.implementer(IAnimal)
class Cow(object):
    @overload
    def say(self) -> str:
        ...

    @overload
    def say(self, count: int) -> List[str]:
        ...

    def say(self, count: int = None) -> Union[str, List[str]]:
        if count is None:
            return "Mooo"
        return ["Mooo"] * count

Type stubs for zope.interface and zope.schema

mypy-zope ships with type stubs (*.pyi files) for zope.interface and zope.schema packages. They are enabled automatically as soon as plugin is enabled.

What is not supported?

These zope.interface features are not supported:

  • Declaring modules as interface implementers.
  • Type inference for zope.schema.List and zope.schema.Dict fields.
  • Stub files are largely incomplete
  • Interface compatibility checker will not type-check non-method attributes

Under development!

Currently the project is in a very early stage of development and might not be practically usable yet. Suggestions and pull requests are welcomed!

Owner
Shoobx
Shoobx
The mypy playground. Try mypy with your web browser.

mypy-playground The mypy playground provides Web UI to run mypy in the sandbox: Features Web UI and sandbox for running mypy eas

Yusuke Miyazaki 57 Jan 02, 2023
A plugin for Flake8 that checks pandas code

pandas-vet pandas-vet is a plugin for flake8 that provides opinionated linting for pandas code. It began as a project during the PyCascades 2019 sprin

Jacob Deppen 146 Dec 28, 2022
The official GitHub mirror of https://gitlab.com/pycqa/flake8

Flake8 Flake8 is a wrapper around these tools: PyFlakes pycodestyle Ned Batchelder's McCabe script Flake8 runs all the tools by launching the single f

Python Code Quality Authority 2.6k Jan 03, 2023
A plugin for Flake8 finding likely bugs and design problems in your program. Contains warnings that don't belong in pyflakes and pycodestyle.

flake8-bugbear A plugin for Flake8 finding likely bugs and design problems in your program. Contains warnings that don't belong in pyflakes and pycode

Python Code Quality Authority 869 Dec 30, 2022
Pylint plugin to enforce some secure coding standards for Python.

Pylint Secure Coding Standard Plugin pylint plugin that enforces some secure coding standards. Installation pip install pylint-secure-coding-standard

Nguyen Damien 2 Jan 04, 2022
mypy plugin for loguru

loguru-mypy A fancy plugin to boost up your logging with loguru mypy compatibility logoru-mypy should be compatible with mypy=0.770. Currently there

Tomasz Trębski 13 Nov 02, 2022
An extension for flake8 that forbids some imports statements in some modules.

flake8-obey-import-goat An extension for flake8 that forbids some imports statements in some modules. Important: this project is developed using DDD,

Ilya Lebedev 10 Nov 09, 2022
flake8 plugin which checks that typing imports are properly guarded

flake8-typing-imports flake8 plugin which checks that typing imports are properly guarded installation pip install flake8-typing-imports flake8 codes

Anthony Sottile 50 Nov 01, 2022
Stubs with type annotations for ordered-set Python library

ordered-set-stubs - stubs with type annotations for ordered-set Python library Archived - now type annotations are the part of the ordered-set library

Roman Inflianskas 2 Feb 06, 2020
coala provides a unified command-line interface for linting and fixing all your code, regardless of the programming languages you use.

"Always code as if the guy who ends up maintaining your code will be a violent psychopath who knows where you live." ― John F. Woods coala provides a

coala development group 3.4k Dec 29, 2022
Silence mypy by adding or removing code comments

mypy-silent Automatically add or remove # type: ignore commends to silence mypy. Inspired by pylint-silent Why? Imagine you want to add type check for

Wu Haotian 8 Nov 30, 2022
Rust like Option and Result types in Python

Option Rust-like Option and Result types in Python, slotted and fully typed. An Option type represents an optional value, every Option is either Some

45 Dec 13, 2022
Mypy stubs, i.e., type information, for numpy, pandas and matplotlib

Mypy type stubs for NumPy, pandas, and Matplotlib This is a PEP-561-compliant stub-only package which provides type information for matplotlib, numpy

Predictive Analytics Lab 194 Dec 19, 2022
Type stubs for the lxml package

lxml-stubs About This repository contains external type annotations (see PEP 484) for the lxml package. Installation To use these stubs with mypy, you

25 Dec 26, 2022
mypy plugin to type check Kubernetes resources

kubernetes-typed mypy plugin to dynamically define types for Kubernetes objects. Features Type checking for Custom Resources Type checking forkubernet

Artem Yarmoliuk 16 Oct 10, 2022
Tools for improving Python imports

imptools Tools for improving Python imports. Installation pip3 install imptools Overview Detailed docs import_path Import a module from any path on th

Danijar Hafner 7 Aug 07, 2022
Static Typing for Python

Python static typing home. Contains the source for typing_extensions and the documentation. Also hosts a user help forum.

Python 1.3k Jan 06, 2023
❄️ A flake8 plugin to help you write better list/set/dict comprehensions.

flake8-comprehensions A flake8 plugin that helps you write better list/set/dict comprehensions. Requirements Python 3.6 to 3.9 supported. Installation

Adam Johnson 398 Dec 23, 2022
The strictest and most opinionated python linter ever!

wemake-python-styleguide Welcome to the strictest and most opinionated python linter ever. wemake-python-styleguide is actually a flake8 plugin with s

wemake.services 2.1k Jan 01, 2023
Code audit tool for python.

Pylama Code audit tool for Python and JavaScript. Pylama wraps these tools: pycodestyle (formerly pep8) © 2012-2013, Florent Xicluna; pydocstyle (form

Kirill Klenov 967 Jan 07, 2023