protobuf
protobuf copied to clipboard
Add class-scope "FromNanoseconds", "FromMicroseconds", "FromMilliseconds", "FromSeconds", "FromDatetime", and "FromJsonString" methods
To what language does this apply? Python
Describe the problem you are trying to solve.
Construct a google.protobuf.timestamp_pb2.Timestamp
from a numeric value of milliseconds in the most-attractive, with-the-best-developer-experience possible.
Describe the solution you'd like
my_timestamp_message = timestamp_pb2.Timestamp.FromMilliseconds(my_numeric_value)
Describe alternatives you've considered
my_timestamp_message = timestamp_pb2.timestamp_from_milliseconds(my_numeric_value)
would probably be okay.
Protocol Buffers Python currently only supports
my_timestamp_message = timestamp_pb2.Timestamp()
my_timestamp_message.FromMilliseconds(my_numeric_value)
. That there is not a single-expression way to construct a populated-from-numerical-value-of-milliseconds timestamp_pb2.Timestamp
message means that lots of opportunities for attractive code are being missed (and additional temporary variables and helper methods written...).
Additional context
Since FromMilliseconds
is currently an instance-scope method, adding a class-scope method of the same name might require some nicely-encapsulated-and-not-marring-the-public-API hackery like
class Example(object):
def __init__(self):
self.FromMilliseconds = self.InstanceScopeFromMilliseconds
def InstanceScopeFromMilliseconds(self, milliseconds):
# (some implementation)
@classmethod
def FromMilliseconds(cls, milliseconds):
# (some implementation that returns an instance of the class)
Obviously there's nothing special about FromMilliseconds
; this enhancement should also be done for FromNanoseconds
, FromMicroseconds
, FromSeconds
, FromDatetime
, and FromJsonString
.
Issue 3986 is something like this in that it asks for something that allows timestamp_pb2.Timestamp
instantiation on one line, but I don't agree with the one concrete suggestion that it offers (returning self
from instance-scope FromMilliseconds
; yuck!).