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
Enforce the same configuration across multiple projects

Nitpick Flake8 plugin to enforce the same tool configuration (flake8, isort, mypy, Pylint...) across multiple Python projects. Useful if you maintain

Augusto W. Andreoli 315 Dec 25, 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
Flake8 extension for enforcing trailing commas in python

Flake8 Extension to enforce better comma placement. Usage If you are using flake8 it's as easy as: pip install flake8-commas Now you can avoid those a

Python Code Quality Authority 127 Sep 03, 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
Static type checker for Python

Static type checker for Python Speed Pyright is a fast type checker meant for large Python source bases. It can run in a “watch” mode and performs fas

Microsoft 9.2k Jan 03, 2023
Utilities for refactoring imports in python-like syntax.

aspy.refactor_imports Utilities for refactoring imports in python-like syntax. Installation pip install aspy.refactor_imports Examples aspy.refactor_i

Anthony Sottile 20 Nov 01, 2022
Mypy plugin and stubs for SQLAlchemy

Pythonista Stubs Stubs for the Pythonista iOS API. This allows for better error detection and IDE / editor autocomplete. Installation and Usage pip in

Dropbox 521 Dec 29, 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
Backport Python 3.8+ typing utils & add issubtype & more

typing-utils Backport Python3.8+ typing utils & issubtype & more Install API issubtype get_origin get_args get_type_hints Install pip install typi

10 Nov 09, 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
Pyright extension for coc.nvim

coc-pyright Pyright extension for coc.nvim Install :CocInstall coc-pyright Note: Pyright may not work as expected if can't detect project root correct

Heyward Fann 1.1k Jan 02, 2023
Mypy stubs for the PyQt5 framework

Mypy stubs for the PyQt5 framework This repository holds the stubs of the PyQt5 framework. It uses the stub files that are produced during compilation

62 Nov 22, 2022
Flake8 plugin to find commented out or dead code

flake8-eradicate flake8 plugin to find commented out (or so called "dead") code. This is quite important for the project in a long run. Based on eradi

wemake.services 277 Dec 27, 2022
Flake8 extension for checking quotes in python

Flake8 Extension to lint for quotes. Major update in 2.0.0 We automatically encourage avoiding escaping quotes as per PEP 8. To disable this, use --no

Zachary Heller 157 Dec 13, 2022
Custom Python linting through AST expressions

bellybutton bellybutton is a customizable, easy-to-configure linting engine for Python. What is this good for? Tools like pylint and flake8 provide, o

H. Chase Stevens 249 Dec 31, 2022
It's not just a linter that annoys you!

README for Pylint - https://pylint.pycqa.org/ Professional support for pylint is available as part of the Tidelift Subscription. Tidelift gives softwa

Python Code Quality Authority 4.4k Jan 04, 2023
OpenStack Hacking Style Checks. Mirror of code maintained at opendev.org.

Introduction hacking is a set of flake8 plugins that test and enforce the OpenStack StyleGuide Hacking pins its dependencies, as a new release of some

Mirrors of opendev.org/openstack 224 Jan 05, 2023
Flake8 Type Annotation Checking

flake8-annotations flake8-annotations is a plugin for Flake8 that detects the absence of PEP 3107-style function annotations and PEP 484-style type co

S. Co1 118 Jan 05, 2023
An enhanced version of the Python typing library.

typingplus An enhanced version of the Python typing library that always uses the latest version of typing available, regardless of which version of Py

Contains 6 Mar 26, 2021
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