Better mypy typing for enum values in python
Hi - I'm the maintainer of https://github.com/dropbox/mypy-protobuf - a protoc plugin for autogenerating mypy stubs compatible with the built in python generator.
What language does this apply to? Python
Describe the problem you are trying to solve.
Generated enum values are pure ints (per the spec). We prefer type them with a NewType wrapper type around int - specific to the enum. See the typeshed stub
https://github.com/python/typeshed/blob/master/third_party/2and3/google/protobuf/internal/enum_type_wrapper.pyi#L9
class _EnumTypeWrapper(Generic[_V]):
DESCRIPTOR: EnumDescriptor
def __init__(self, enum_type: EnumDescriptor) -> None: ...
def Name(self, number: _V) -> str: ...
def Value(self, name: str) -> _V: ...
def keys(self) -> List[str]: ...
def values(self) -> List[_V]: ...
def items(self) -> List[Tuple[str, _V]]: ...
I've been cooking up a strategy inside mypy-protobuf where a proto
enum MyEnum {
FOO = 0;
BAR = 1;
}
Autogenerates pyi stubs
class _MyEnum(google.protobuf.internal.enum_type_wrapper.EnumTypeWrapper[OuterEnum.V], builtins.type):
DESCRIPTOR: google.protobuf.descriptor.EnumDescriptor = ...
FOO = OuterEnum.V(0)
BAR = OuterEnum.V(1)
class MyEnum(metaclass=_MyEnum):
V = typing.NewType('V', builtins.int)
This allows callsites to type their code as
x: MyEnum.V = MyEnum.Value("FOO")
Unfortunately - because .V does not exist at runtime (only in the pyi stubs) - this does not work.
Fortunately, you can work around this with:
x: "MyEnum.V" = MyEnum.Value("FOO")
Describe the solution you'd like
I'd like to propose adding V = int runtime type alias to the EnumTypeWrapper (in enum_type_wrapper.py) - to avoid the need for this workaround.
class EnumTypeWrapper(object):
"""A utility for finding the names of enum values."""
# This is a type alias, which mypy typing stubs can type as
# a genericized parameter constrained to an int, allowing subclasses
# to be typed with more constraint
# Eg.
# def Name(self, number: MyGeneratedEnum.V) -> str
V = int
... [rest of impl omitted]
This would mean that enum variants named "V" would need to jump through a hoop using getattr to be accessed, but this is already the case with "Name", "Value", "keys", etc - so it seems feasible as an extension. I'm open to other naming ideas for this.
Could do something like this for more clarity - though it does add a dependency on typing module for python <= 3.5
from typing import NewType
V = NewType('V', int)
I would also be open to discussing other strategies we could employ across mypy-protobuf, protoc, and typeshed in order to get better mypy typing for enum values (better than just typing as an int) - other than this V inner type alias.
Describe alternatives you've considered
I've also tried mypy typing V at a sibling scope to MyEnum (eg MyEnumValue = NewType('MyEnumValue', int), but this is no improvement - as you still need to play tricks to import it from real code.
Thanks friends! Happy to open discussion.
Another idea we've tried - would be to make MyEnum an instance of int. Then we would be typing the enumtypewrapper instance as MyEnum as well as the int values as MyEnum.
This seems a bit of a departure from reality of the generated code - as those are actually two separate types (instance of EnumTypeWrapper vs instance of int), but it can be made workable. The typing would allow folks to accidentally try and call enumtypewrapper methods on the ints themselves, but it would cut down on this "extra" type.
I'd softly lean toward the V solution as it makes clear in the typing that the EnumTypeWrapper and the int values are distinct objects of distinct types.
Hi! Any updated thoughts on #8182. I'm planning on going forward with the V solution in mypy-protobuf - and it would be ergonomic for calling code to have #8182 to write code like this!
def f(x: MyEnum.V):
print(x)
f(MyEnum.Value("FOO"))
rather than like this
def f(x: 'MyEnum.V'):
print(x)
f(MyEnum.Value("FOO"))
I realize - that with python 3.10 (or w/ from __future__ import annotations) - python will no longer try to execute the type annotations, meaning that this sort of change may no longer be necessary.
Actually realized - even with from __future__ import annotations - it is still helpful to be able to inline code that casts to the type wrapper. Eg
x = MyEnum.V(5)
Hi @anandolee - wanted to check in on this task and #8182
Hey @anandolee and/or @acozzette - wanted to check in here to see if there are next steps I can help with. Happy to put in a bit of work here (either technically / documentation / derisking) if that would be helpful - just point me to what would be useful here.
If there's some high level concern, lmk as that might be helpful - either for coming up with a different strategy, or to communicate to folks being bothered by the status quo.
@nipunn1313, I stumbled across this issue trying to understand why MyEnum.FOO didn't typecheck. I'm reviewing your suggestion and trying to understand how you settled on using V? Was it not possible to define a static class that had the enum attributes?
Hi @jaywhy13. protobuf generates an EnumTypeWrapper (static class) with helper methods, and a raw int for the value type.
Rather than typing as a raw int, mypy-protobuf wanted stronger typing - specific to the enum itself - a pyi file like this:
class MyEnum(EnumTypeWrapper):
V = NewType('V', int)
FOO: int
I suppose you're wondering why we didn't generate typing stubs more like
class MyEnum(EnumTypeWrapper):
class V(IntEnum):
FOO: int
This could work as well, but still ends up requiring a V. May end up being somewhat misleading as the actual generated protobuf code uses an int and not an IntEnum. NewType around int is truer to the generated protobuf code.
In either case, the base code in protobuf itself would still need something like V = int
In selecting V - chose it to be short for Value - but also easy to type (just one letter). Most places in the code would show something like MyEnum.V and be clear.
For clarity - I worked on mypy-protobuf and not on protobuf itself, so I don't currently have the flexibility to make changes to both. I'm proposing a minimal change to protobuf to the core protobuf team in #8182 - so that mypy-protobuf can work better.
Pinging some folks who might more actively monitor Github activity: @deannagarcia @TeBoring Really would be quite nice to get this one-line change through https://github.com/protocolbuffers/protobuf/pull/8182
Let me state my summary of this issue, both to check my understanding and to help others who may not be familiar with the Python type-checking ecosystem. Please let me know if I got anything wrong here.
Mypy is a static type checking tool for Python. It reads type annotations from the Python source code and spits out errors for any type violations it detects. This type checking is performed without running the code.
A simple example:
# The type annotation here is valid Python 3 syntax, but is ignored
# by the interpreter.
def greeting(name: str) -> str:
return 'Hello ' + name
# If you run Mypy on this file, it throws an error:
# Argument 1 to "greeting" has incompatible type "int"; expected "str"
greeting(3)
Mypy is also capable of reading annotations from separate "stub files" with .pyi extensions. This gives Mypy type information about modules that are implemented in C, or that don't have type annotations. This is similar to the .d.ts "Declarations Files" in TypeScript:
# test.py
def greeting(name):
return 'Hello ' + name
# test.pyi
def greeting(name: str) -> str: ...
Since protobuf generated code does not currently contain any annotations, a separate project https://github.com/dropbox/mypy-protobuf has implemented its own code generator for protobuf that generates .pyi files for each generated module.
This works fine for the generated interfaces themselves. However users writing their own functions have no easy way of accepting strongly-typed protobuf enums:
# In protobuf generated interfaces, enums are ints. We have no way of writing
# a function that only accepts enum values from MyEnum:
def f(enum_val: int):
print(enum_val)
To address this, protobuf-mypy has created a distinct type that is the same as int at runtime, but is treated differently by the static typing framework:
# Doesn't work pre-PEP 563
def f(x: MyEnum.V):
print(x)
However this doesn't work until Python 3.10, or with an explicit import of from __future__ import annotations, because it needs PEP 563 to accept this code when MyEnum.V is not actually defined by protobuf generated code.
Another edge case is cast(), which doesn't work even with PEP 563:
# Doesn't work even with PEP 563
cast(MyEnum.V, x)
To solve this problem, and make the code compatible with pre-PEP 563 code (and to make cast() work), the proposal is for the actual generated code to include a V or ValueType alias.
Does that all sound correct?
If that's right, my initial thoughts are:
- A
ValueTypealias tointseems reasonable to enable this use case. - We should evaluate our overall plans for static typing in Python, and make sure this overall approach is a good long-term strategy for us.
@haberman This is a great write-up! I hope the team will consider providing types inline with the generated runtime code as part of their long term plans (#2638)! This will improve code editing experience by making jump-to-definition using tools like the type-aware VSCode Python extension navigate to the actual runtime definition rather than just the stub file.
Does that all sound correct?
If that's right, my initial thoughts are:
- A ValueType alias to int seems reasonable to enable this use case.
- We should evaluate our overall plans for static typing in Python, and make sure this overall approach is a good long-term strategy for us.
Yep. Fantastic summary. Thanks. I would note one nit
- adding type annotations is now a python3 language feature
- mypy is one of several typecheckers for python using the type annotations (the original one inspiring the language feature). https://github.com/microsoft/pyright is another popular one.
For overall plans - there is some discussion in #2638 - which mostly points people to using mypy-protobuf. Would love a future where either
- Protobuf itself was able to produce the
.pyifiles. - Protobuf Inlined annotations into the generated
_pb2.py. May be tricky due to the non-explicitness of class types, but it's another option
MyMessage = _reflection.GeneratedProtocolMessageType('MyMessage', (_message.Message,), {
...
I would personally be happy to have mypy-protobuf integrated into protobuf as a way to implement option 1 if you want to go that route. (adding --mypy_out to command line). I suspect a prototype of this might be as easy as adding mypy-protobuf to install_requires https://github.com/protocolbuffers/protobuf/blob/master/python/setup.py#L274.
- Protobuf itself was able to produce the .pyi files.
Yes, I'm leaning in this direction, rather than embedding type annotations directly into the generated code.
The reason for this is load-time efficiency. When the schema is large (many .proto files, many messages, enums, etc) the time spent parsing and executing the generated code becomes significant. We need to make the generated modules as small and optimized as possible. (We're actually starting on some work right now to shrink the generated code to improve the load time efficiency.)
However, the .pyi files would have no such constraint. We could make them as readable and annotated as possible.
My vision is that we drop all pretense of readability for _pb2.py, and make them nothing but a serialized descriptor and a builder function:
# foo_pb2.py
from google.protobuf.internal import module_builder
# Embedded in the code as a b'' string or loaded from a
# separate file with pkgutil.get_data().
_serialized_descriptor = "<...>"
module_builder.build(_serialized_descriptor, globals())
I like the idea of compensating for the relative loss of readability here with .pyi files which document the full interface in a readable way.
We'd need to talk this over as a team and get consensus on it, but I like this direction.
I would personally be happy to have mypy-protobuf integrated into protobuf as a way to implement option 1 if you want to go that route.
Thanks for this. :) We'd probably need to make sure this would all work out CLA-wise, and review the design etc, but it's good to know this option is available.
One other thing on the Enum issue specifically. Because protobuf schemas can diverge between sender and receiver, enum values can appear that diverge from your enum definition.
In proto3, enum fields are truly open: they can contain any int32 value. So there needs to be a way of representing a proto enum value as a bare integer, even if it is outside the domain of what was defined in the .proto file.
For example, protobuf enum fields (at least in proto3) will accept bare integers that do not correspond to any enumerator in the .proto file:
// test.proto
syntax = "proto3";
enum E {
UNSPECIFIED = 0;
ONE = 1;
TWO = 2;
}
message M {
E e = 1;
}
# test.py
import test_pb2
m = test_pb2.m()
# Setter can accept a bare int outside the domain:
m.e = 12345
# Getter can return a bare int outside the domain:
x = m.e
Can the enum typing solution in protobuf-mypy accomodate this?
proto2 enums are closed (unexpected enums at parse time are put into the unknown field set instead of the field), so a typing solution that excludes bare integers would be more appropriate there.
mypy-protobuf currently accomodates this by typing enum values as MyEnum.V where V = NewType('V', int) - a stricter open int. Accepts any integer value, but would need to be written as m.e = MyEnum.V(12345) for mypy to be happy. At runtime, MyEnum.V is simply int. Methods like Name and Value use V as the type for the argument / return value.
Here's an example of generated code: https://github.com/dropbox/mypy-protobuf/blob/main/test/generated/testproto/test_pb2.pyi#L28
Here are the typeshed stubs for enum_type_wrapper.py (non-generated)
https://github.com/python/typeshed/blob/master/stubs/protobuf/google/protobuf/internal/enum_type_wrapper.pyi
If you'd like to bring the types for the non-generated types from typeshed into protobuf itself - PEP 561 provides a way with py.typed
Let me know how I can help. If you'd like me to be involved in the discussion with the team, I'm happy to help (shoot me an email or lmk here). I've worked on mypy-protobuf for over 4 years, including from the times before we open sourced it at Dropbox. It brought us a lot of value over the years. Would be happy to continue maintaining it under the umbrella of protocolbuffers and help make typed generated code more standard in whatever way makes sense.
Accepts any integer value, but would need to be written as
m.e = MyEnum.V(12345)for mypy to be happy.
That seems like a really nice compromise.
If you'd like to bring the types for the non-generated types from typeshed into protobuf itself - PEP 561 provides a way with py.typed
Can you spell out in slightly more detail what this would mean?
I've worked on mypy-protobuf for over 4 years, including from the times before we open sourced it at Dropbox. It brought us a lot of value over the years.
Wow, that is a lot of background and experience! Thanks very kindly for the offer. Let me touch base with some people early next week and get back to you on this.
If you'd like to bring the types for the non-generated types from typeshed into protobuf itself - PEP 561 provides a way with py.typed
Can you spell out in slightly more detail what this would mean?
I think pyright's docs explain this quite well . My tl;dr is that type annotations for third party python libraries (like protobuf eg) can be done in a few ways)
- Inline annotations + a blank
py.typedfile to let typecheckers like mypy know that the inline annotations are correct and complete. Either in the same files, or alongside in.pyistubs. - Create your own separate annotation package (eg
pip install protobuf-stubs) - typeshed - which used to ship with mypy, but recently started autogenerating annotation packages like types-protobuf).
3 was the original way, especially important in the early days of mypy development, but now that it's more mature, they're encouraging use of 1/2 - so the type annotations are owned by the package developers. PEP 561 is the specification introducing option 1/2. Currently, protobuf uses option 3 - with most of those stubs being contributed to typeshed by the community (much by Dropbox engineers originally).