Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use type hinting with dictionaries and google protobuf enum?

I am trying to use protobuf enum as a type for values in a dictionary but it does not work for some reason.

My enum definition in proto is:

enum Device {
  UNSPECIFIED = 0;
  ON = 1;
  OFF = 2;
}

After successful compilation and importing, the following code results in error.

from devices_pb2 import Device

def foo(device: Device) -> Dict[str, Device]:
    pass

Error message:

    def foo(device: Device) -> Dict[str, Device]:
  File "/home/ivan/anaconda3/envs/py37/lib/python3.7/typing.py", line 254, in inner
    return func(*args, **kwds)
  File "/home/ivan/anaconda3/envs/py37/lib/python3.7/typing.py", line 629, in __getitem__
    params = tuple(_type_check(p, msg) for p in params)
  File "/home/ivan/anaconda3/envs/py37/lib/python3.7/typing.py", line 629, in <genexpr>
    params = tuple(_type_check(p, msg) for p in params)
  File "/home/ivan/anaconda3/envs/py37/lib/python3.7/typing.py", line 142, in _type_check
    raise TypeError(f"{msg} Got {arg!r:.100}.")
TypeError: Parameters to generic types must be types. Got <google.protobuf.internal.enum_type_wrapper.EnumTypeWrapper object at 0x7f4df6d81850>.

However, if I do not use dictionary then it works just fine:

def foo(device: Device) -> Device:
    pass

I wonder if there is a solution to this problem?

like image 675
Ivan Avatar asked Feb 21 '20 16:02

Ivan


Video Answer


1 Answers

Adding the following solved the problem:

from __future__ import annotations

For more details, please check here.

like image 185
Ivan Avatar answered Sep 27 '22 22:09

Ivan