Plugin for mypy to support zope interfaces
Maintained. Last release 8 weeks ago, commits in 2 of the last 26 weeks. Weaker on commit activity and contributor spread.
pip install mypy-zopePlugin for mypy to support zope.interface
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 attributes is
getting the type in the example above. That means mypy will report an
error if you try to assign string to that attribute on an instance of
type. Custom fields or fields not recognized by plugin are given type .