Skip to main content

Plugin for mypy to support zope interfaces

Project description

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

Ready to use!

Currently, the project is used in production in various substantially large projects and considered production-grade, however there still might be subtle bugs around. Suggestions and pull requests are welcomed!

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

mypy_zope-1.0.9.tar.gz (34.0 kB view details)

Uploaded Source

Built Distribution

mypy_zope-1.0.9-py3-none-any.whl (32.4 kB view details)

Uploaded Python 3

File details

Details for the file mypy_zope-1.0.9.tar.gz.

File metadata

  • Download URL: mypy_zope-1.0.9.tar.gz
  • Upload date:
  • Size: 34.0 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/5.1.1 CPython/3.12.3

File hashes

Hashes for mypy_zope-1.0.9.tar.gz
Algorithm Hash digest
SHA256 37d6985dfb05a4c27b35cff47577fd5bad878db4893ddedf54d165f7389a1cdb
MD5 83bd94d71f573720305ce743bd5d1842
BLAKE2b-256 3df6e93becf00e2cd9e263d813ab05ad422318a9d093fd4c6678febce4387ce4

See more details on using hashes here.

File details

Details for the file mypy_zope-1.0.9-py3-none-any.whl.

File metadata

  • Download URL: mypy_zope-1.0.9-py3-none-any.whl
  • Upload date:
  • Size: 32.4 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/5.1.1 CPython/3.12.3

File hashes

Hashes for mypy_zope-1.0.9-py3-none-any.whl
Algorithm Hash digest
SHA256 6666c1556891a3cb186137519dbd7a58cb30fb72b2504798cad47b35391921ba
MD5 902bd83be3d9e5b6fc245d4f7c0cd759
BLAKE2b-256 6adbee6e5840d85904c7525afee6d7eaa9cd24bb177ea82d1ad705e19468151a

See more details on using hashes here.

Supported by

AWS AWS Cloud computing and Security Sponsor Datadog Datadog Monitoring Fastly Fastly CDN Google Google Download Analytics Microsoft Microsoft PSF Sponsor Pingdom Pingdom Monitoring Sentry Sentry Error logging StatusPage StatusPage Status page