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
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
flake8 plugin to catch useless `assert` statements

flake8-useless-assert flake8 plugin to catch useless assert statements Download or install on the PyPI page Violations Code Description Example ULA001

1 Feb 12, 2022
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
Typed interface stubs for Pythonista iOS

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

Harold Martin 12 Jul 14, 2020
Check for python builtins being used as variables or parameters

Flake8 Builtins plugin Check for python builtins being used as variables or parameters. Imagine some code like this: def max_values(list, list2):

Gil Forcada Codinachs 98 Jan 08, 2023
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
open source tools to generate mypy stubs from protobufs

mypy-protobuf: Generate mypy stub files from protobuf specs We just released a new major release mypy-protobuf 2. on 02/02/2021! It includes some back

Dropbox 527 Jan 03, 2023
Easy saving and switching between multiple KDE configurations.

Konfsave Konfsave is a config manager. That is, it allows you to save, back up, and easily switch between different (per-user) system configurations.

42 Sep 25, 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
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
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
Convert relative imports to absolute

absolufy-imports A tool and pre-commit hook to automatically convert relative imports to absolute. Installation $ pip install absolufy-imports Usage a

Marco Gorelli 130 Dec 30, 2022
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
A framework for detecting, highlighting and correcting grammatical errors on natural language text.

Gramformer Human and machine generated text often suffer from grammatical and/or typographical errors. It can be spelling, punctuation, grammatical or

Prithivida 1.3k Jan 08, 2023
Mylint - My really simple rendition of how a linter works.

mylint My really simple rendition of how a linter works. This original version was written for my AST article. Since then I've added tests and turned

Tushar Sadhwani 2 Dec 29, 2021
Flake8 plugin to validate annotations complexity

flake8-annotations-complexity An extension for flake8 to report on too complex type annotations. Complex type annotations often means bad annotations

BestDoctor 41 Dec 28, 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
Tool to automatically fix some issues reported by flake8 (forked from autoflake).

autoflake8 Introduction autoflake8 removes unused imports and unused variables from Python code. It makes use of pyflakes to do this. autoflake8 also

francisco souza 27 Sep 08, 2022
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 that checks import order against various Python Style Guides

flake8-import-order A flake8 and Pylama plugin that checks the ordering of your imports. It does not check anything else about the imports. Merely tha

Python Code Quality Authority 270 Nov 24, 2022