Skip to content

Instantly share code, notes, and snippets.

@gjo
Last active March 7, 2019 06:50
Show Gist options
  • Save gjo/6e29d15e637e372b2b92f8e972377eb1 to your computer and use it in GitHub Desktop.
Save gjo/6e29d15e637e372b2b92f8e972377eb1 to your computer and use it in GitHub Desktop.
testing annotated attributes (tests/samples/annotated_attribute.py) with mypy_zope 0.1.3
"""zope.interface provides an attribute with a type annotation for classes
(requres: python 3.6)
"""
import typing
import zope.interface
class IFoo(zope.interface.Interface):
f_str: typing.Text = zope.interface.Attribute('String Attr')
f_str_opt: typing.Optional[typing.Text] = zope.interface.Attribute('Optional String Attr')
f_int: int = zope.interface.Attribute('Integer Attr')
f_bar: "IBar" = zope.interface.Attribute('Interface Attr')
class IBar(zope.interface.Interface):
field = zope.interface.Attribute('Unannotated Attr')
@zope.interface.implementer(IFoo)
class Foo(object):
pass
@zope.interface.implementer(IBar)
class Bar(object):
pass
def main() -> None:
foo = Foo()
bar = Bar()
# We can assign anything to abstract attributes
foo.f_str = "Sample"
foo.f_str = 10
foo.f_str_opt = "Sample"
foo.f_str_opt = None
foo.f_int = 10
foo.f_int = None
foo.f_bar = bar
if __name__ == '__main__':
main()
"""
<output>
interface_attribute_annotated.py:35: error: Incompatible types in assignment (expression has type "int", variable has type "str")
interface_attribute_annotated.py:39: error: Incompatible types in assignment (expression has type "None", variable has type "int")
</output>
"""
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment