ortools.sat.cp_model_pb2

Generated protocol buffer code.

 1# -*- coding: utf-8 -*-
 2# Generated by the protocol buffer compiler.  DO NOT EDIT!
 3# NO CHECKED-IN PROTOBUF GENCODE
 4# source: ortools/sat/cp_model.proto
 5# Protobuf Python Version: 5.29.3
 6"""Generated protocol buffer code."""
 7from google.protobuf import descriptor as _descriptor
 8from google.protobuf import descriptor_pool as _descriptor_pool
 9from google.protobuf import runtime_version as _runtime_version
10from google.protobuf import symbol_database as _symbol_database
11from google.protobuf.internal import builder as _builder
12_runtime_version.ValidateProtobufRuntimeVersion(
13    _runtime_version.Domain.PUBLIC,
14    5,
15    29,
16    3,
17    '',
18    'ortools/sat/cp_model.proto'
19)
20# @@protoc_insertion_point(imports)
21
22_sym_db = _symbol_database.Default()
23
24
25
26
27DESCRIPTOR = _descriptor_pool.Default().AddSerializedFile(b'\n\x1aortools/sat/cp_model.proto\x12\x17operations_research.sat\"4\n\x14IntegerVariableProto\x12\x0c\n\x04name\x18\x01 \x01(\t\x12\x0e\n\x06\x64omain\x18\x02 \x03(\x03\"%\n\x11\x42oolArgumentProto\x12\x10\n\x08literals\x18\x01 \x03(\x05\"E\n\x15LinearExpressionProto\x12\x0c\n\x04vars\x18\x01 \x03(\x05\x12\x0e\n\x06\x63oeffs\x18\x02 \x03(\x03\x12\x0e\n\x06offset\x18\x03 \x01(\x03\"\x94\x01\n\x13LinearArgumentProto\x12>\n\x06target\x18\x01 \x01(\x0b\x32..operations_research.sat.LinearExpressionProto\x12=\n\x05\x65xprs\x18\x02 \x03(\x0b\x32..operations_research.sat.LinearExpressionProto\"\\\n\x1b\x41llDifferentConstraintProto\x12=\n\x05\x65xprs\x18\x01 \x03(\x0b\x32..operations_research.sat.LinearExpressionProto\"E\n\x15LinearConstraintProto\x12\x0c\n\x04vars\x18\x01 \x03(\x05\x12\x0e\n\x06\x63oeffs\x18\x02 \x03(\x03\x12\x0e\n\x06\x64omain\x18\x03 \x03(\x03\"\x91\x02\n\x16\x45lementConstraintProto\x12\r\n\x05index\x18\x01 \x01(\x05\x12\x0e\n\x06target\x18\x02 \x01(\x05\x12\x0c\n\x04vars\x18\x03 \x03(\x05\x12\x44\n\x0clinear_index\x18\x04 \x01(\x0b\x32..operations_research.sat.LinearExpressionProto\x12\x45\n\rlinear_target\x18\x05 \x01(\x0b\x32..operations_research.sat.LinearExpressionProto\x12=\n\x05\x65xprs\x18\x06 \x03(\x0b\x32..operations_research.sat.LinearExpressionProto\"\xd3\x01\n\x17IntervalConstraintProto\x12=\n\x05start\x18\x04 \x01(\x0b\x32..operations_research.sat.LinearExpressionProto\x12;\n\x03\x65nd\x18\x05 \x01(\x0b\x32..operations_research.sat.LinearExpressionProto\x12<\n\x04size\x18\x06 \x01(\x0b\x32..operations_research.sat.LinearExpressionProto\"-\n\x18NoOverlapConstraintProto\x12\x11\n\tintervals\x18\x01 \x03(\x05\"F\n\x1aNoOverlap2DConstraintProto\x12\x13\n\x0bx_intervals\x18\x01 \x03(\x05\x12\x13\n\x0by_intervals\x18\x02 \x03(\x05\"\xb1\x01\n\x19\x43umulativeConstraintProto\x12@\n\x08\x63\x61pacity\x18\x01 \x01(\x0b\x32..operations_research.sat.LinearExpressionProto\x12\x11\n\tintervals\x18\x02 \x03(\x05\x12?\n\x07\x64\x65mands\x18\x03 \x03(\x0b\x32..operations_research.sat.LinearExpressionProto\"\xea\x01\n\x18ReservoirConstraintProto\x12\x11\n\tmin_level\x18\x01 \x01(\x03\x12\x11\n\tmax_level\x18\x02 \x01(\x03\x12\x42\n\ntime_exprs\x18\x03 \x03(\x0b\x32..operations_research.sat.LinearExpressionProto\x12\x45\n\rlevel_changes\x18\x06 \x03(\x0b\x32..operations_research.sat.LinearExpressionProto\x12\x17\n\x0f\x61\x63tive_literals\x18\x05 \x03(\x05J\x04\x08\x04\x10\x05\"H\n\x16\x43ircuitConstraintProto\x12\r\n\x05tails\x18\x03 \x03(\x05\x12\r\n\x05heads\x18\x04 \x03(\x05\x12\x10\n\x08literals\x18\x05 \x03(\x05\"j\n\x15RoutesConstraintProto\x12\r\n\x05tails\x18\x01 \x03(\x05\x12\r\n\x05heads\x18\x02 \x03(\x05\x12\x10\n\x08literals\x18\x03 \x03(\x05\x12\x0f\n\x07\x64\x65mands\x18\x04 \x03(\x05\x12\x10\n\x08\x63\x61pacity\x18\x05 \x01(\x03\"\x84\x01\n\x14TableConstraintProto\x12\x0c\n\x04vars\x18\x01 \x03(\x05\x12\x0e\n\x06values\x18\x02 \x03(\x03\x12=\n\x05\x65xprs\x18\x04 \x03(\x0b\x32..operations_research.sat.LinearExpressionProto\x12\x0f\n\x07negated\x18\x03 \x01(\x08\"=\n\x16InverseConstraintProto\x12\x10\n\x08\x66_direct\x18\x01 \x03(\x05\x12\x11\n\tf_inverse\x18\x02 \x03(\x05\"\xe1\x01\n\x18\x41utomatonConstraintProto\x12\x16\n\x0estarting_state\x18\x02 \x01(\x03\x12\x14\n\x0c\x66inal_states\x18\x03 \x03(\x03\x12\x17\n\x0ftransition_tail\x18\x04 \x03(\x03\x12\x17\n\x0ftransition_head\x18\x05 \x03(\x03\x12\x18\n\x10transition_label\x18\x06 \x03(\x03\x12\x0c\n\x04vars\x18\x07 \x03(\x05\x12=\n\x05\x65xprs\x18\x08 \x03(\x0b\x32..operations_research.sat.LinearExpressionProto\"$\n\x14ListOfVariablesProto\x12\x0c\n\x04vars\x18\x01 \x03(\x05\"\xf0\x0c\n\x0f\x43onstraintProto\x12\x0c\n\x04name\x18\x01 \x01(\t\x12\x1b\n\x13\x65nforcement_literal\x18\x02 \x03(\x05\x12=\n\x07\x62ool_or\x18\x03 \x01(\x0b\x32*.operations_research.sat.BoolArgumentProtoH\x00\x12>\n\x08\x62ool_and\x18\x04 \x01(\x0b\x32*.operations_research.sat.BoolArgumentProtoH\x00\x12\x41\n\x0b\x61t_most_one\x18\x1a \x01(\x0b\x32*.operations_research.sat.BoolArgumentProtoH\x00\x12\x41\n\x0b\x65xactly_one\x18\x1d \x01(\x0b\x32*.operations_research.sat.BoolArgumentProtoH\x00\x12>\n\x08\x62ool_xor\x18\x05 \x01(\x0b\x32*.operations_research.sat.BoolArgumentProtoH\x00\x12?\n\x07int_div\x18\x07 \x01(\x0b\x32,.operations_research.sat.LinearArgumentProtoH\x00\x12?\n\x07int_mod\x18\x08 \x01(\x0b\x32,.operations_research.sat.LinearArgumentProtoH\x00\x12@\n\x08int_prod\x18\x0b \x01(\x0b\x32,.operations_research.sat.LinearArgumentProtoH\x00\x12?\n\x07lin_max\x18\x1b \x01(\x0b\x32,.operations_research.sat.LinearArgumentProtoH\x00\x12@\n\x06linear\x18\x0c \x01(\x0b\x32..operations_research.sat.LinearConstraintProtoH\x00\x12H\n\x08\x61ll_diff\x18\r \x01(\x0b\x32\x34.operations_research.sat.AllDifferentConstraintProtoH\x00\x12\x42\n\x07\x65lement\x18\x0e \x01(\x0b\x32/.operations_research.sat.ElementConstraintProtoH\x00\x12\x42\n\x07\x63ircuit\x18\x0f \x01(\x0b\x32/.operations_research.sat.CircuitConstraintProtoH\x00\x12@\n\x06routes\x18\x17 \x01(\x0b\x32..operations_research.sat.RoutesConstraintProtoH\x00\x12>\n\x05table\x18\x10 \x01(\x0b\x32-.operations_research.sat.TableConstraintProtoH\x00\x12\x46\n\tautomaton\x18\x11 \x01(\x0b\x32\x31.operations_research.sat.AutomatonConstraintProtoH\x00\x12\x42\n\x07inverse\x18\x12 \x01(\x0b\x32/.operations_research.sat.InverseConstraintProtoH\x00\x12\x46\n\treservoir\x18\x18 \x01(\x0b\x32\x31.operations_research.sat.ReservoirConstraintProtoH\x00\x12\x44\n\x08interval\x18\x13 \x01(\x0b\x32\x30.operations_research.sat.IntervalConstraintProtoH\x00\x12G\n\nno_overlap\x18\x14 \x01(\x0b\x32\x31.operations_research.sat.NoOverlapConstraintProtoH\x00\x12L\n\rno_overlap_2d\x18\x15 \x01(\x0b\x32\x33.operations_research.sat.NoOverlap2DConstraintProtoH\x00\x12H\n\ncumulative\x18\x16 \x01(\x0b\x32\x32.operations_research.sat.CumulativeConstraintProtoH\x00\x12I\n\x10\x64ummy_constraint\x18\x1e \x01(\x0b\x32-.operations_research.sat.ListOfVariablesProtoH\x00\x42\x0c\n\nconstraint\"\xe0\x01\n\x10\x43pObjectiveProto\x12\x0c\n\x04vars\x18\x01 \x03(\x05\x12\x0e\n\x06\x63oeffs\x18\x04 \x03(\x03\x12\x0e\n\x06offset\x18\x02 \x01(\x01\x12\x16\n\x0escaling_factor\x18\x03 \x01(\x01\x12\x0e\n\x06\x64omain\x18\x05 \x03(\x03\x12\x19\n\x11scaling_was_exact\x18\x06 \x01(\x08\x12\x1d\n\x15integer_before_offset\x18\x07 \x01(\x03\x12\x1c\n\x14integer_after_offset\x18\t \x01(\x03\x12\x1e\n\x16integer_scaling_factor\x18\x08 \x01(\x03\"U\n\x13\x46loatObjectiveProto\x12\x0c\n\x04vars\x18\x01 \x03(\x05\x12\x0e\n\x06\x63oeffs\x18\x02 \x03(\x01\x12\x0e\n\x06offset\x18\x03 \x01(\x01\x12\x10\n\x08maximize\x18\x04 \x01(\x08\"\x81\x05\n\x15\x44\x65\x63isionStrategyProto\x12\x11\n\tvariables\x18\x01 \x03(\x05\x12=\n\x05\x65xprs\x18\x05 \x03(\x0b\x32..operations_research.sat.LinearExpressionProto\x12m\n\x1bvariable_selection_strategy\x18\x02 \x01(\x0e\x32H.operations_research.sat.DecisionStrategyProto.VariableSelectionStrategy\x12i\n\x19\x64omain_reduction_strategy\x18\x03 \x01(\x0e\x32\x46.operations_research.sat.DecisionStrategyProto.DomainReductionStrategy\"\x94\x01\n\x19VariableSelectionStrategy\x12\x10\n\x0c\x43HOOSE_FIRST\x10\x00\x12\x15\n\x11\x43HOOSE_LOWEST_MIN\x10\x01\x12\x16\n\x12\x43HOOSE_HIGHEST_MAX\x10\x02\x12\x1a\n\x16\x43HOOSE_MIN_DOMAIN_SIZE\x10\x03\x12\x1a\n\x16\x43HOOSE_MAX_DOMAIN_SIZE\x10\x04\"\xa4\x01\n\x17\x44omainReductionStrategy\x12\x14\n\x10SELECT_MIN_VALUE\x10\x00\x12\x14\n\x10SELECT_MAX_VALUE\x10\x01\x12\x15\n\x11SELECT_LOWER_HALF\x10\x02\x12\x15\n\x11SELECT_UPPER_HALF\x10\x03\x12\x17\n\x13SELECT_MEDIAN_VALUE\x10\x04\x12\x16\n\x12SELECT_RANDOM_HALF\x10\x05\"9\n\x19PartialVariableAssignment\x12\x0c\n\x04vars\x18\x01 \x03(\x05\x12\x0e\n\x06values\x18\x02 \x03(\x03\">\n\x16SparsePermutationProto\x12\x0f\n\x07support\x18\x01 \x03(\x05\x12\x13\n\x0b\x63ycle_sizes\x18\x02 \x03(\x05\"G\n\x10\x44\x65nseMatrixProto\x12\x10\n\x08num_rows\x18\x01 \x01(\x05\x12\x10\n\x08num_cols\x18\x02 \x01(\x05\x12\x0f\n\x07\x65ntries\x18\x03 \x03(\x05\"\x94\x01\n\rSymmetryProto\x12\x45\n\x0cpermutations\x18\x01 \x03(\x0b\x32/.operations_research.sat.SparsePermutationProto\x12<\n\torbitopes\x18\x02 \x03(\x0b\x32).operations_research.sat.DenseMatrixProto\"\x8e\x04\n\x0c\x43pModelProto\x12\x0c\n\x04name\x18\x01 \x01(\t\x12@\n\tvariables\x18\x02 \x03(\x0b\x32-.operations_research.sat.IntegerVariableProto\x12=\n\x0b\x63onstraints\x18\x03 \x03(\x0b\x32(.operations_research.sat.ConstraintProto\x12<\n\tobjective\x18\x04 \x01(\x0b\x32).operations_research.sat.CpObjectiveProto\x12N\n\x18\x66loating_point_objective\x18\t \x01(\x0b\x32,.operations_research.sat.FloatObjectiveProto\x12G\n\x0fsearch_strategy\x18\x05 \x03(\x0b\x32..operations_research.sat.DecisionStrategyProto\x12I\n\rsolution_hint\x18\x06 \x01(\x0b\x32\x32.operations_research.sat.PartialVariableAssignment\x12\x13\n\x0b\x61ssumptions\x18\x07 \x03(\x05\x12\x38\n\x08symmetry\x18\x08 \x01(\x0b\x32&.operations_research.sat.SymmetryProto\"\"\n\x10\x43pSolverSolution\x12\x0e\n\x06values\x18\x01 \x03(\x03\"\xb1\x06\n\x10\x43pSolverResponse\x12\x37\n\x06status\x18\x01 \x01(\x0e\x32\'.operations_research.sat.CpSolverStatus\x12\x10\n\x08solution\x18\x02 \x03(\x03\x12\x17\n\x0fobjective_value\x18\x03 \x01(\x01\x12\x1c\n\x14\x62\x65st_objective_bound\x18\x04 \x01(\x01\x12G\n\x14\x61\x64\x64itional_solutions\x18\x1b \x03(\x0b\x32).operations_research.sat.CpSolverSolution\x12J\n\x13tightened_variables\x18\x15 \x03(\x0b\x32-.operations_research.sat.IntegerVariableProto\x12\x30\n(sufficient_assumptions_for_infeasibility\x18\x17 \x03(\x05\x12\x44\n\x11integer_objective\x18\x1c \x01(\x0b\x32).operations_research.sat.CpObjectiveProto\x12#\n\x1binner_objective_lower_bound\x18\x1d \x01(\x03\x12\x14\n\x0cnum_integers\x18\x1e \x01(\x03\x12\x14\n\x0cnum_booleans\x18\n \x01(\x03\x12\x1a\n\x12num_fixed_booleans\x18\x1f \x01(\x03\x12\x15\n\rnum_conflicts\x18\x0b \x01(\x03\x12\x14\n\x0cnum_branches\x18\x0c \x01(\x03\x12\x1f\n\x17num_binary_propagations\x18\r \x01(\x03\x12 \n\x18num_integer_propagations\x18\x0e \x01(\x03\x12\x14\n\x0cnum_restarts\x18\x18 \x01(\x03\x12\x19\n\x11num_lp_iterations\x18\x19 \x01(\x03\x12\x11\n\twall_time\x18\x0f \x01(\x01\x12\x11\n\tuser_time\x18\x10 \x01(\x01\x12\x1a\n\x12\x64\x65terministic_time\x18\x11 \x01(\x01\x12\x14\n\x0cgap_integral\x18\x16 \x01(\x01\x12\x15\n\rsolution_info\x18\x14 \x01(\t\x12\x11\n\tsolve_log\x18\x1a \x01(\t*[\n\x0e\x43pSolverStatus\x12\x0b\n\x07UNKNOWN\x10\x00\x12\x11\n\rMODEL_INVALID\x10\x01\x12\x0c\n\x08\x46\x45\x41SIBLE\x10\x02\x12\x0e\n\nINFEASIBLE\x10\x03\x12\x0b\n\x07OPTIMAL\x10\x04\x42v\n\x16\x63om.google.ortools.satB\x0f\x43pModelProtobufP\x01Z4github.com/google/or-tools/ortools/sat/proto/cpmodel\xaa\x02\x12Google.OrTools.Satb\x06proto3')
28
29_globals = globals()
30_builder.BuildMessageAndEnumDescriptors(DESCRIPTOR, _globals)
31_builder.BuildTopDescriptorsAndMessages(DESCRIPTOR, 'ortools.sat.cp_model_pb2', _globals)
32if not _descriptor._USE_C_DESCRIPTORS:
33  _globals['DESCRIPTOR']._loaded_options = None
34  _globals['DESCRIPTOR']._serialized_options = b'\n\026com.google.ortools.satB\017CpModelProtobufP\001Z4github.com/google/or-tools/ortools/sat/proto/cpmodel\252\002\022Google.OrTools.Sat'
35  _globals['_CPSOLVERSTATUS']._serialized_start=6548
36  _globals['_CPSOLVERSTATUS']._serialized_end=6639
37  _globals['_INTEGERVARIABLEPROTO']._serialized_start=55
38  _globals['_INTEGERVARIABLEPROTO']._serialized_end=107
39  _globals['_BOOLARGUMENTPROTO']._serialized_start=109
40  _globals['_BOOLARGUMENTPROTO']._serialized_end=146
41  _globals['_LINEAREXPRESSIONPROTO']._serialized_start=148
42  _globals['_LINEAREXPRESSIONPROTO']._serialized_end=217
43  _globals['_LINEARARGUMENTPROTO']._serialized_start=220
44  _globals['_LINEARARGUMENTPROTO']._serialized_end=368
45  _globals['_ALLDIFFERENTCONSTRAINTPROTO']._serialized_start=370
46  _globals['_ALLDIFFERENTCONSTRAINTPROTO']._serialized_end=462
47  _globals['_LINEARCONSTRAINTPROTO']._serialized_start=464
48  _globals['_LINEARCONSTRAINTPROTO']._serialized_end=533
49  _globals['_ELEMENTCONSTRAINTPROTO']._serialized_start=536
50  _globals['_ELEMENTCONSTRAINTPROTO']._serialized_end=809
51  _globals['_INTERVALCONSTRAINTPROTO']._serialized_start=812
52  _globals['_INTERVALCONSTRAINTPROTO']._serialized_end=1023
53  _globals['_NOOVERLAPCONSTRAINTPROTO']._serialized_start=1025
54  _globals['_NOOVERLAPCONSTRAINTPROTO']._serialized_end=1070
55  _globals['_NOOVERLAP2DCONSTRAINTPROTO']._serialized_start=1072
56  _globals['_NOOVERLAP2DCONSTRAINTPROTO']._serialized_end=1142
57  _globals['_CUMULATIVECONSTRAINTPROTO']._serialized_start=1145
58  _globals['_CUMULATIVECONSTRAINTPROTO']._serialized_end=1322
59  _globals['_RESERVOIRCONSTRAINTPROTO']._serialized_start=1325
60  _globals['_RESERVOIRCONSTRAINTPROTO']._serialized_end=1559
61  _globals['_CIRCUITCONSTRAINTPROTO']._serialized_start=1561
62  _globals['_CIRCUITCONSTRAINTPROTO']._serialized_end=1633
63  _globals['_ROUTESCONSTRAINTPROTO']._serialized_start=1635
64  _globals['_ROUTESCONSTRAINTPROTO']._serialized_end=1741
65  _globals['_TABLECONSTRAINTPROTO']._serialized_start=1744
66  _globals['_TABLECONSTRAINTPROTO']._serialized_end=1876
67  _globals['_INVERSECONSTRAINTPROTO']._serialized_start=1878
68  _globals['_INVERSECONSTRAINTPROTO']._serialized_end=1939
69  _globals['_AUTOMATONCONSTRAINTPROTO']._serialized_start=1942
70  _globals['_AUTOMATONCONSTRAINTPROTO']._serialized_end=2167
71  _globals['_LISTOFVARIABLESPROTO']._serialized_start=2169
72  _globals['_LISTOFVARIABLESPROTO']._serialized_end=2205
73  _globals['_CONSTRAINTPROTO']._serialized_start=2208
74  _globals['_CONSTRAINTPROTO']._serialized_end=3856
75  _globals['_CPOBJECTIVEPROTO']._serialized_start=3859
76  _globals['_CPOBJECTIVEPROTO']._serialized_end=4083
77  _globals['_FLOATOBJECTIVEPROTO']._serialized_start=4085
78  _globals['_FLOATOBJECTIVEPROTO']._serialized_end=4170
79  _globals['_DECISIONSTRATEGYPROTO']._serialized_start=4173
80  _globals['_DECISIONSTRATEGYPROTO']._serialized_end=4814
81  _globals['_DECISIONSTRATEGYPROTO_VARIABLESELECTIONSTRATEGY']._serialized_start=4499
82  _globals['_DECISIONSTRATEGYPROTO_VARIABLESELECTIONSTRATEGY']._serialized_end=4647
83  _globals['_DECISIONSTRATEGYPROTO_DOMAINREDUCTIONSTRATEGY']._serialized_start=4650
84  _globals['_DECISIONSTRATEGYPROTO_DOMAINREDUCTIONSTRATEGY']._serialized_end=4814
85  _globals['_PARTIALVARIABLEASSIGNMENT']._serialized_start=4816
86  _globals['_PARTIALVARIABLEASSIGNMENT']._serialized_end=4873
87  _globals['_SPARSEPERMUTATIONPROTO']._serialized_start=4875
88  _globals['_SPARSEPERMUTATIONPROTO']._serialized_end=4937
89  _globals['_DENSEMATRIXPROTO']._serialized_start=4939
90  _globals['_DENSEMATRIXPROTO']._serialized_end=5010
91  _globals['_SYMMETRYPROTO']._serialized_start=5013
92  _globals['_SYMMETRYPROTO']._serialized_end=5161
93  _globals['_CPMODELPROTO']._serialized_start=5164
94  _globals['_CPMODELPROTO']._serialized_end=5690
95  _globals['_CPSOLVERSOLUTION']._serialized_start=5692
96  _globals['_CPSOLVERSOLUTION']._serialized_end=5726
97  _globals['_CPSOLVERRESPONSE']._serialized_start=5729
98  _globals['_CPSOLVERRESPONSE']._serialized_end=6546
99# @@protoc_insertion_point(module_scope)
DESCRIPTOR = <google.protobuf.descriptor.FileDescriptor object>
class IntegerVariableProto(google.protobuf.message.Message):

Abstract base class for protocol messages.

Protocol message classes are almost always generated by the protocol compiler. These generated types subclass Message and implement the methods shown below.

IntegerVariableProto(**kwargs)
498  def init(self, **kwargs):
499    self._cached_byte_size = 0
500    self._cached_byte_size_dirty = len(kwargs) > 0
501    self._fields = {}
502    # Contains a mapping from oneof field descriptors to the descriptor
503    # of the currently set field in that oneof field.
504    self._oneofs = {}
505
506    # _unknown_fields is () when empty for efficiency, and will be turned into
507    # a list if fields are added.
508    self._unknown_fields = ()
509    self._is_present_in_parent = False
510    self._listener = message_listener_mod.NullMessageListener()
511    self._listener_for_children = _Listener(self)
512    for field_name, field_value in kwargs.items():
513      field = _GetFieldByName(message_descriptor, field_name)
514      if field is None:
515        raise TypeError('%s() got an unexpected keyword argument "%s"' %
516                        (message_descriptor.name, field_name))
517      if field_value is None:
518        # field=None is the same as no field at all.
519        continue
520      if field.label == _FieldDescriptor.LABEL_REPEATED:
521        field_copy = field._default_constructor(self)
522        if field.cpp_type == _FieldDescriptor.CPPTYPE_MESSAGE:  # Composite
523          if _IsMapField(field):
524            if _IsMessageMapField(field):
525              for key in field_value:
526                field_copy[key].MergeFrom(field_value[key])
527            else:
528              field_copy.update(field_value)
529          else:
530            for val in field_value:
531              if isinstance(val, dict):
532                field_copy.add(**val)
533              else:
534                field_copy.add().MergeFrom(val)
535        else:  # Scalar
536          if field.cpp_type == _FieldDescriptor.CPPTYPE_ENUM:
537            field_value = [_GetIntegerEnumValue(field.enum_type, val)
538                           for val in field_value]
539          field_copy.extend(field_value)
540        self._fields[field] = field_copy
541      elif field.cpp_type == _FieldDescriptor.CPPTYPE_MESSAGE:
542        field_copy = field._default_constructor(self)
543        new_val = None
544        if isinstance(field_value, message_mod.Message):
545          new_val = field_value
546        elif isinstance(field_value, dict):
547          if field.message_type.full_name == _StructFullTypeName:
548            field_copy.Clear()
549            if len(field_value) == 1 and 'fields' in field_value:
550              try:
551                field_copy.update(field_value)
552              except:
553                # Fall back to init normal message field
554                field_copy.Clear()
555                new_val = field.message_type._concrete_class(**field_value)
556            else:
557              field_copy.update(field_value)
558          else:
559            new_val = field.message_type._concrete_class(**field_value)
560        elif hasattr(field_copy, '_internal_assign'):
561          field_copy._internal_assign(field_value)
562        else:
563          raise TypeError(
564              'Message field {0}.{1} must be initialized with a '
565              'dict or instance of same class, got {2}.'.format(
566                  message_descriptor.name,
567                  field_name,
568                  type(field_value).__name__,
569              )
570          )
571
572        if new_val != None:
573          try:
574            field_copy.MergeFrom(new_val)
575          except TypeError:
576            _ReraiseTypeErrorWithFieldName(message_descriptor.name, field_name)
577        self._fields[field] = field_copy
578      else:
579        if field.cpp_type == _FieldDescriptor.CPPTYPE_ENUM:
580          field_value = _GetIntegerEnumValue(field.enum_type, field_value)
581        try:
582          setattr(self, field_name, field_value)
583        except TypeError:
584          _ReraiseTypeErrorWithFieldName(message_descriptor.name, field_name)
DESCRIPTOR = <google.protobuf.descriptor.Descriptor object>
def MergeFrom(self, msg):
1364  def MergeFrom(self, msg):
1365    if not isinstance(msg, cls):
1366      raise TypeError(
1367          'Parameter to MergeFrom() must be instance of same class: '
1368          'expected %s got %s.' % (_FullyQualifiedClassName(cls),
1369                                   _FullyQualifiedClassName(msg.__class__)))
1370
1371    assert msg is not self
1372    self._Modified()
1373
1374    fields = self._fields
1375
1376    for field, value in msg._fields.items():
1377      if field.label == LABEL_REPEATED:
1378        field_value = fields.get(field)
1379        if field_value is None:
1380          # Construct a new object to represent this field.
1381          field_value = field._default_constructor(self)
1382          fields[field] = field_value
1383        field_value.MergeFrom(value)
1384      elif field.cpp_type == CPPTYPE_MESSAGE:
1385        if value._is_present_in_parent:
1386          field_value = fields.get(field)
1387          if field_value is None:
1388            # Construct a new object to represent this field.
1389            field_value = field._default_constructor(self)
1390            fields[field] = field_value
1391          field_value.MergeFrom(value)
1392      else:
1393        self._fields[field] = value
1394        if field.containing_oneof:
1395          self._UpdateOneofState(field)
1396
1397    if msg._unknown_fields:
1398      if not self._unknown_fields:
1399        self._unknown_fields = []
1400      self._unknown_fields.extend(msg._unknown_fields)

Merges the contents of the specified message into current message.

This method merges the contents of the specified message into the current message. Singular fields that are set in the specified message overwrite the corresponding fields in the current message. Repeated fields are appended. Singular sub-messages and groups are recursively merged.

Arguments:
  • other_msg (Message): A message to merge into the current message.
def Clear(self):
1423def _Clear(self):
1424  # Clear fields.
1425  self._fields = {}
1426  self._unknown_fields = ()
1427
1428  self._oneofs = {}
1429  self._Modified()

Clears all data that was set in the message.

def SetInParent(self):
1489  def Modified(self):
1490    """Sets the _cached_byte_size_dirty bit to true,
1491    and propagates this to our listener iff this was a state change.
1492    """
1493
1494    # Note:  Some callers check _cached_byte_size_dirty before calling
1495    #   _Modified() as an extra optimization.  So, if this method is ever
1496    #   changed such that it does stuff even when _cached_byte_size_dirty is
1497    #   already true, the callers need to be updated.
1498    if not self._cached_byte_size_dirty:
1499      self._cached_byte_size_dirty = True
1500      self._listener_for_children.dirty = True
1501      self._is_present_in_parent = True
1502      self._listener.Modified()

Sets the _cached_byte_size_dirty bit to true, and propagates this to our listener iff this was a state change.

def IsInitialized(self, errors=None):
1265  def IsInitialized(self, errors=None):
1266    """Checks if all required fields of a message are set.
1267
1268    Args:
1269      errors:  A list which, if provided, will be populated with the field
1270               paths of all missing required fields.
1271
1272    Returns:
1273      True iff the specified message has all required fields set.
1274    """
1275
1276    # Performance is critical so we avoid HasField() and ListFields().
1277
1278    for field in required_fields:
1279      if (field not in self._fields or
1280          (field.cpp_type == _FieldDescriptor.CPPTYPE_MESSAGE and
1281           not self._fields[field]._is_present_in_parent)):
1282        if errors is not None:
1283          errors.extend(self.FindInitializationErrors())
1284        return False
1285
1286    for field, value in list(self._fields.items()):  # dict can change size!
1287      if field.cpp_type == _FieldDescriptor.CPPTYPE_MESSAGE:
1288        if field.label == _FieldDescriptor.LABEL_REPEATED:
1289          if (field.message_type._is_map_entry):
1290            continue
1291          for element in value:
1292            if not element.IsInitialized():
1293              if errors is not None:
1294                errors.extend(self.FindInitializationErrors())
1295              return False
1296        elif value._is_present_in_parent and not value.IsInitialized():
1297          if errors is not None:
1298            errors.extend(self.FindInitializationErrors())
1299          return False
1300
1301    return True

Checks if all required fields of a message are set.

Arguments:
  • errors: A list which, if provided, will be populated with the field paths of all missing required fields.
Returns:

True iff the specified message has all required fields set.

def MergeFromString(self, serialized):
1180  def MergeFromString(self, serialized):
1181    serialized = memoryview(serialized)
1182    length = len(serialized)
1183    try:
1184      if self._InternalParse(serialized, 0, length) != length:
1185        # The only reason _InternalParse would return early is if it
1186        # encountered an end-group tag.
1187        raise message_mod.DecodeError('Unexpected end-group tag.')
1188    except (IndexError, TypeError):
1189      # Now ord(buf[p:p+1]) == ord('') gets TypeError.
1190      raise message_mod.DecodeError('Truncated message.')
1191    except struct.error as e:
1192      raise message_mod.DecodeError(e)
1193    return length   # Return this for legacy reasons.

Merges serialized protocol buffer data into this message.

When we find a field in serialized that is already present in this message:

  • If it's a "repeated" field, we append to the end of our list.
  • Else, if it's a scalar, we overwrite our field.
  • Else, (it's a nonrepeated composite), we recursively merge into the existing composite.
Arguments:
  • serialized (bytes): Any object that allows us to call memoryview(serialized) to access a string of bytes using the buffer interface.
Returns:

int: The number of bytes read from serialized. For non-group messages, this will always be len(serialized), but for messages which are actually groups, this will generally be less than len(serialized), since we must stop when we reach an END_GROUP tag. Note that if we do stop because of an END_GROUP tag, the number of bytes returned does not include the bytes for the END_GROUP tag information.

Raises:
  • DecodeError: if the input cannot be parsed.
def SerializeToString(self, **kwargs):
1133  def SerializeToString(self, **kwargs):
1134    # Check if the message has all of its required fields set.
1135    if not self.IsInitialized():
1136      raise message_mod.EncodeError(
1137          'Message %s is missing required fields: %s' % (
1138          self.DESCRIPTOR.full_name, ','.join(self.FindInitializationErrors())))
1139    return self.SerializePartialToString(**kwargs)

Serializes the protocol message to a binary string.

Keyword Args:

deterministic (bool): If true, requests deterministic serialization of the protobuf, with predictable ordering of map keys.

Returns:

A binary string representation of the message if all of the required fields in the message are set (i.e. the message is initialized).

Raises:
def SerializePartialToString(self, **kwargs):
1146  def SerializePartialToString(self, **kwargs):
1147    out = BytesIO()
1148    self._InternalSerialize(out.write, **kwargs)
1149    return out.getvalue()

Serializes the protocol message to a binary string.

This method is similar to SerializeToString but doesn't check if the message is initialized.

Keyword Args:

deterministic (bool): If true, requests deterministic serialization of the protobuf, with predictable ordering of map keys.

Returns:

bytes: A serialized representation of the partial message.

def ListFields(self):
848  def ListFields(self):
849    all_fields = [item for item in self._fields.items() if _IsPresent(item)]
850    all_fields.sort(key = lambda item: item[0].number)
851    return all_fields

Returns a list of (FieldDescriptor, value) tuples for present fields.

A message field is non-empty if HasField() would return true. A singular primitive field is non-empty if HasField() would return true in proto2 or it is non zero in proto3. A repeated field is non-empty if it contains at least one element. The fields are ordered by field number.

Returns:

list[tuple(FieldDescriptor, value)]: field descriptors and values for all fields in the message which are not empty. The values vary by field type.

def HasField(self, field_name):
872  def HasField(self, field_name):
873    try:
874      field = hassable_fields[field_name]
875    except KeyError as exc:
876      raise ValueError('Protocol message %s has no non-repeated field "%s" '
877                       'nor has presence is not available for this field.' % (
878                           message_descriptor.full_name, field_name)) from exc
879
880    if isinstance(field, descriptor_mod.OneofDescriptor):
881      try:
882        return HasField(self, self._oneofs[field].name)
883      except KeyError:
884        return False
885    else:
886      if field.cpp_type == _FieldDescriptor.CPPTYPE_MESSAGE:
887        value = self._fields.get(field)
888        return value is not None and value._is_present_in_parent
889      else:
890        return field in self._fields

Checks if a certain field is set for the message.

For a oneof group, checks if any field inside is set. Note that if the field_name is not defined in the message descriptor, ValueError will be raised.

Arguments:
  • field_name (str): The name of the field to check for presence.
Returns:

bool: Whether a value has been set for the named field.

Raises:
  • ValueError: if the field_name is not a member of this message.
def ClearField(self, field_name):
897  def ClearField(self, field_name):
898    try:
899      field = message_descriptor.fields_by_name[field_name]
900    except KeyError:
901      try:
902        field = message_descriptor.oneofs_by_name[field_name]
903        if field in self._oneofs:
904          field = self._oneofs[field]
905        else:
906          return
907      except KeyError:
908        raise ValueError('Protocol message %s has no "%s" field.' %
909                         (message_descriptor.name, field_name))
910
911    if field in self._fields:
912      # To match the C++ implementation, we need to invalidate iterators
913      # for map fields when ClearField() happens.
914      if hasattr(self._fields[field], 'InvalidateIterators'):
915        self._fields[field].InvalidateIterators()
916
917      # Note:  If the field is a sub-message, its listener will still point
918      #   at us.  That's fine, because the worst than can happen is that it
919      #   will call _Modified() and invalidate our byte size.  Big deal.
920      del self._fields[field]
921
922      if self._oneofs.get(field.containing_oneof, None) is field:
923        del self._oneofs[field.containing_oneof]
924
925    # Always call _Modified() -- even if nothing was changed, this is
926    # a mutating method, and thus calling it should cause the field to become
927    # present in the parent message.
928    self._Modified()

Clears the contents of a given field.

Inside a oneof group, clears the field set. If the name neither refers to a defined field or oneof group, ValueError is raised.

Arguments:
  • field_name (str): The name of the field to check for presence.
Raises:
  • ValueError: if the field_name is not a member of this message.
def WhichOneof(self, oneof_name):
1406  def WhichOneof(self, oneof_name):
1407    """Returns the name of the currently set field inside a oneof, or None."""
1408    try:
1409      field = message_descriptor.oneofs_by_name[oneof_name]
1410    except KeyError:
1411      raise ValueError(
1412          'Protocol message has no oneof "%s" field.' % oneof_name)
1413
1414    nested_field = self._oneofs.get(field, None)
1415    if nested_field is not None and self.HasField(nested_field.name):
1416      return nested_field.name
1417    else:
1418      return None

Returns the name of the currently set field inside a oneof, or None.

def DiscardUnknownFields(self):
1438def _DiscardUnknownFields(self):
1439  self._unknown_fields = []
1440  for field, value in self.ListFields():
1441    if field.cpp_type == _FieldDescriptor.CPPTYPE_MESSAGE:
1442      if _IsMapField(field):
1443        if _IsMessageMapField(field):
1444          for key in value:
1445            value[key].DiscardUnknownFields()
1446      elif field.label == _FieldDescriptor.LABEL_REPEATED:
1447        for sub_message in value:
1448          sub_message.DiscardUnknownFields()
1449      else:
1450        value.DiscardUnknownFields()

Clears all fields in the UnknownFieldSet.

This operation is recursive for nested message.

def ByteSize(self):
1101  def ByteSize(self):
1102    if not self._cached_byte_size_dirty:
1103      return self._cached_byte_size
1104
1105    size = 0
1106    descriptor = self.DESCRIPTOR
1107    if descriptor._is_map_entry:
1108      # Fields of map entry should always be serialized.
1109      key_field = descriptor.fields_by_name['key']
1110      _MaybeAddEncoder(cls, key_field)
1111      size = key_field._sizer(self.key)
1112      value_field = descriptor.fields_by_name['value']
1113      _MaybeAddEncoder(cls, value_field)
1114      size += value_field._sizer(self.value)
1115    else:
1116      for field_descriptor, field_value in self.ListFields():
1117        _MaybeAddEncoder(cls, field_descriptor)
1118        size += field_descriptor._sizer(field_value)
1119      for tag_bytes, value_bytes in self._unknown_fields:
1120        size += len(tag_bytes) + len(value_bytes)
1121
1122    self._cached_byte_size = size
1123    self._cached_byte_size_dirty = False
1124    self._listener_for_children.dirty = False
1125    return size

Returns the serialized size of this message.

Recursively calls ByteSize() on all contained messages.

Returns:

int: The number of bytes required to serialize this message.

def FromString(s):
826  def FromString(s):
827    message = cls()
828    message.MergeFromString(s)
829    return message
NAME_FIELD_NUMBER = 1
name
711  def getter(self):
712    # TODO: This may be broken since there may not be
713    # default_value.  Combine with has_default_value somehow.
714    return self._fields.get(field, default_value)

Getter for name.

DOMAIN_FIELD_NUMBER = 2
domain
668  def getter(self):
669    field_value = self._fields.get(field)
670    if field_value is None:
671      # Construct a new object to represent this field.
672      field_value = field._default_constructor(self)
673
674      # Atomically check if another thread has preempted us and, if not, swap
675      # in the new object we just created.  If someone has preempted us, we
676      # take that object and discard ours.
677      # WARNING:  We are relying on setdefault() being atomic.  This is true
678      #   in CPython but we haven't investigated others.  This warning appears
679      #   in several other locations in this file.
680      field_value = self._fields.setdefault(field, field_value)
681    return field_value

Getter for domain.

def FindInitializationErrors(self):
1305  def FindInitializationErrors(self):
1306    """Finds required fields which are not initialized.
1307
1308    Returns:
1309      A list of strings.  Each string is a path to an uninitialized field from
1310      the top-level message, e.g. "foo.bar[5].baz".
1311    """
1312
1313    errors = []  # simplify things
1314
1315    for field in required_fields:
1316      if not self.HasField(field.name):
1317        errors.append(field.name)
1318
1319    for field, value in self.ListFields():
1320      if field.cpp_type == _FieldDescriptor.CPPTYPE_MESSAGE:
1321        if field.is_extension:
1322          name = '(%s)' % field.full_name
1323        else:
1324          name = field.name
1325
1326        if _IsMapField(field):
1327          if _IsMessageMapField(field):
1328            for key in value:
1329              element = value[key]
1330              prefix = '%s[%s].' % (name, key)
1331              sub_errors = element.FindInitializationErrors()
1332              errors += [prefix + error for error in sub_errors]
1333          else:
1334            # ScalarMaps can't have any initialization errors.
1335            pass
1336        elif field.label == _FieldDescriptor.LABEL_REPEATED:
1337          for i in range(len(value)):
1338            element = value[i]
1339            prefix = '%s[%d].' % (name, i)
1340            sub_errors = element.FindInitializationErrors()
1341            errors += [prefix + error for error in sub_errors]
1342        else:
1343          prefix = name + '.'
1344          sub_errors = value.FindInitializationErrors()
1345          errors += [prefix + error for error in sub_errors]
1346
1347    return errors

Finds required fields which are not initialized.

Returns:

A list of strings. Each string is a path to an uninitialized field from the top-level message, e.g. "foo.bar[5].baz".

class BoolArgumentProto(google.protobuf.message.Message):

Abstract base class for protocol messages.

Protocol message classes are almost always generated by the protocol compiler. These generated types subclass Message and implement the methods shown below.

BoolArgumentProto(**kwargs)
498  def init(self, **kwargs):
499    self._cached_byte_size = 0
500    self._cached_byte_size_dirty = len(kwargs) > 0
501    self._fields = {}
502    # Contains a mapping from oneof field descriptors to the descriptor
503    # of the currently set field in that oneof field.
504    self._oneofs = {}
505
506    # _unknown_fields is () when empty for efficiency, and will be turned into
507    # a list if fields are added.
508    self._unknown_fields = ()
509    self._is_present_in_parent = False
510    self._listener = message_listener_mod.NullMessageListener()
511    self._listener_for_children = _Listener(self)
512    for field_name, field_value in kwargs.items():
513      field = _GetFieldByName(message_descriptor, field_name)
514      if field is None:
515        raise TypeError('%s() got an unexpected keyword argument "%s"' %
516                        (message_descriptor.name, field_name))
517      if field_value is None:
518        # field=None is the same as no field at all.
519        continue
520      if field.label == _FieldDescriptor.LABEL_REPEATED:
521        field_copy = field._default_constructor(self)
522        if field.cpp_type == _FieldDescriptor.CPPTYPE_MESSAGE:  # Composite
523          if _IsMapField(field):
524            if _IsMessageMapField(field):
525              for key in field_value:
526                field_copy[key].MergeFrom(field_value[key])
527            else:
528              field_copy.update(field_value)
529          else:
530            for val in field_value:
531              if isinstance(val, dict):
532                field_copy.add(**val)
533              else:
534                field_copy.add().MergeFrom(val)
535        else:  # Scalar
536          if field.cpp_type == _FieldDescriptor.CPPTYPE_ENUM:
537            field_value = [_GetIntegerEnumValue(field.enum_type, val)
538                           for val in field_value]
539          field_copy.extend(field_value)
540        self._fields[field] = field_copy
541      elif field.cpp_type == _FieldDescriptor.CPPTYPE_MESSAGE:
542        field_copy = field._default_constructor(self)
543        new_val = None
544        if isinstance(field_value, message_mod.Message):
545          new_val = field_value
546        elif isinstance(field_value, dict):
547          if field.message_type.full_name == _StructFullTypeName:
548            field_copy.Clear()
549            if len(field_value) == 1 and 'fields' in field_value:
550              try:
551                field_copy.update(field_value)
552              except:
553                # Fall back to init normal message field
554                field_copy.Clear()
555                new_val = field.message_type._concrete_class(**field_value)
556            else:
557              field_copy.update(field_value)
558          else:
559            new_val = field.message_type._concrete_class(**field_value)
560        elif hasattr(field_copy, '_internal_assign'):
561          field_copy._internal_assign(field_value)
562        else:
563          raise TypeError(
564              'Message field {0}.{1} must be initialized with a '
565              'dict or instance of same class, got {2}.'.format(
566                  message_descriptor.name,
567                  field_name,
568                  type(field_value).__name__,
569              )
570          )
571
572        if new_val != None:
573          try:
574            field_copy.MergeFrom(new_val)
575          except TypeError:
576            _ReraiseTypeErrorWithFieldName(message_descriptor.name, field_name)
577        self._fields[field] = field_copy
578      else:
579        if field.cpp_type == _FieldDescriptor.CPPTYPE_ENUM:
580          field_value = _GetIntegerEnumValue(field.enum_type, field_value)
581        try:
582          setattr(self, field_name, field_value)
583        except TypeError:
584          _ReraiseTypeErrorWithFieldName(message_descriptor.name, field_name)
DESCRIPTOR = <google.protobuf.descriptor.Descriptor object>
def MergeFrom(self, msg):
1364  def MergeFrom(self, msg):
1365    if not isinstance(msg, cls):
1366      raise TypeError(
1367          'Parameter to MergeFrom() must be instance of same class: '
1368          'expected %s got %s.' % (_FullyQualifiedClassName(cls),
1369                                   _FullyQualifiedClassName(msg.__class__)))
1370
1371    assert msg is not self
1372    self._Modified()
1373
1374    fields = self._fields
1375
1376    for field, value in msg._fields.items():
1377      if field.label == LABEL_REPEATED:
1378        field_value = fields.get(field)
1379        if field_value is None:
1380          # Construct a new object to represent this field.
1381          field_value = field._default_constructor(self)
1382          fields[field] = field_value
1383        field_value.MergeFrom(value)
1384      elif field.cpp_type == CPPTYPE_MESSAGE:
1385        if value._is_present_in_parent:
1386          field_value = fields.get(field)
1387          if field_value is None:
1388            # Construct a new object to represent this field.
1389            field_value = field._default_constructor(self)
1390            fields[field] = field_value
1391          field_value.MergeFrom(value)
1392      else:
1393        self._fields[field] = value
1394        if field.containing_oneof:
1395          self._UpdateOneofState(field)
1396
1397    if msg._unknown_fields:
1398      if not self._unknown_fields:
1399        self._unknown_fields = []
1400      self._unknown_fields.extend(msg._unknown_fields)

Merges the contents of the specified message into current message.

This method merges the contents of the specified message into the current message. Singular fields that are set in the specified message overwrite the corresponding fields in the current message. Repeated fields are appended. Singular sub-messages and groups are recursively merged.

Arguments:
  • other_msg (Message): A message to merge into the current message.
def Clear(self):
1423def _Clear(self):
1424  # Clear fields.
1425  self._fields = {}
1426  self._unknown_fields = ()
1427
1428  self._oneofs = {}
1429  self._Modified()

Clears all data that was set in the message.

def SetInParent(self):
1489  def Modified(self):
1490    """Sets the _cached_byte_size_dirty bit to true,
1491    and propagates this to our listener iff this was a state change.
1492    """
1493
1494    # Note:  Some callers check _cached_byte_size_dirty before calling
1495    #   _Modified() as an extra optimization.  So, if this method is ever
1496    #   changed such that it does stuff even when _cached_byte_size_dirty is
1497    #   already true, the callers need to be updated.
1498    if not self._cached_byte_size_dirty:
1499      self._cached_byte_size_dirty = True
1500      self._listener_for_children.dirty = True
1501      self._is_present_in_parent = True
1502      self._listener.Modified()

Sets the _cached_byte_size_dirty bit to true, and propagates this to our listener iff this was a state change.

def IsInitialized(self, errors=None):
1265  def IsInitialized(self, errors=None):
1266    """Checks if all required fields of a message are set.
1267
1268    Args:
1269      errors:  A list which, if provided, will be populated with the field
1270               paths of all missing required fields.
1271
1272    Returns:
1273      True iff the specified message has all required fields set.
1274    """
1275
1276    # Performance is critical so we avoid HasField() and ListFields().
1277
1278    for field in required_fields:
1279      if (field not in self._fields or
1280          (field.cpp_type == _FieldDescriptor.CPPTYPE_MESSAGE and
1281           not self._fields[field]._is_present_in_parent)):
1282        if errors is not None:
1283          errors.extend(self.FindInitializationErrors())
1284        return False
1285
1286    for field, value in list(self._fields.items()):  # dict can change size!
1287      if field.cpp_type == _FieldDescriptor.CPPTYPE_MESSAGE:
1288        if field.label == _FieldDescriptor.LABEL_REPEATED:
1289          if (field.message_type._is_map_entry):
1290            continue
1291          for element in value:
1292            if not element.IsInitialized():
1293              if errors is not None:
1294                errors.extend(self.FindInitializationErrors())
1295              return False
1296        elif value._is_present_in_parent and not value.IsInitialized():
1297          if errors is not None:
1298            errors.extend(self.FindInitializationErrors())
1299          return False
1300
1301    return True

Checks if all required fields of a message are set.

Arguments:
  • errors: A list which, if provided, will be populated with the field paths of all missing required fields.
Returns:

True iff the specified message has all required fields set.

def MergeFromString(self, serialized):
1180  def MergeFromString(self, serialized):
1181    serialized = memoryview(serialized)
1182    length = len(serialized)
1183    try:
1184      if self._InternalParse(serialized, 0, length) != length:
1185        # The only reason _InternalParse would return early is if it
1186        # encountered an end-group tag.
1187        raise message_mod.DecodeError('Unexpected end-group tag.')
1188    except (IndexError, TypeError):
1189      # Now ord(buf[p:p+1]) == ord('') gets TypeError.
1190      raise message_mod.DecodeError('Truncated message.')
1191    except struct.error as e:
1192      raise message_mod.DecodeError(e)
1193    return length   # Return this for legacy reasons.

Merges serialized protocol buffer data into this message.

When we find a field in serialized that is already present in this message:

  • If it's a "repeated" field, we append to the end of our list.
  • Else, if it's a scalar, we overwrite our field.
  • Else, (it's a nonrepeated composite), we recursively merge into the existing composite.
Arguments:
  • serialized (bytes): Any object that allows us to call memoryview(serialized) to access a string of bytes using the buffer interface.
Returns:

int: The number of bytes read from serialized. For non-group messages, this will always be len(serialized), but for messages which are actually groups, this will generally be less than len(serialized), since we must stop when we reach an END_GROUP tag. Note that if we do stop because of an END_GROUP tag, the number of bytes returned does not include the bytes for the END_GROUP tag information.

Raises:
  • DecodeError: if the input cannot be parsed.
def SerializeToString(self, **kwargs):
1133  def SerializeToString(self, **kwargs):
1134    # Check if the message has all of its required fields set.
1135    if not self.IsInitialized():
1136      raise message_mod.EncodeError(
1137          'Message %s is missing required fields: %s' % (
1138          self.DESCRIPTOR.full_name, ','.join(self.FindInitializationErrors())))
1139    return self.SerializePartialToString(**kwargs)

Serializes the protocol message to a binary string.

Keyword Args:

deterministic (bool): If true, requests deterministic serialization of the protobuf, with predictable ordering of map keys.

Returns:

A binary string representation of the message if all of the required fields in the message are set (i.e. the message is initialized).

Raises:
def SerializePartialToString(self, **kwargs):
1146  def SerializePartialToString(self, **kwargs):
1147    out = BytesIO()
1148    self._InternalSerialize(out.write, **kwargs)
1149    return out.getvalue()

Serializes the protocol message to a binary string.

This method is similar to SerializeToString but doesn't check if the message is initialized.

Keyword Args:

deterministic (bool): If true, requests deterministic serialization of the protobuf, with predictable ordering of map keys.

Returns:

bytes: A serialized representation of the partial message.

def ListFields(self):
848  def ListFields(self):
849    all_fields = [item for item in self._fields.items() if _IsPresent(item)]
850    all_fields.sort(key = lambda item: item[0].number)
851    return all_fields

Returns a list of (FieldDescriptor, value) tuples for present fields.

A message field is non-empty if HasField() would return true. A singular primitive field is non-empty if HasField() would return true in proto2 or it is non zero in proto3. A repeated field is non-empty if it contains at least one element. The fields are ordered by field number.

Returns:

list[tuple(FieldDescriptor, value)]: field descriptors and values for all fields in the message which are not empty. The values vary by field type.

def HasField(self, field_name):
872  def HasField(self, field_name):
873    try:
874      field = hassable_fields[field_name]
875    except KeyError as exc:
876      raise ValueError('Protocol message %s has no non-repeated field "%s" '
877                       'nor has presence is not available for this field.' % (
878                           message_descriptor.full_name, field_name)) from exc
879
880    if isinstance(field, descriptor_mod.OneofDescriptor):
881      try:
882        return HasField(self, self._oneofs[field].name)
883      except KeyError:
884        return False
885    else:
886      if field.cpp_type == _FieldDescriptor.CPPTYPE_MESSAGE:
887        value = self._fields.get(field)
888        return value is not None and value._is_present_in_parent
889      else:
890        return field in self._fields

Checks if a certain field is set for the message.

For a oneof group, checks if any field inside is set. Note that if the field_name is not defined in the message descriptor, ValueError will be raised.

Arguments:
  • field_name (str): The name of the field to check for presence.
Returns:

bool: Whether a value has been set for the named field.

Raises:
  • ValueError: if the field_name is not a member of this message.
def ClearField(self, field_name):
897  def ClearField(self, field_name):
898    try:
899      field = message_descriptor.fields_by_name[field_name]
900    except KeyError:
901      try:
902        field = message_descriptor.oneofs_by_name[field_name]
903        if field in self._oneofs:
904          field = self._oneofs[field]
905        else:
906          return
907      except KeyError:
908        raise ValueError('Protocol message %s has no "%s" field.' %
909                         (message_descriptor.name, field_name))
910
911    if field in self._fields:
912      # To match the C++ implementation, we need to invalidate iterators
913      # for map fields when ClearField() happens.
914      if hasattr(self._fields[field], 'InvalidateIterators'):
915        self._fields[field].InvalidateIterators()
916
917      # Note:  If the field is a sub-message, its listener will still point
918      #   at us.  That's fine, because the worst than can happen is that it
919      #   will call _Modified() and invalidate our byte size.  Big deal.
920      del self._fields[field]
921
922      if self._oneofs.get(field.containing_oneof, None) is field:
923        del self._oneofs[field.containing_oneof]
924
925    # Always call _Modified() -- even if nothing was changed, this is
926    # a mutating method, and thus calling it should cause the field to become
927    # present in the parent message.
928    self._Modified()

Clears the contents of a given field.

Inside a oneof group, clears the field set. If the name neither refers to a defined field or oneof group, ValueError is raised.

Arguments:
  • field_name (str): The name of the field to check for presence.
Raises:
  • ValueError: if the field_name is not a member of this message.
def WhichOneof(self, oneof_name):
1406  def WhichOneof(self, oneof_name):
1407    """Returns the name of the currently set field inside a oneof, or None."""
1408    try:
1409      field = message_descriptor.oneofs_by_name[oneof_name]
1410    except KeyError:
1411      raise ValueError(
1412          'Protocol message has no oneof "%s" field.' % oneof_name)
1413
1414    nested_field = self._oneofs.get(field, None)
1415    if nested_field is not None and self.HasField(nested_field.name):
1416      return nested_field.name
1417    else:
1418      return None

Returns the name of the currently set field inside a oneof, or None.

def DiscardUnknownFields(self):
1438def _DiscardUnknownFields(self):
1439  self._unknown_fields = []
1440  for field, value in self.ListFields():
1441    if field.cpp_type == _FieldDescriptor.CPPTYPE_MESSAGE:
1442      if _IsMapField(field):
1443        if _IsMessageMapField(field):
1444          for key in value:
1445            value[key].DiscardUnknownFields()
1446      elif field.label == _FieldDescriptor.LABEL_REPEATED:
1447        for sub_message in value:
1448          sub_message.DiscardUnknownFields()
1449      else:
1450        value.DiscardUnknownFields()

Clears all fields in the UnknownFieldSet.

This operation is recursive for nested message.

def ByteSize(self):
1101  def ByteSize(self):
1102    if not self._cached_byte_size_dirty:
1103      return self._cached_byte_size
1104
1105    size = 0
1106    descriptor = self.DESCRIPTOR
1107    if descriptor._is_map_entry:
1108      # Fields of map entry should always be serialized.
1109      key_field = descriptor.fields_by_name['key']
1110      _MaybeAddEncoder(cls, key_field)
1111      size = key_field._sizer(self.key)
1112      value_field = descriptor.fields_by_name['value']
1113      _MaybeAddEncoder(cls, value_field)
1114      size += value_field._sizer(self.value)
1115    else:
1116      for field_descriptor, field_value in self.ListFields():
1117        _MaybeAddEncoder(cls, field_descriptor)
1118        size += field_descriptor._sizer(field_value)
1119      for tag_bytes, value_bytes in self._unknown_fields:
1120        size += len(tag_bytes) + len(value_bytes)
1121
1122    self._cached_byte_size = size
1123    self._cached_byte_size_dirty = False
1124    self._listener_for_children.dirty = False
1125    return size

Returns the serialized size of this message.

Recursively calls ByteSize() on all contained messages.

Returns:

int: The number of bytes required to serialize this message.

def FromString(s):
826  def FromString(s):
827    message = cls()
828    message.MergeFromString(s)
829    return message
LITERALS_FIELD_NUMBER = 1
literals
668  def getter(self):
669    field_value = self._fields.get(field)
670    if field_value is None:
671      # Construct a new object to represent this field.
672      field_value = field._default_constructor(self)
673
674      # Atomically check if another thread has preempted us and, if not, swap
675      # in the new object we just created.  If someone has preempted us, we
676      # take that object and discard ours.
677      # WARNING:  We are relying on setdefault() being atomic.  This is true
678      #   in CPython but we haven't investigated others.  This warning appears
679      #   in several other locations in this file.
680      field_value = self._fields.setdefault(field, field_value)
681    return field_value

Getter for literals.

def FindInitializationErrors(self):
1305  def FindInitializationErrors(self):
1306    """Finds required fields which are not initialized.
1307
1308    Returns:
1309      A list of strings.  Each string is a path to an uninitialized field from
1310      the top-level message, e.g. "foo.bar[5].baz".
1311    """
1312
1313    errors = []  # simplify things
1314
1315    for field in required_fields:
1316      if not self.HasField(field.name):
1317        errors.append(field.name)
1318
1319    for field, value in self.ListFields():
1320      if field.cpp_type == _FieldDescriptor.CPPTYPE_MESSAGE:
1321        if field.is_extension:
1322          name = '(%s)' % field.full_name
1323        else:
1324          name = field.name
1325
1326        if _IsMapField(field):
1327          if _IsMessageMapField(field):
1328            for key in value:
1329              element = value[key]
1330              prefix = '%s[%s].' % (name, key)
1331              sub_errors = element.FindInitializationErrors()
1332              errors += [prefix + error for error in sub_errors]
1333          else:
1334            # ScalarMaps can't have any initialization errors.
1335            pass
1336        elif field.label == _FieldDescriptor.LABEL_REPEATED:
1337          for i in range(len(value)):
1338            element = value[i]
1339            prefix = '%s[%d].' % (name, i)
1340            sub_errors = element.FindInitializationErrors()
1341            errors += [prefix + error for error in sub_errors]
1342        else:
1343          prefix = name + '.'
1344          sub_errors = value.FindInitializationErrors()
1345          errors += [prefix + error for error in sub_errors]
1346
1347    return errors

Finds required fields which are not initialized.

Returns:

A list of strings. Each string is a path to an uninitialized field from the top-level message, e.g. "foo.bar[5].baz".

class LinearExpressionProto(google.protobuf.message.Message):

Abstract base class for protocol messages.

Protocol message classes are almost always generated by the protocol compiler. These generated types subclass Message and implement the methods shown below.

LinearExpressionProto(**kwargs)
498  def init(self, **kwargs):
499    self._cached_byte_size = 0
500    self._cached_byte_size_dirty = len(kwargs) > 0
501    self._fields = {}
502    # Contains a mapping from oneof field descriptors to the descriptor
503    # of the currently set field in that oneof field.
504    self._oneofs = {}
505
506    # _unknown_fields is () when empty for efficiency, and will be turned into
507    # a list if fields are added.
508    self._unknown_fields = ()
509    self._is_present_in_parent = False
510    self._listener = message_listener_mod.NullMessageListener()
511    self._listener_for_children = _Listener(self)
512    for field_name, field_value in kwargs.items():
513      field = _GetFieldByName(message_descriptor, field_name)
514      if field is None:
515        raise TypeError('%s() got an unexpected keyword argument "%s"' %
516                        (message_descriptor.name, field_name))
517      if field_value is None:
518        # field=None is the same as no field at all.
519        continue
520      if field.label == _FieldDescriptor.LABEL_REPEATED:
521        field_copy = field._default_constructor(self)
522        if field.cpp_type == _FieldDescriptor.CPPTYPE_MESSAGE:  # Composite
523          if _IsMapField(field):
524            if _IsMessageMapField(field):
525              for key in field_value:
526                field_copy[key].MergeFrom(field_value[key])
527            else:
528              field_copy.update(field_value)
529          else:
530            for val in field_value:
531              if isinstance(val, dict):
532                field_copy.add(**val)
533              else:
534                field_copy.add().MergeFrom(val)
535        else:  # Scalar
536          if field.cpp_type == _FieldDescriptor.CPPTYPE_ENUM:
537            field_value = [_GetIntegerEnumValue(field.enum_type, val)
538                           for val in field_value]
539          field_copy.extend(field_value)
540        self._fields[field] = field_copy
541      elif field.cpp_type == _FieldDescriptor.CPPTYPE_MESSAGE:
542        field_copy = field._default_constructor(self)
543        new_val = None
544        if isinstance(field_value, message_mod.Message):
545          new_val = field_value
546        elif isinstance(field_value, dict):
547          if field.message_type.full_name == _StructFullTypeName:
548            field_copy.Clear()
549            if len(field_value) == 1 and 'fields' in field_value:
550              try:
551                field_copy.update(field_value)
552              except:
553                # Fall back to init normal message field
554                field_copy.Clear()
555                new_val = field.message_type._concrete_class(**field_value)
556            else:
557              field_copy.update(field_value)
558          else:
559            new_val = field.message_type._concrete_class(**field_value)
560        elif hasattr(field_copy, '_internal_assign'):
561          field_copy._internal_assign(field_value)
562        else:
563          raise TypeError(
564              'Message field {0}.{1} must be initialized with a '
565              'dict or instance of same class, got {2}.'.format(
566                  message_descriptor.name,
567                  field_name,
568                  type(field_value).__name__,
569              )
570          )
571
572        if new_val != None:
573          try:
574            field_copy.MergeFrom(new_val)
575          except TypeError:
576            _ReraiseTypeErrorWithFieldName(message_descriptor.name, field_name)
577        self._fields[field] = field_copy
578      else:
579        if field.cpp_type == _FieldDescriptor.CPPTYPE_ENUM:
580          field_value = _GetIntegerEnumValue(field.enum_type, field_value)
581        try:
582          setattr(self, field_name, field_value)
583        except TypeError:
584          _ReraiseTypeErrorWithFieldName(message_descriptor.name, field_name)
DESCRIPTOR = <google.protobuf.descriptor.Descriptor object>
def MergeFrom(self, msg):
1364  def MergeFrom(self, msg):
1365    if not isinstance(msg, cls):
1366      raise TypeError(
1367          'Parameter to MergeFrom() must be instance of same class: '
1368          'expected %s got %s.' % (_FullyQualifiedClassName(cls),
1369                                   _FullyQualifiedClassName(msg.__class__)))
1370
1371    assert msg is not self
1372    self._Modified()
1373
1374    fields = self._fields
1375
1376    for field, value in msg._fields.items():
1377      if field.label == LABEL_REPEATED:
1378        field_value = fields.get(field)
1379        if field_value is None:
1380          # Construct a new object to represent this field.
1381          field_value = field._default_constructor(self)
1382          fields[field] = field_value
1383        field_value.MergeFrom(value)
1384      elif field.cpp_type == CPPTYPE_MESSAGE:
1385        if value._is_present_in_parent:
1386          field_value = fields.get(field)
1387          if field_value is None:
1388            # Construct a new object to represent this field.
1389            field_value = field._default_constructor(self)
1390            fields[field] = field_value
1391          field_value.MergeFrom(value)
1392      else:
1393        self._fields[field] = value
1394        if field.containing_oneof:
1395          self._UpdateOneofState(field)
1396
1397    if msg._unknown_fields:
1398      if not self._unknown_fields:
1399        self._unknown_fields = []
1400      self._unknown_fields.extend(msg._unknown_fields)

Merges the contents of the specified message into current message.

This method merges the contents of the specified message into the current message. Singular fields that are set in the specified message overwrite the corresponding fields in the current message. Repeated fields are appended. Singular sub-messages and groups are recursively merged.

Arguments:
  • other_msg (Message): A message to merge into the current message.
def Clear(self):
1423def _Clear(self):
1424  # Clear fields.
1425  self._fields = {}
1426  self._unknown_fields = ()
1427
1428  self._oneofs = {}
1429  self._Modified()

Clears all data that was set in the message.

def SetInParent(self):
1489  def Modified(self):
1490    """Sets the _cached_byte_size_dirty bit to true,
1491    and propagates this to our listener iff this was a state change.
1492    """
1493
1494    # Note:  Some callers check _cached_byte_size_dirty before calling
1495    #   _Modified() as an extra optimization.  So, if this method is ever
1496    #   changed such that it does stuff even when _cached_byte_size_dirty is
1497    #   already true, the callers need to be updated.
1498    if not self._cached_byte_size_dirty:
1499      self._cached_byte_size_dirty = True
1500      self._listener_for_children.dirty = True
1501      self._is_present_in_parent = True
1502      self._listener.Modified()

Sets the _cached_byte_size_dirty bit to true, and propagates this to our listener iff this was a state change.

def IsInitialized(self, errors=None):
1265  def IsInitialized(self, errors=None):
1266    """Checks if all required fields of a message are set.
1267
1268    Args:
1269      errors:  A list which, if provided, will be populated with the field
1270               paths of all missing required fields.
1271
1272    Returns:
1273      True iff the specified message has all required fields set.
1274    """
1275
1276    # Performance is critical so we avoid HasField() and ListFields().
1277
1278    for field in required_fields:
1279      if (field not in self._fields or
1280          (field.cpp_type == _FieldDescriptor.CPPTYPE_MESSAGE and
1281           not self._fields[field]._is_present_in_parent)):
1282        if errors is not None:
1283          errors.extend(self.FindInitializationErrors())
1284        return False
1285
1286    for field, value in list(self._fields.items()):  # dict can change size!
1287      if field.cpp_type == _FieldDescriptor.CPPTYPE_MESSAGE:
1288        if field.label == _FieldDescriptor.LABEL_REPEATED:
1289          if (field.message_type._is_map_entry):
1290            continue
1291          for element in value:
1292            if not element.IsInitialized():
1293              if errors is not None:
1294                errors.extend(self.FindInitializationErrors())
1295              return False
1296        elif value._is_present_in_parent and not value.IsInitialized():
1297          if errors is not None:
1298            errors.extend(self.FindInitializationErrors())
1299          return False
1300
1301    return True

Checks if all required fields of a message are set.

Arguments:
  • errors: A list which, if provided, will be populated with the field paths of all missing required fields.
Returns:

True iff the specified message has all required fields set.

def MergeFromString(self, serialized):
1180  def MergeFromString(self, serialized):
1181    serialized = memoryview(serialized)
1182    length = len(serialized)
1183    try:
1184      if self._InternalParse(serialized, 0, length) != length:
1185        # The only reason _InternalParse would return early is if it
1186        # encountered an end-group tag.
1187        raise message_mod.DecodeError('Unexpected end-group tag.')
1188    except (IndexError, TypeError):
1189      # Now ord(buf[p:p+1]) == ord('') gets TypeError.
1190      raise message_mod.DecodeError('Truncated message.')
1191    except struct.error as e:
1192      raise message_mod.DecodeError(e)
1193    return length   # Return this for legacy reasons.

Merges serialized protocol buffer data into this message.

When we find a field in serialized that is already present in this message:

  • If it's a "repeated" field, we append to the end of our list.
  • Else, if it's a scalar, we overwrite our field.
  • Else, (it's a nonrepeated composite), we recursively merge into the existing composite.
Arguments:
  • serialized (bytes): Any object that allows us to call memoryview(serialized) to access a string of bytes using the buffer interface.
Returns:

int: The number of bytes read from serialized. For non-group messages, this will always be len(serialized), but for messages which are actually groups, this will generally be less than len(serialized), since we must stop when we reach an END_GROUP tag. Note that if we do stop because of an END_GROUP tag, the number of bytes returned does not include the bytes for the END_GROUP tag information.

Raises:
  • DecodeError: if the input cannot be parsed.
def SerializeToString(self, **kwargs):
1133  def SerializeToString(self, **kwargs):
1134    # Check if the message has all of its required fields set.
1135    if not self.IsInitialized():
1136      raise message_mod.EncodeError(
1137          'Message %s is missing required fields: %s' % (
1138          self.DESCRIPTOR.full_name, ','.join(self.FindInitializationErrors())))
1139    return self.SerializePartialToString(**kwargs)

Serializes the protocol message to a binary string.

Keyword Args:

deterministic (bool): If true, requests deterministic serialization of the protobuf, with predictable ordering of map keys.

Returns:

A binary string representation of the message if all of the required fields in the message are set (i.e. the message is initialized).

Raises:
def SerializePartialToString(self, **kwargs):
1146  def SerializePartialToString(self, **kwargs):
1147    out = BytesIO()
1148    self._InternalSerialize(out.write, **kwargs)
1149    return out.getvalue()

Serializes the protocol message to a binary string.

This method is similar to SerializeToString but doesn't check if the message is initialized.

Keyword Args:

deterministic (bool): If true, requests deterministic serialization of the protobuf, with predictable ordering of map keys.

Returns:

bytes: A serialized representation of the partial message.

def ListFields(self):
848  def ListFields(self):
849    all_fields = [item for item in self._fields.items() if _IsPresent(item)]
850    all_fields.sort(key = lambda item: item[0].number)
851    return all_fields

Returns a list of (FieldDescriptor, value) tuples for present fields.

A message field is non-empty if HasField() would return true. A singular primitive field is non-empty if HasField() would return true in proto2 or it is non zero in proto3. A repeated field is non-empty if it contains at least one element. The fields are ordered by field number.

Returns:

list[tuple(FieldDescriptor, value)]: field descriptors and values for all fields in the message which are not empty. The values vary by field type.

def HasField(self, field_name):
872  def HasField(self, field_name):
873    try:
874      field = hassable_fields[field_name]
875    except KeyError as exc:
876      raise ValueError('Protocol message %s has no non-repeated field "%s" '
877                       'nor has presence is not available for this field.' % (
878                           message_descriptor.full_name, field_name)) from exc
879
880    if isinstance(field, descriptor_mod.OneofDescriptor):
881      try:
882        return HasField(self, self._oneofs[field].name)
883      except KeyError:
884        return False
885    else:
886      if field.cpp_type == _FieldDescriptor.CPPTYPE_MESSAGE:
887        value = self._fields.get(field)
888        return value is not None and value._is_present_in_parent
889      else:
890        return field in self._fields

Checks if a certain field is set for the message.

For a oneof group, checks if any field inside is set. Note that if the field_name is not defined in the message descriptor, ValueError will be raised.

Arguments:
  • field_name (str): The name of the field to check for presence.
Returns:

bool: Whether a value has been set for the named field.

Raises:
  • ValueError: if the field_name is not a member of this message.
def ClearField(self, field_name):
897  def ClearField(self, field_name):
898    try:
899      field = message_descriptor.fields_by_name[field_name]
900    except KeyError:
901      try:
902        field = message_descriptor.oneofs_by_name[field_name]
903        if field in self._oneofs:
904          field = self._oneofs[field]
905        else:
906          return
907      except KeyError:
908        raise ValueError('Protocol message %s has no "%s" field.' %
909                         (message_descriptor.name, field_name))
910
911    if field in self._fields:
912      # To match the C++ implementation, we need to invalidate iterators
913      # for map fields when ClearField() happens.
914      if hasattr(self._fields[field], 'InvalidateIterators'):
915        self._fields[field].InvalidateIterators()
916
917      # Note:  If the field is a sub-message, its listener will still point
918      #   at us.  That's fine, because the worst than can happen is that it
919      #   will call _Modified() and invalidate our byte size.  Big deal.
920      del self._fields[field]
921
922      if self._oneofs.get(field.containing_oneof, None) is field:
923        del self._oneofs[field.containing_oneof]
924
925    # Always call _Modified() -- even if nothing was changed, this is
926    # a mutating method, and thus calling it should cause the field to become
927    # present in the parent message.
928    self._Modified()

Clears the contents of a given field.

Inside a oneof group, clears the field set. If the name neither refers to a defined field or oneof group, ValueError is raised.

Arguments:
  • field_name (str): The name of the field to check for presence.
Raises:
  • ValueError: if the field_name is not a member of this message.
def WhichOneof(self, oneof_name):
1406  def WhichOneof(self, oneof_name):
1407    """Returns the name of the currently set field inside a oneof, or None."""
1408    try:
1409      field = message_descriptor.oneofs_by_name[oneof_name]
1410    except KeyError:
1411      raise ValueError(
1412          'Protocol message has no oneof "%s" field.' % oneof_name)
1413
1414    nested_field = self._oneofs.get(field, None)
1415    if nested_field is not None and self.HasField(nested_field.name):
1416      return nested_field.name
1417    else:
1418      return None

Returns the name of the currently set field inside a oneof, or None.

def DiscardUnknownFields(self):
1438def _DiscardUnknownFields(self):
1439  self._unknown_fields = []
1440  for field, value in self.ListFields():
1441    if field.cpp_type == _FieldDescriptor.CPPTYPE_MESSAGE:
1442      if _IsMapField(field):
1443        if _IsMessageMapField(field):
1444          for key in value:
1445            value[key].DiscardUnknownFields()
1446      elif field.label == _FieldDescriptor.LABEL_REPEATED:
1447        for sub_message in value:
1448          sub_message.DiscardUnknownFields()
1449      else:
1450        value.DiscardUnknownFields()

Clears all fields in the UnknownFieldSet.

This operation is recursive for nested message.

def ByteSize(self):
1101  def ByteSize(self):
1102    if not self._cached_byte_size_dirty:
1103      return self._cached_byte_size
1104
1105    size = 0
1106    descriptor = self.DESCRIPTOR
1107    if descriptor._is_map_entry:
1108      # Fields of map entry should always be serialized.
1109      key_field = descriptor.fields_by_name['key']
1110      _MaybeAddEncoder(cls, key_field)
1111      size = key_field._sizer(self.key)
1112      value_field = descriptor.fields_by_name['value']
1113      _MaybeAddEncoder(cls, value_field)
1114      size += value_field._sizer(self.value)
1115    else:
1116      for field_descriptor, field_value in self.ListFields():
1117        _MaybeAddEncoder(cls, field_descriptor)
1118        size += field_descriptor._sizer(field_value)
1119      for tag_bytes, value_bytes in self._unknown_fields:
1120        size += len(tag_bytes) + len(value_bytes)
1121
1122    self._cached_byte_size = size
1123    self._cached_byte_size_dirty = False
1124    self._listener_for_children.dirty = False
1125    return size

Returns the serialized size of this message.

Recursively calls ByteSize() on all contained messages.

Returns:

int: The number of bytes required to serialize this message.

def FromString(s):
826  def FromString(s):
827    message = cls()
828    message.MergeFromString(s)
829    return message
VARS_FIELD_NUMBER = 1
vars
668  def getter(self):
669    field_value = self._fields.get(field)
670    if field_value is None:
671      # Construct a new object to represent this field.
672      field_value = field._default_constructor(self)
673
674      # Atomically check if another thread has preempted us and, if not, swap
675      # in the new object we just created.  If someone has preempted us, we
676      # take that object and discard ours.
677      # WARNING:  We are relying on setdefault() being atomic.  This is true
678      #   in CPython but we haven't investigated others.  This warning appears
679      #   in several other locations in this file.
680      field_value = self._fields.setdefault(field, field_value)
681    return field_value

Getter for vars.

COEFFS_FIELD_NUMBER = 2
coeffs
668  def getter(self):
669    field_value = self._fields.get(field)
670    if field_value is None:
671      # Construct a new object to represent this field.
672      field_value = field._default_constructor(self)
673
674      # Atomically check if another thread has preempted us and, if not, swap
675      # in the new object we just created.  If someone has preempted us, we
676      # take that object and discard ours.
677      # WARNING:  We are relying on setdefault() being atomic.  This is true
678      #   in CPython but we haven't investigated others.  This warning appears
679      #   in several other locations in this file.
680      field_value = self._fields.setdefault(field, field_value)
681    return field_value

Getter for coeffs.

OFFSET_FIELD_NUMBER = 3
offset
711  def getter(self):
712    # TODO: This may be broken since there may not be
713    # default_value.  Combine with has_default_value somehow.
714    return self._fields.get(field, default_value)

Getter for offset.

def FindInitializationErrors(self):
1305  def FindInitializationErrors(self):
1306    """Finds required fields which are not initialized.
1307
1308    Returns:
1309      A list of strings.  Each string is a path to an uninitialized field from
1310      the top-level message, e.g. "foo.bar[5].baz".
1311    """
1312
1313    errors = []  # simplify things
1314
1315    for field in required_fields:
1316      if not self.HasField(field.name):
1317        errors.append(field.name)
1318
1319    for field, value in self.ListFields():
1320      if field.cpp_type == _FieldDescriptor.CPPTYPE_MESSAGE:
1321        if field.is_extension:
1322          name = '(%s)' % field.full_name
1323        else:
1324          name = field.name
1325
1326        if _IsMapField(field):
1327          if _IsMessageMapField(field):
1328            for key in value:
1329              element = value[key]
1330              prefix = '%s[%s].' % (name, key)
1331              sub_errors = element.FindInitializationErrors()
1332              errors += [prefix + error for error in sub_errors]
1333          else:
1334            # ScalarMaps can't have any initialization errors.
1335            pass
1336        elif field.label == _FieldDescriptor.LABEL_REPEATED:
1337          for i in range(len(value)):
1338            element = value[i]
1339            prefix = '%s[%d].' % (name, i)
1340            sub_errors = element.FindInitializationErrors()
1341            errors += [prefix + error for error in sub_errors]
1342        else:
1343          prefix = name + '.'
1344          sub_errors = value.FindInitializationErrors()
1345          errors += [prefix + error for error in sub_errors]
1346
1347    return errors

Finds required fields which are not initialized.

Returns:

A list of strings. Each string is a path to an uninitialized field from the top-level message, e.g. "foo.bar[5].baz".

class LinearArgumentProto(google.protobuf.message.Message):

Abstract base class for protocol messages.

Protocol message classes are almost always generated by the protocol compiler. These generated types subclass Message and implement the methods shown below.

LinearArgumentProto(**kwargs)
498  def init(self, **kwargs):
499    self._cached_byte_size = 0
500    self._cached_byte_size_dirty = len(kwargs) > 0
501    self._fields = {}
502    # Contains a mapping from oneof field descriptors to the descriptor
503    # of the currently set field in that oneof field.
504    self._oneofs = {}
505
506    # _unknown_fields is () when empty for efficiency, and will be turned into
507    # a list if fields are added.
508    self._unknown_fields = ()
509    self._is_present_in_parent = False
510    self._listener = message_listener_mod.NullMessageListener()
511    self._listener_for_children = _Listener(self)
512    for field_name, field_value in kwargs.items():
513      field = _GetFieldByName(message_descriptor, field_name)
514      if field is None:
515        raise TypeError('%s() got an unexpected keyword argument "%s"' %
516                        (message_descriptor.name, field_name))
517      if field_value is None:
518        # field=None is the same as no field at all.
519        continue
520      if field.label == _FieldDescriptor.LABEL_REPEATED:
521        field_copy = field._default_constructor(self)
522        if field.cpp_type == _FieldDescriptor.CPPTYPE_MESSAGE:  # Composite
523          if _IsMapField(field):
524            if _IsMessageMapField(field):
525              for key in field_value:
526                field_copy[key].MergeFrom(field_value[key])
527            else:
528              field_copy.update(field_value)
529          else:
530            for val in field_value:
531              if isinstance(val, dict):
532                field_copy.add(**val)
533              else:
534                field_copy.add().MergeFrom(val)
535        else:  # Scalar
536          if field.cpp_type == _FieldDescriptor.CPPTYPE_ENUM:
537            field_value = [_GetIntegerEnumValue(field.enum_type, val)
538                           for val in field_value]
539          field_copy.extend(field_value)
540        self._fields[field] = field_copy
541      elif field.cpp_type == _FieldDescriptor.CPPTYPE_MESSAGE:
542        field_copy = field._default_constructor(self)
543        new_val = None
544        if isinstance(field_value, message_mod.Message):
545          new_val = field_value
546        elif isinstance(field_value, dict):
547          if field.message_type.full_name == _StructFullTypeName:
548            field_copy.Clear()
549            if len(field_value) == 1 and 'fields' in field_value:
550              try:
551                field_copy.update(field_value)
552              except:
553                # Fall back to init normal message field
554                field_copy.Clear()
555                new_val = field.message_type._concrete_class(**field_value)
556            else:
557              field_copy.update(field_value)
558          else:
559            new_val = field.message_type._concrete_class(**field_value)
560        elif hasattr(field_copy, '_internal_assign'):
561          field_copy._internal_assign(field_value)
562        else:
563          raise TypeError(
564              'Message field {0}.{1} must be initialized with a '
565              'dict or instance of same class, got {2}.'.format(
566                  message_descriptor.name,
567                  field_name,
568                  type(field_value).__name__,
569              )
570          )
571
572        if new_val != None:
573          try:
574            field_copy.MergeFrom(new_val)
575          except TypeError:
576            _ReraiseTypeErrorWithFieldName(message_descriptor.name, field_name)
577        self._fields[field] = field_copy
578      else:
579        if field.cpp_type == _FieldDescriptor.CPPTYPE_ENUM:
580          field_value = _GetIntegerEnumValue(field.enum_type, field_value)
581        try:
582          setattr(self, field_name, field_value)
583        except TypeError:
584          _ReraiseTypeErrorWithFieldName(message_descriptor.name, field_name)
DESCRIPTOR = <google.protobuf.descriptor.Descriptor object>
def MergeFrom(self, msg):
1364  def MergeFrom(self, msg):
1365    if not isinstance(msg, cls):
1366      raise TypeError(
1367          'Parameter to MergeFrom() must be instance of same class: '
1368          'expected %s got %s.' % (_FullyQualifiedClassName(cls),
1369                                   _FullyQualifiedClassName(msg.__class__)))
1370
1371    assert msg is not self
1372    self._Modified()
1373
1374    fields = self._fields
1375
1376    for field, value in msg._fields.items():
1377      if field.label == LABEL_REPEATED:
1378        field_value = fields.get(field)
1379        if field_value is None:
1380          # Construct a new object to represent this field.
1381          field_value = field._default_constructor(self)
1382          fields[field] = field_value
1383        field_value.MergeFrom(value)
1384      elif field.cpp_type == CPPTYPE_MESSAGE:
1385        if value._is_present_in_parent:
1386          field_value = fields.get(field)
1387          if field_value is None:
1388            # Construct a new object to represent this field.
1389            field_value = field._default_constructor(self)
1390            fields[field] = field_value
1391          field_value.MergeFrom(value)
1392      else:
1393        self._fields[field] = value
1394        if field.containing_oneof:
1395          self._UpdateOneofState(field)
1396
1397    if msg._unknown_fields:
1398      if not self._unknown_fields:
1399        self._unknown_fields = []
1400      self._unknown_fields.extend(msg._unknown_fields)

Merges the contents of the specified message into current message.

This method merges the contents of the specified message into the current message. Singular fields that are set in the specified message overwrite the corresponding fields in the current message. Repeated fields are appended. Singular sub-messages and groups are recursively merged.

Arguments:
  • other_msg (Message): A message to merge into the current message.
def Clear(self):
1423def _Clear(self):
1424  # Clear fields.
1425  self._fields = {}
1426  self._unknown_fields = ()
1427
1428  self._oneofs = {}
1429  self._Modified()

Clears all data that was set in the message.

def SetInParent(self):
1489  def Modified(self):
1490    """Sets the _cached_byte_size_dirty bit to true,
1491    and propagates this to our listener iff this was a state change.
1492    """
1493
1494    # Note:  Some callers check _cached_byte_size_dirty before calling
1495    #   _Modified() as an extra optimization.  So, if this method is ever
1496    #   changed such that it does stuff even when _cached_byte_size_dirty is
1497    #   already true, the callers need to be updated.
1498    if not self._cached_byte_size_dirty:
1499      self._cached_byte_size_dirty = True
1500      self._listener_for_children.dirty = True
1501      self._is_present_in_parent = True
1502      self._listener.Modified()

Sets the _cached_byte_size_dirty bit to true, and propagates this to our listener iff this was a state change.

def IsInitialized(self, errors=None):
1265  def IsInitialized(self, errors=None):
1266    """Checks if all required fields of a message are set.
1267
1268    Args:
1269      errors:  A list which, if provided, will be populated with the field
1270               paths of all missing required fields.
1271
1272    Returns:
1273      True iff the specified message has all required fields set.
1274    """
1275
1276    # Performance is critical so we avoid HasField() and ListFields().
1277
1278    for field in required_fields:
1279      if (field not in self._fields or
1280          (field.cpp_type == _FieldDescriptor.CPPTYPE_MESSAGE and
1281           not self._fields[field]._is_present_in_parent)):
1282        if errors is not None:
1283          errors.extend(self.FindInitializationErrors())
1284        return False
1285
1286    for field, value in list(self._fields.items()):  # dict can change size!
1287      if field.cpp_type == _FieldDescriptor.CPPTYPE_MESSAGE:
1288        if field.label == _FieldDescriptor.LABEL_REPEATED:
1289          if (field.message_type._is_map_entry):
1290            continue
1291          for element in value:
1292            if not element.IsInitialized():
1293              if errors is not None:
1294                errors.extend(self.FindInitializationErrors())
1295              return False
1296        elif value._is_present_in_parent and not value.IsInitialized():
1297          if errors is not None:
1298            errors.extend(self.FindInitializationErrors())
1299          return False
1300
1301    return True

Checks if all required fields of a message are set.

Arguments:
  • errors: A list which, if provided, will be populated with the field paths of all missing required fields.
Returns:

True iff the specified message has all required fields set.

def MergeFromString(self, serialized):
1180  def MergeFromString(self, serialized):
1181    serialized = memoryview(serialized)
1182    length = len(serialized)
1183    try:
1184      if self._InternalParse(serialized, 0, length) != length:
1185        # The only reason _InternalParse would return early is if it
1186        # encountered an end-group tag.
1187        raise message_mod.DecodeError('Unexpected end-group tag.')
1188    except (IndexError, TypeError):
1189      # Now ord(buf[p:p+1]) == ord('') gets TypeError.
1190      raise message_mod.DecodeError('Truncated message.')
1191    except struct.error as e:
1192      raise message_mod.DecodeError(e)
1193    return length   # Return this for legacy reasons.

Merges serialized protocol buffer data into this message.

When we find a field in serialized that is already present in this message:

  • If it's a "repeated" field, we append to the end of our list.
  • Else, if it's a scalar, we overwrite our field.
  • Else, (it's a nonrepeated composite), we recursively merge into the existing composite.
Arguments:
  • serialized (bytes): Any object that allows us to call memoryview(serialized) to access a string of bytes using the buffer interface.
Returns:

int: The number of bytes read from serialized. For non-group messages, this will always be len(serialized), but for messages which are actually groups, this will generally be less than len(serialized), since we must stop when we reach an END_GROUP tag. Note that if we do stop because of an END_GROUP tag, the number of bytes returned does not include the bytes for the END_GROUP tag information.

Raises:
  • DecodeError: if the input cannot be parsed.
def SerializeToString(self, **kwargs):
1133  def SerializeToString(self, **kwargs):
1134    # Check if the message has all of its required fields set.
1135    if not self.IsInitialized():
1136      raise message_mod.EncodeError(
1137          'Message %s is missing required fields: %s' % (
1138          self.DESCRIPTOR.full_name, ','.join(self.FindInitializationErrors())))
1139    return self.SerializePartialToString(**kwargs)

Serializes the protocol message to a binary string.

Keyword Args:

deterministic (bool): If true, requests deterministic serialization of the protobuf, with predictable ordering of map keys.

Returns:

A binary string representation of the message if all of the required fields in the message are set (i.e. the message is initialized).

Raises:
def SerializePartialToString(self, **kwargs):
1146  def SerializePartialToString(self, **kwargs):
1147    out = BytesIO()
1148    self._InternalSerialize(out.write, **kwargs)
1149    return out.getvalue()

Serializes the protocol message to a binary string.

This method is similar to SerializeToString but doesn't check if the message is initialized.

Keyword Args:

deterministic (bool): If true, requests deterministic serialization of the protobuf, with predictable ordering of map keys.

Returns:

bytes: A serialized representation of the partial message.

def ListFields(self):
848  def ListFields(self):
849    all_fields = [item for item in self._fields.items() if _IsPresent(item)]
850    all_fields.sort(key = lambda item: item[0].number)
851    return all_fields

Returns a list of (FieldDescriptor, value) tuples for present fields.

A message field is non-empty if HasField() would return true. A singular primitive field is non-empty if HasField() would return true in proto2 or it is non zero in proto3. A repeated field is non-empty if it contains at least one element. The fields are ordered by field number.

Returns:

list[tuple(FieldDescriptor, value)]: field descriptors and values for all fields in the message which are not empty. The values vary by field type.

def HasField(self, field_name):
872  def HasField(self, field_name):
873    try:
874      field = hassable_fields[field_name]
875    except KeyError as exc:
876      raise ValueError('Protocol message %s has no non-repeated field "%s" '
877                       'nor has presence is not available for this field.' % (
878                           message_descriptor.full_name, field_name)) from exc
879
880    if isinstance(field, descriptor_mod.OneofDescriptor):
881      try:
882        return HasField(self, self._oneofs[field].name)
883      except KeyError:
884        return False
885    else:
886      if field.cpp_type == _FieldDescriptor.CPPTYPE_MESSAGE:
887        value = self._fields.get(field)
888        return value is not None and value._is_present_in_parent
889      else:
890        return field in self._fields

Checks if a certain field is set for the message.

For a oneof group, checks if any field inside is set. Note that if the field_name is not defined in the message descriptor, ValueError will be raised.

Arguments:
  • field_name (str): The name of the field to check for presence.
Returns:

bool: Whether a value has been set for the named field.

Raises:
  • ValueError: if the field_name is not a member of this message.
def ClearField(self, field_name):
897  def ClearField(self, field_name):
898    try:
899      field = message_descriptor.fields_by_name[field_name]
900    except KeyError:
901      try:
902        field = message_descriptor.oneofs_by_name[field_name]
903        if field in self._oneofs:
904          field = self._oneofs[field]
905        else:
906          return
907      except KeyError:
908        raise ValueError('Protocol message %s has no "%s" field.' %
909                         (message_descriptor.name, field_name))
910
911    if field in self._fields:
912      # To match the C++ implementation, we need to invalidate iterators
913      # for map fields when ClearField() happens.
914      if hasattr(self._fields[field], 'InvalidateIterators'):
915        self._fields[field].InvalidateIterators()
916
917      # Note:  If the field is a sub-message, its listener will still point
918      #   at us.  That's fine, because the worst than can happen is that it
919      #   will call _Modified() and invalidate our byte size.  Big deal.
920      del self._fields[field]
921
922      if self._oneofs.get(field.containing_oneof, None) is field:
923        del self._oneofs[field.containing_oneof]
924
925    # Always call _Modified() -- even if nothing was changed, this is
926    # a mutating method, and thus calling it should cause the field to become
927    # present in the parent message.
928    self._Modified()

Clears the contents of a given field.

Inside a oneof group, clears the field set. If the name neither refers to a defined field or oneof group, ValueError is raised.

Arguments:
  • field_name (str): The name of the field to check for presence.
Raises:
  • ValueError: if the field_name is not a member of this message.
def WhichOneof(self, oneof_name):
1406  def WhichOneof(self, oneof_name):
1407    """Returns the name of the currently set field inside a oneof, or None."""
1408    try:
1409      field = message_descriptor.oneofs_by_name[oneof_name]
1410    except KeyError:
1411      raise ValueError(
1412          'Protocol message has no oneof "%s" field.' % oneof_name)
1413
1414    nested_field = self._oneofs.get(field, None)
1415    if nested_field is not None and self.HasField(nested_field.name):
1416      return nested_field.name
1417    else:
1418      return None

Returns the name of the currently set field inside a oneof, or None.

def DiscardUnknownFields(self):
1438def _DiscardUnknownFields(self):
1439  self._unknown_fields = []
1440  for field, value in self.ListFields():
1441    if field.cpp_type == _FieldDescriptor.CPPTYPE_MESSAGE:
1442      if _IsMapField(field):
1443        if _IsMessageMapField(field):
1444          for key in value:
1445            value[key].DiscardUnknownFields()
1446      elif field.label == _FieldDescriptor.LABEL_REPEATED:
1447        for sub_message in value:
1448          sub_message.DiscardUnknownFields()
1449      else:
1450        value.DiscardUnknownFields()

Clears all fields in the UnknownFieldSet.

This operation is recursive for nested message.

def ByteSize(self):
1101  def ByteSize(self):
1102    if not self._cached_byte_size_dirty:
1103      return self._cached_byte_size
1104
1105    size = 0
1106    descriptor = self.DESCRIPTOR
1107    if descriptor._is_map_entry:
1108      # Fields of map entry should always be serialized.
1109      key_field = descriptor.fields_by_name['key']
1110      _MaybeAddEncoder(cls, key_field)
1111      size = key_field._sizer(self.key)
1112      value_field = descriptor.fields_by_name['value']
1113      _MaybeAddEncoder(cls, value_field)
1114      size += value_field._sizer(self.value)
1115    else:
1116      for field_descriptor, field_value in self.ListFields():
1117        _MaybeAddEncoder(cls, field_descriptor)
1118        size += field_descriptor._sizer(field_value)
1119      for tag_bytes, value_bytes in self._unknown_fields:
1120        size += len(tag_bytes) + len(value_bytes)
1121
1122    self._cached_byte_size = size
1123    self._cached_byte_size_dirty = False
1124    self._listener_for_children.dirty = False
1125    return size

Returns the serialized size of this message.

Recursively calls ByteSize() on all contained messages.

Returns:

int: The number of bytes required to serialize this message.

def FromString(s):
826  def FromString(s):
827    message = cls()
828    message.MergeFromString(s)
829    return message
TARGET_FIELD_NUMBER = 1
target
767  def getter(self):
768    field_value = self._fields.get(field)
769    if field_value is None:
770      # Construct a new object to represent this field.
771      field_value = field._default_constructor(self)
772
773      # Atomically check if another thread has preempted us and, if not, swap
774      # in the new object we just created.  If someone has preempted us, we
775      # take that object and discard ours.
776      # WARNING:  We are relying on setdefault() being atomic.  This is true
777      #   in CPython but we haven't investigated others.  This warning appears
778      #   in several other locations in this file.
779      field_value = self._fields.setdefault(field, field_value)
780    return field_value

Getter for target.

EXPRS_FIELD_NUMBER = 2
exprs
668  def getter(self):
669    field_value = self._fields.get(field)
670    if field_value is None:
671      # Construct a new object to represent this field.
672      field_value = field._default_constructor(self)
673
674      # Atomically check if another thread has preempted us and, if not, swap
675      # in the new object we just created.  If someone has preempted us, we
676      # take that object and discard ours.
677      # WARNING:  We are relying on setdefault() being atomic.  This is true
678      #   in CPython but we haven't investigated others.  This warning appears
679      #   in several other locations in this file.
680      field_value = self._fields.setdefault(field, field_value)
681    return field_value

Getter for exprs.

def FindInitializationErrors(self):
1305  def FindInitializationErrors(self):
1306    """Finds required fields which are not initialized.
1307
1308    Returns:
1309      A list of strings.  Each string is a path to an uninitialized field from
1310      the top-level message, e.g. "foo.bar[5].baz".
1311    """
1312
1313    errors = []  # simplify things
1314
1315    for field in required_fields:
1316      if not self.HasField(field.name):
1317        errors.append(field.name)
1318
1319    for field, value in self.ListFields():
1320      if field.cpp_type == _FieldDescriptor.CPPTYPE_MESSAGE:
1321        if field.is_extension:
1322          name = '(%s)' % field.full_name
1323        else:
1324          name = field.name
1325
1326        if _IsMapField(field):
1327          if _IsMessageMapField(field):
1328            for key in value:
1329              element = value[key]
1330              prefix = '%s[%s].' % (name, key)
1331              sub_errors = element.FindInitializationErrors()
1332              errors += [prefix + error for error in sub_errors]
1333          else:
1334            # ScalarMaps can't have any initialization errors.
1335            pass
1336        elif field.label == _FieldDescriptor.LABEL_REPEATED:
1337          for i in range(len(value)):
1338            element = value[i]
1339            prefix = '%s[%d].' % (name, i)
1340            sub_errors = element.FindInitializationErrors()
1341            errors += [prefix + error for error in sub_errors]
1342        else:
1343          prefix = name + '.'
1344          sub_errors = value.FindInitializationErrors()
1345          errors += [prefix + error for error in sub_errors]
1346
1347    return errors

Finds required fields which are not initialized.

Returns:

A list of strings. Each string is a path to an uninitialized field from the top-level message, e.g. "foo.bar[5].baz".

class AllDifferentConstraintProto(google.protobuf.message.Message):

Abstract base class for protocol messages.

Protocol message classes are almost always generated by the protocol compiler. These generated types subclass Message and implement the methods shown below.

AllDifferentConstraintProto(**kwargs)
498  def init(self, **kwargs):
499    self._cached_byte_size = 0
500    self._cached_byte_size_dirty = len(kwargs) > 0
501    self._fields = {}
502    # Contains a mapping from oneof field descriptors to the descriptor
503    # of the currently set field in that oneof field.
504    self._oneofs = {}
505
506    # _unknown_fields is () when empty for efficiency, and will be turned into
507    # a list if fields are added.
508    self._unknown_fields = ()
509    self._is_present_in_parent = False
510    self._listener = message_listener_mod.NullMessageListener()
511    self._listener_for_children = _Listener(self)
512    for field_name, field_value in kwargs.items():
513      field = _GetFieldByName(message_descriptor, field_name)
514      if field is None:
515        raise TypeError('%s() got an unexpected keyword argument "%s"' %
516                        (message_descriptor.name, field_name))
517      if field_value is None:
518        # field=None is the same as no field at all.
519        continue
520      if field.label == _FieldDescriptor.LABEL_REPEATED:
521        field_copy = field._default_constructor(self)
522        if field.cpp_type == _FieldDescriptor.CPPTYPE_MESSAGE:  # Composite
523          if _IsMapField(field):
524            if _IsMessageMapField(field):
525              for key in field_value:
526                field_copy[key].MergeFrom(field_value[key])
527            else:
528              field_copy.update(field_value)
529          else:
530            for val in field_value:
531              if isinstance(val, dict):
532                field_copy.add(**val)
533              else:
534                field_copy.add().MergeFrom(val)
535        else:  # Scalar
536          if field.cpp_type == _FieldDescriptor.CPPTYPE_ENUM:
537            field_value = [_GetIntegerEnumValue(field.enum_type, val)
538                           for val in field_value]
539          field_copy.extend(field_value)
540        self._fields[field] = field_copy
541      elif field.cpp_type == _FieldDescriptor.CPPTYPE_MESSAGE:
542        field_copy = field._default_constructor(self)
543        new_val = None
544        if isinstance(field_value, message_mod.Message):
545          new_val = field_value
546        elif isinstance(field_value, dict):
547          if field.message_type.full_name == _StructFullTypeName:
548            field_copy.Clear()
549            if len(field_value) == 1 and 'fields' in field_value:
550              try:
551                field_copy.update(field_value)
552              except:
553                # Fall back to init normal message field
554                field_copy.Clear()
555                new_val = field.message_type._concrete_class(**field_value)
556            else:
557              field_copy.update(field_value)
558          else:
559            new_val = field.message_type._concrete_class(**field_value)
560        elif hasattr(field_copy, '_internal_assign'):
561          field_copy._internal_assign(field_value)
562        else:
563          raise TypeError(
564              'Message field {0}.{1} must be initialized with a '
565              'dict or instance of same class, got {2}.'.format(
566                  message_descriptor.name,
567                  field_name,
568                  type(field_value).__name__,
569              )
570          )
571
572        if new_val != None:
573          try:
574            field_copy.MergeFrom(new_val)
575          except TypeError:
576            _ReraiseTypeErrorWithFieldName(message_descriptor.name, field_name)
577        self._fields[field] = field_copy
578      else:
579        if field.cpp_type == _FieldDescriptor.CPPTYPE_ENUM:
580          field_value = _GetIntegerEnumValue(field.enum_type, field_value)
581        try:
582          setattr(self, field_name, field_value)
583        except TypeError:
584          _ReraiseTypeErrorWithFieldName(message_descriptor.name, field_name)
DESCRIPTOR = <google.protobuf.descriptor.Descriptor object>
def MergeFrom(self, msg):
1364  def MergeFrom(self, msg):
1365    if not isinstance(msg, cls):
1366      raise TypeError(
1367          'Parameter to MergeFrom() must be instance of same class: '
1368          'expected %s got %s.' % (_FullyQualifiedClassName(cls),
1369                                   _FullyQualifiedClassName(msg.__class__)))
1370
1371    assert msg is not self
1372    self._Modified()
1373
1374    fields = self._fields
1375
1376    for field, value in msg._fields.items():
1377      if field.label == LABEL_REPEATED:
1378        field_value = fields.get(field)
1379        if field_value is None:
1380          # Construct a new object to represent this field.
1381          field_value = field._default_constructor(self)
1382          fields[field] = field_value
1383        field_value.MergeFrom(value)
1384      elif field.cpp_type == CPPTYPE_MESSAGE:
1385        if value._is_present_in_parent:
1386          field_value = fields.get(field)
1387          if field_value is None:
1388            # Construct a new object to represent this field.
1389            field_value = field._default_constructor(self)
1390            fields[field] = field_value
1391          field_value.MergeFrom(value)
1392      else:
1393        self._fields[field] = value
1394        if field.containing_oneof:
1395          self._UpdateOneofState(field)
1396
1397    if msg._unknown_fields:
1398      if not self._unknown_fields:
1399        self._unknown_fields = []
1400      self._unknown_fields.extend(msg._unknown_fields)

Merges the contents of the specified message into current message.

This method merges the contents of the specified message into the current message. Singular fields that are set in the specified message overwrite the corresponding fields in the current message. Repeated fields are appended. Singular sub-messages and groups are recursively merged.

Arguments:
  • other_msg (Message): A message to merge into the current message.
def Clear(self):
1423def _Clear(self):
1424  # Clear fields.
1425  self._fields = {}
1426  self._unknown_fields = ()
1427
1428  self._oneofs = {}
1429  self._Modified()

Clears all data that was set in the message.

def SetInParent(self):
1489  def Modified(self):
1490    """Sets the _cached_byte_size_dirty bit to true,
1491    and propagates this to our listener iff this was a state change.
1492    """
1493
1494    # Note:  Some callers check _cached_byte_size_dirty before calling
1495    #   _Modified() as an extra optimization.  So, if this method is ever
1496    #   changed such that it does stuff even when _cached_byte_size_dirty is
1497    #   already true, the callers need to be updated.
1498    if not self._cached_byte_size_dirty:
1499      self._cached_byte_size_dirty = True
1500      self._listener_for_children.dirty = True
1501      self._is_present_in_parent = True
1502      self._listener.Modified()

Sets the _cached_byte_size_dirty bit to true, and propagates this to our listener iff this was a state change.

def IsInitialized(self, errors=None):
1265  def IsInitialized(self, errors=None):
1266    """Checks if all required fields of a message are set.
1267
1268    Args:
1269      errors:  A list which, if provided, will be populated with the field
1270               paths of all missing required fields.
1271
1272    Returns:
1273      True iff the specified message has all required fields set.
1274    """
1275
1276    # Performance is critical so we avoid HasField() and ListFields().
1277
1278    for field in required_fields:
1279      if (field not in self._fields or
1280          (field.cpp_type == _FieldDescriptor.CPPTYPE_MESSAGE and
1281           not self._fields[field]._is_present_in_parent)):
1282        if errors is not None:
1283          errors.extend(self.FindInitializationErrors())
1284        return False
1285
1286    for field, value in list(self._fields.items()):  # dict can change size!
1287      if field.cpp_type == _FieldDescriptor.CPPTYPE_MESSAGE:
1288        if field.label == _FieldDescriptor.LABEL_REPEATED:
1289          if (field.message_type._is_map_entry):
1290            continue
1291          for element in value:
1292            if not element.IsInitialized():
1293              if errors is not None:
1294                errors.extend(self.FindInitializationErrors())
1295              return False
1296        elif value._is_present_in_parent and not value.IsInitialized():
1297          if errors is not None:
1298            errors.extend(self.FindInitializationErrors())
1299          return False
1300
1301    return True

Checks if all required fields of a message are set.

Arguments:
  • errors: A list which, if provided, will be populated with the field paths of all missing required fields.
Returns:

True iff the specified message has all required fields set.

def MergeFromString(self, serialized):
1180  def MergeFromString(self, serialized):
1181    serialized = memoryview(serialized)
1182    length = len(serialized)
1183    try:
1184      if self._InternalParse(serialized, 0, length) != length:
1185        # The only reason _InternalParse would return early is if it
1186        # encountered an end-group tag.
1187        raise message_mod.DecodeError('Unexpected end-group tag.')
1188    except (IndexError, TypeError):
1189      # Now ord(buf[p:p+1]) == ord('') gets TypeError.
1190      raise message_mod.DecodeError('Truncated message.')
1191    except struct.error as e:
1192      raise message_mod.DecodeError(e)
1193    return length   # Return this for legacy reasons.

Merges serialized protocol buffer data into this message.

When we find a field in serialized that is already present in this message:

  • If it's a "repeated" field, we append to the end of our list.
  • Else, if it's a scalar, we overwrite our field.
  • Else, (it's a nonrepeated composite), we recursively merge into the existing composite.
Arguments:
  • serialized (bytes): Any object that allows us to call memoryview(serialized) to access a string of bytes using the buffer interface.
Returns:

int: The number of bytes read from serialized. For non-group messages, this will always be len(serialized), but for messages which are actually groups, this will generally be less than len(serialized), since we must stop when we reach an END_GROUP tag. Note that if we do stop because of an END_GROUP tag, the number of bytes returned does not include the bytes for the END_GROUP tag information.

Raises:
  • DecodeError: if the input cannot be parsed.
def SerializeToString(self, **kwargs):
1133  def SerializeToString(self, **kwargs):
1134    # Check if the message has all of its required fields set.
1135    if not self.IsInitialized():
1136      raise message_mod.EncodeError(
1137          'Message %s is missing required fields: %s' % (
1138          self.DESCRIPTOR.full_name, ','.join(self.FindInitializationErrors())))
1139    return self.SerializePartialToString(**kwargs)

Serializes the protocol message to a binary string.

Keyword Args:

deterministic (bool): If true, requests deterministic serialization of the protobuf, with predictable ordering of map keys.

Returns:

A binary string representation of the message if all of the required fields in the message are set (i.e. the message is initialized).

Raises:
def SerializePartialToString(self, **kwargs):
1146  def SerializePartialToString(self, **kwargs):
1147    out = BytesIO()
1148    self._InternalSerialize(out.write, **kwargs)
1149    return out.getvalue()

Serializes the protocol message to a binary string.

This method is similar to SerializeToString but doesn't check if the message is initialized.

Keyword Args:

deterministic (bool): If true, requests deterministic serialization of the protobuf, with predictable ordering of map keys.

Returns:

bytes: A serialized representation of the partial message.

def ListFields(self):
848  def ListFields(self):
849    all_fields = [item for item in self._fields.items() if _IsPresent(item)]
850    all_fields.sort(key = lambda item: item[0].number)
851    return all_fields

Returns a list of (FieldDescriptor, value) tuples for present fields.

A message field is non-empty if HasField() would return true. A singular primitive field is non-empty if HasField() would return true in proto2 or it is non zero in proto3. A repeated field is non-empty if it contains at least one element. The fields are ordered by field number.

Returns:

list[tuple(FieldDescriptor, value)]: field descriptors and values for all fields in the message which are not empty. The values vary by field type.

def HasField(self, field_name):
872  def HasField(self, field_name):
873    try:
874      field = hassable_fields[field_name]
875    except KeyError as exc:
876      raise ValueError('Protocol message %s has no non-repeated field "%s" '
877                       'nor has presence is not available for this field.' % (
878                           message_descriptor.full_name, field_name)) from exc
879
880    if isinstance(field, descriptor_mod.OneofDescriptor):
881      try:
882        return HasField(self, self._oneofs[field].name)
883      except KeyError:
884        return False
885    else:
886      if field.cpp_type == _FieldDescriptor.CPPTYPE_MESSAGE:
887        value = self._fields.get(field)
888        return value is not None and value._is_present_in_parent
889      else:
890        return field in self._fields

Checks if a certain field is set for the message.

For a oneof group, checks if any field inside is set. Note that if the field_name is not defined in the message descriptor, ValueError will be raised.

Arguments:
  • field_name (str): The name of the field to check for presence.
Returns:

bool: Whether a value has been set for the named field.

Raises:
  • ValueError: if the field_name is not a member of this message.
def ClearField(self, field_name):
897  def ClearField(self, field_name):
898    try:
899      field = message_descriptor.fields_by_name[field_name]
900    except KeyError:
901      try:
902        field = message_descriptor.oneofs_by_name[field_name]
903        if field in self._oneofs:
904          field = self._oneofs[field]
905        else:
906          return
907      except KeyError:
908        raise ValueError('Protocol message %s has no "%s" field.' %
909                         (message_descriptor.name, field_name))
910
911    if field in self._fields:
912      # To match the C++ implementation, we need to invalidate iterators
913      # for map fields when ClearField() happens.
914      if hasattr(self._fields[field], 'InvalidateIterators'):
915        self._fields[field].InvalidateIterators()
916
917      # Note:  If the field is a sub-message, its listener will still point
918      #   at us.  That's fine, because the worst than can happen is that it
919      #   will call _Modified() and invalidate our byte size.  Big deal.
920      del self._fields[field]
921
922      if self._oneofs.get(field.containing_oneof, None) is field:
923        del self._oneofs[field.containing_oneof]
924
925    # Always call _Modified() -- even if nothing was changed, this is
926    # a mutating method, and thus calling it should cause the field to become
927    # present in the parent message.
928    self._Modified()

Clears the contents of a given field.

Inside a oneof group, clears the field set. If the name neither refers to a defined field or oneof group, ValueError is raised.

Arguments:
  • field_name (str): The name of the field to check for presence.
Raises:
  • ValueError: if the field_name is not a member of this message.
def WhichOneof(self, oneof_name):
1406  def WhichOneof(self, oneof_name):
1407    """Returns the name of the currently set field inside a oneof, or None."""
1408    try:
1409      field = message_descriptor.oneofs_by_name[oneof_name]
1410    except KeyError:
1411      raise ValueError(
1412          'Protocol message has no oneof "%s" field.' % oneof_name)
1413
1414    nested_field = self._oneofs.get(field, None)
1415    if nested_field is not None and self.HasField(nested_field.name):
1416      return nested_field.name
1417    else:
1418      return None

Returns the name of the currently set field inside a oneof, or None.

def DiscardUnknownFields(self):
1438def _DiscardUnknownFields(self):
1439  self._unknown_fields = []
1440  for field, value in self.ListFields():
1441    if field.cpp_type == _FieldDescriptor.CPPTYPE_MESSAGE:
1442      if _IsMapField(field):
1443        if _IsMessageMapField(field):
1444          for key in value:
1445            value[key].DiscardUnknownFields()
1446      elif field.label == _FieldDescriptor.LABEL_REPEATED:
1447        for sub_message in value:
1448          sub_message.DiscardUnknownFields()
1449      else:
1450        value.DiscardUnknownFields()

Clears all fields in the UnknownFieldSet.

This operation is recursive for nested message.

def ByteSize(self):
1101  def ByteSize(self):
1102    if not self._cached_byte_size_dirty:
1103      return self._cached_byte_size
1104
1105    size = 0
1106    descriptor = self.DESCRIPTOR
1107    if descriptor._is_map_entry:
1108      # Fields of map entry should always be serialized.
1109      key_field = descriptor.fields_by_name['key']
1110      _MaybeAddEncoder(cls, key_field)
1111      size = key_field._sizer(self.key)
1112      value_field = descriptor.fields_by_name['value']
1113      _MaybeAddEncoder(cls, value_field)
1114      size += value_field._sizer(self.value)
1115    else:
1116      for field_descriptor, field_value in self.ListFields():
1117        _MaybeAddEncoder(cls, field_descriptor)
1118        size += field_descriptor._sizer(field_value)
1119      for tag_bytes, value_bytes in self._unknown_fields:
1120        size += len(tag_bytes) + len(value_bytes)
1121
1122    self._cached_byte_size = size
1123    self._cached_byte_size_dirty = False
1124    self._listener_for_children.dirty = False
1125    return size

Returns the serialized size of this message.

Recursively calls ByteSize() on all contained messages.

Returns:

int: The number of bytes required to serialize this message.

def FromString(s):
826  def FromString(s):
827    message = cls()
828    message.MergeFromString(s)
829    return message
EXPRS_FIELD_NUMBER = 1
exprs
668  def getter(self):
669    field_value = self._fields.get(field)
670    if field_value is None:
671      # Construct a new object to represent this field.
672      field_value = field._default_constructor(self)
673
674      # Atomically check if another thread has preempted us and, if not, swap
675      # in the new object we just created.  If someone has preempted us, we
676      # take that object and discard ours.
677      # WARNING:  We are relying on setdefault() being atomic.  This is true
678      #   in CPython but we haven't investigated others.  This warning appears
679      #   in several other locations in this file.
680      field_value = self._fields.setdefault(field, field_value)
681    return field_value

Getter for exprs.

def FindInitializationErrors(self):
1305  def FindInitializationErrors(self):
1306    """Finds required fields which are not initialized.
1307
1308    Returns:
1309      A list of strings.  Each string is a path to an uninitialized field from
1310      the top-level message, e.g. "foo.bar[5].baz".
1311    """
1312
1313    errors = []  # simplify things
1314
1315    for field in required_fields:
1316      if not self.HasField(field.name):
1317        errors.append(field.name)
1318
1319    for field, value in self.ListFields():
1320      if field.cpp_type == _FieldDescriptor.CPPTYPE_MESSAGE:
1321        if field.is_extension:
1322          name = '(%s)' % field.full_name
1323        else:
1324          name = field.name
1325
1326        if _IsMapField(field):
1327          if _IsMessageMapField(field):
1328            for key in value:
1329              element = value[key]
1330              prefix = '%s[%s].' % (name, key)
1331              sub_errors = element.FindInitializationErrors()
1332              errors += [prefix + error for error in sub_errors]
1333          else:
1334            # ScalarMaps can't have any initialization errors.
1335            pass
1336        elif field.label == _FieldDescriptor.LABEL_REPEATED:
1337          for i in range(len(value)):
1338            element = value[i]
1339            prefix = '%s[%d].' % (name, i)
1340            sub_errors = element.FindInitializationErrors()
1341            errors += [prefix + error for error in sub_errors]
1342        else:
1343          prefix = name + '.'
1344          sub_errors = value.FindInitializationErrors()
1345          errors += [prefix + error for error in sub_errors]
1346
1347    return errors

Finds required fields which are not initialized.

Returns:

A list of strings. Each string is a path to an uninitialized field from the top-level message, e.g. "foo.bar[5].baz".

class LinearConstraintProto(google.protobuf.message.Message):

Abstract base class for protocol messages.

Protocol message classes are almost always generated by the protocol compiler. These generated types subclass Message and implement the methods shown below.

LinearConstraintProto(**kwargs)
498  def init(self, **kwargs):
499    self._cached_byte_size = 0
500    self._cached_byte_size_dirty = len(kwargs) > 0
501    self._fields = {}
502    # Contains a mapping from oneof field descriptors to the descriptor
503    # of the currently set field in that oneof field.
504    self._oneofs = {}
505
506    # _unknown_fields is () when empty for efficiency, and will be turned into
507    # a list if fields are added.
508    self._unknown_fields = ()
509    self._is_present_in_parent = False
510    self._listener = message_listener_mod.NullMessageListener()
511    self._listener_for_children = _Listener(self)
512    for field_name, field_value in kwargs.items():
513      field = _GetFieldByName(message_descriptor, field_name)
514      if field is None:
515        raise TypeError('%s() got an unexpected keyword argument "%s"' %
516                        (message_descriptor.name, field_name))
517      if field_value is None:
518        # field=None is the same as no field at all.
519        continue
520      if field.label == _FieldDescriptor.LABEL_REPEATED:
521        field_copy = field._default_constructor(self)
522        if field.cpp_type == _FieldDescriptor.CPPTYPE_MESSAGE:  # Composite
523          if _IsMapField(field):
524            if _IsMessageMapField(field):
525              for key in field_value:
526                field_copy[key].MergeFrom(field_value[key])
527            else:
528              field_copy.update(field_value)
529          else:
530            for val in field_value:
531              if isinstance(val, dict):
532                field_copy.add(**val)
533              else:
534                field_copy.add().MergeFrom(val)
535        else:  # Scalar
536          if field.cpp_type == _FieldDescriptor.CPPTYPE_ENUM:
537            field_value = [_GetIntegerEnumValue(field.enum_type, val)
538                           for val in field_value]
539          field_copy.extend(field_value)
540        self._fields[field] = field_copy
541      elif field.cpp_type == _FieldDescriptor.CPPTYPE_MESSAGE:
542        field_copy = field._default_constructor(self)
543        new_val = None
544        if isinstance(field_value, message_mod.Message):
545          new_val = field_value
546        elif isinstance(field_value, dict):
547          if field.message_type.full_name == _StructFullTypeName:
548            field_copy.Clear()
549            if len(field_value) == 1 and 'fields' in field_value:
550              try:
551                field_copy.update(field_value)
552              except:
553                # Fall back to init normal message field
554                field_copy.Clear()
555                new_val = field.message_type._concrete_class(**field_value)
556            else:
557              field_copy.update(field_value)
558          else:
559            new_val = field.message_type._concrete_class(**field_value)
560        elif hasattr(field_copy, '_internal_assign'):
561          field_copy._internal_assign(field_value)
562        else:
563          raise TypeError(
564              'Message field {0}.{1} must be initialized with a '
565              'dict or instance of same class, got {2}.'.format(
566                  message_descriptor.name,
567                  field_name,
568                  type(field_value).__name__,
569              )
570          )
571
572        if new_val != None:
573          try:
574            field_copy.MergeFrom(new_val)
575          except TypeError:
576            _ReraiseTypeErrorWithFieldName(message_descriptor.name, field_name)
577        self._fields[field] = field_copy
578      else:
579        if field.cpp_type == _FieldDescriptor.CPPTYPE_ENUM:
580          field_value = _GetIntegerEnumValue(field.enum_type, field_value)
581        try:
582          setattr(self, field_name, field_value)
583        except TypeError:
584          _ReraiseTypeErrorWithFieldName(message_descriptor.name, field_name)
DESCRIPTOR = <google.protobuf.descriptor.Descriptor object>
def MergeFrom(self, msg):
1364  def MergeFrom(self, msg):
1365    if not isinstance(msg, cls):
1366      raise TypeError(
1367          'Parameter to MergeFrom() must be instance of same class: '
1368          'expected %s got %s.' % (_FullyQualifiedClassName(cls),
1369                                   _FullyQualifiedClassName(msg.__class__)))
1370
1371    assert msg is not self
1372    self._Modified()
1373
1374    fields = self._fields
1375
1376    for field, value in msg._fields.items():
1377      if field.label == LABEL_REPEATED:
1378        field_value = fields.get(field)
1379        if field_value is None:
1380          # Construct a new object to represent this field.
1381          field_value = field._default_constructor(self)
1382          fields[field] = field_value
1383        field_value.MergeFrom(value)
1384      elif field.cpp_type == CPPTYPE_MESSAGE:
1385        if value._is_present_in_parent:
1386          field_value = fields.get(field)
1387          if field_value is None:
1388            # Construct a new object to represent this field.
1389            field_value = field._default_constructor(self)
1390            fields[field] = field_value
1391          field_value.MergeFrom(value)
1392      else:
1393        self._fields[field] = value
1394        if field.containing_oneof:
1395          self._UpdateOneofState(field)
1396
1397    if msg._unknown_fields:
1398      if not self._unknown_fields:
1399        self._unknown_fields = []
1400      self._unknown_fields.extend(msg._unknown_fields)

Merges the contents of the specified message into current message.

This method merges the contents of the specified message into the current message. Singular fields that are set in the specified message overwrite the corresponding fields in the current message. Repeated fields are appended. Singular sub-messages and groups are recursively merged.

Arguments:
  • other_msg (Message): A message to merge into the current message.
def Clear(self):
1423def _Clear(self):
1424  # Clear fields.
1425  self._fields = {}
1426  self._unknown_fields = ()
1427
1428  self._oneofs = {}
1429  self._Modified()

Clears all data that was set in the message.

def SetInParent(self):
1489  def Modified(self):
1490    """Sets the _cached_byte_size_dirty bit to true,
1491    and propagates this to our listener iff this was a state change.
1492    """
1493
1494    # Note:  Some callers check _cached_byte_size_dirty before calling
1495    #   _Modified() as an extra optimization.  So, if this method is ever
1496    #   changed such that it does stuff even when _cached_byte_size_dirty is
1497    #   already true, the callers need to be updated.
1498    if not self._cached_byte_size_dirty:
1499      self._cached_byte_size_dirty = True
1500      self._listener_for_children.dirty = True
1501      self._is_present_in_parent = True
1502      self._listener.Modified()

Sets the _cached_byte_size_dirty bit to true, and propagates this to our listener iff this was a state change.

def IsInitialized(self, errors=None):
1265  def IsInitialized(self, errors=None):
1266    """Checks if all required fields of a message are set.
1267
1268    Args:
1269      errors:  A list which, if provided, will be populated with the field
1270               paths of all missing required fields.
1271
1272    Returns:
1273      True iff the specified message has all required fields set.
1274    """
1275
1276    # Performance is critical so we avoid HasField() and ListFields().
1277
1278    for field in required_fields:
1279      if (field not in self._fields or
1280          (field.cpp_type == _FieldDescriptor.CPPTYPE_MESSAGE and
1281           not self._fields[field]._is_present_in_parent)):
1282        if errors is not None:
1283          errors.extend(self.FindInitializationErrors())
1284        return False
1285
1286    for field, value in list(self._fields.items()):  # dict can change size!
1287      if field.cpp_type == _FieldDescriptor.CPPTYPE_MESSAGE:
1288        if field.label == _FieldDescriptor.LABEL_REPEATED:
1289          if (field.message_type._is_map_entry):
1290            continue
1291          for element in value:
1292            if not element.IsInitialized():
1293              if errors is not None:
1294                errors.extend(self.FindInitializationErrors())
1295              return False
1296        elif value._is_present_in_parent and not value.IsInitialized():
1297          if errors is not None:
1298            errors.extend(self.FindInitializationErrors())
1299          return False
1300
1301    return True

Checks if all required fields of a message are set.

Arguments:
  • errors: A list which, if provided, will be populated with the field paths of all missing required fields.
Returns:

True iff the specified message has all required fields set.

def MergeFromString(self, serialized):
1180  def MergeFromString(self, serialized):
1181    serialized = memoryview(serialized)
1182    length = len(serialized)
1183    try:
1184      if self._InternalParse(serialized, 0, length) != length:
1185        # The only reason _InternalParse would return early is if it
1186        # encountered an end-group tag.
1187        raise message_mod.DecodeError('Unexpected end-group tag.')
1188    except (IndexError, TypeError):
1189      # Now ord(buf[p:p+1]) == ord('') gets TypeError.
1190      raise message_mod.DecodeError('Truncated message.')
1191    except struct.error as e:
1192      raise message_mod.DecodeError(e)
1193    return length   # Return this for legacy reasons.

Merges serialized protocol buffer data into this message.

When we find a field in serialized that is already present in this message:

  • If it's a "repeated" field, we append to the end of our list.
  • Else, if it's a scalar, we overwrite our field.
  • Else, (it's a nonrepeated composite), we recursively merge into the existing composite.
Arguments:
  • serialized (bytes): Any object that allows us to call memoryview(serialized) to access a string of bytes using the buffer interface.
Returns:

int: The number of bytes read from serialized. For non-group messages, this will always be len(serialized), but for messages which are actually groups, this will generally be less than len(serialized), since we must stop when we reach an END_GROUP tag. Note that if we do stop because of an END_GROUP tag, the number of bytes returned does not include the bytes for the END_GROUP tag information.

Raises:
  • DecodeError: if the input cannot be parsed.
def SerializeToString(self, **kwargs):
1133  def SerializeToString(self, **kwargs):
1134    # Check if the message has all of its required fields set.
1135    if not self.IsInitialized():
1136      raise message_mod.EncodeError(
1137          'Message %s is missing required fields: %s' % (
1138          self.DESCRIPTOR.full_name, ','.join(self.FindInitializationErrors())))
1139    return self.SerializePartialToString(**kwargs)

Serializes the protocol message to a binary string.

Keyword Args:

deterministic (bool): If true, requests deterministic serialization of the protobuf, with predictable ordering of map keys.

Returns:

A binary string representation of the message if all of the required fields in the message are set (i.e. the message is initialized).

Raises:
def SerializePartialToString(self, **kwargs):
1146  def SerializePartialToString(self, **kwargs):
1147    out = BytesIO()
1148    self._InternalSerialize(out.write, **kwargs)
1149    return out.getvalue()

Serializes the protocol message to a binary string.

This method is similar to SerializeToString but doesn't check if the message is initialized.

Keyword Args:

deterministic (bool): If true, requests deterministic serialization of the protobuf, with predictable ordering of map keys.

Returns:

bytes: A serialized representation of the partial message.

def ListFields(self):
848  def ListFields(self):
849    all_fields = [item for item in self._fields.items() if _IsPresent(item)]
850    all_fields.sort(key = lambda item: item[0].number)
851    return all_fields

Returns a list of (FieldDescriptor, value) tuples for present fields.

A message field is non-empty if HasField() would return true. A singular primitive field is non-empty if HasField() would return true in proto2 or it is non zero in proto3. A repeated field is non-empty if it contains at least one element. The fields are ordered by field number.

Returns:

list[tuple(FieldDescriptor, value)]: field descriptors and values for all fields in the message which are not empty. The values vary by field type.

def HasField(self, field_name):
872  def HasField(self, field_name):
873    try:
874      field = hassable_fields[field_name]
875    except KeyError as exc:
876      raise ValueError('Protocol message %s has no non-repeated field "%s" '
877                       'nor has presence is not available for this field.' % (
878                           message_descriptor.full_name, field_name)) from exc
879
880    if isinstance(field, descriptor_mod.OneofDescriptor):
881      try:
882        return HasField(self, self._oneofs[field].name)
883      except KeyError:
884        return False
885    else:
886      if field.cpp_type == _FieldDescriptor.CPPTYPE_MESSAGE:
887        value = self._fields.get(field)
888        return value is not None and value._is_present_in_parent
889      else:
890        return field in self._fields

Checks if a certain field is set for the message.

For a oneof group, checks if any field inside is set. Note that if the field_name is not defined in the message descriptor, ValueError will be raised.

Arguments:
  • field_name (str): The name of the field to check for presence.
Returns:

bool: Whether a value has been set for the named field.

Raises:
  • ValueError: if the field_name is not a member of this message.
def ClearField(self, field_name):
897  def ClearField(self, field_name):
898    try:
899      field = message_descriptor.fields_by_name[field_name]
900    except KeyError:
901      try:
902        field = message_descriptor.oneofs_by_name[field_name]
903        if field in self._oneofs:
904          field = self._oneofs[field]
905        else:
906          return
907      except KeyError:
908        raise ValueError('Protocol message %s has no "%s" field.' %
909                         (message_descriptor.name, field_name))
910
911    if field in self._fields:
912      # To match the C++ implementation, we need to invalidate iterators
913      # for map fields when ClearField() happens.
914      if hasattr(self._fields[field], 'InvalidateIterators'):
915        self._fields[field].InvalidateIterators()
916
917      # Note:  If the field is a sub-message, its listener will still point
918      #   at us.  That's fine, because the worst than can happen is that it
919      #   will call _Modified() and invalidate our byte size.  Big deal.
920      del self._fields[field]
921
922      if self._oneofs.get(field.containing_oneof, None) is field:
923        del self._oneofs[field.containing_oneof]
924
925    # Always call _Modified() -- even if nothing was changed, this is
926    # a mutating method, and thus calling it should cause the field to become
927    # present in the parent message.
928    self._Modified()

Clears the contents of a given field.

Inside a oneof group, clears the field set. If the name neither refers to a defined field or oneof group, ValueError is raised.

Arguments:
  • field_name (str): The name of the field to check for presence.
Raises:
  • ValueError: if the field_name is not a member of this message.
def WhichOneof(self, oneof_name):
1406  def WhichOneof(self, oneof_name):
1407    """Returns the name of the currently set field inside a oneof, or None."""
1408    try:
1409      field = message_descriptor.oneofs_by_name[oneof_name]
1410    except KeyError:
1411      raise ValueError(
1412          'Protocol message has no oneof "%s" field.' % oneof_name)
1413
1414    nested_field = self._oneofs.get(field, None)
1415    if nested_field is not None and self.HasField(nested_field.name):
1416      return nested_field.name
1417    else:
1418      return None

Returns the name of the currently set field inside a oneof, or None.

def DiscardUnknownFields(self):
1438def _DiscardUnknownFields(self):
1439  self._unknown_fields = []
1440  for field, value in self.ListFields():
1441    if field.cpp_type == _FieldDescriptor.CPPTYPE_MESSAGE:
1442      if _IsMapField(field):
1443        if _IsMessageMapField(field):
1444          for key in value:
1445            value[key].DiscardUnknownFields()
1446      elif field.label == _FieldDescriptor.LABEL_REPEATED:
1447        for sub_message in value:
1448          sub_message.DiscardUnknownFields()
1449      else:
1450        value.DiscardUnknownFields()

Clears all fields in the UnknownFieldSet.

This operation is recursive for nested message.

def ByteSize(self):
1101  def ByteSize(self):
1102    if not self._cached_byte_size_dirty:
1103      return self._cached_byte_size
1104
1105    size = 0
1106    descriptor = self.DESCRIPTOR
1107    if descriptor._is_map_entry:
1108      # Fields of map entry should always be serialized.
1109      key_field = descriptor.fields_by_name['key']
1110      _MaybeAddEncoder(cls, key_field)
1111      size = key_field._sizer(self.key)
1112      value_field = descriptor.fields_by_name['value']
1113      _MaybeAddEncoder(cls, value_field)
1114      size += value_field._sizer(self.value)
1115    else:
1116      for field_descriptor, field_value in self.ListFields():
1117        _MaybeAddEncoder(cls, field_descriptor)
1118        size += field_descriptor._sizer(field_value)
1119      for tag_bytes, value_bytes in self._unknown_fields:
1120        size += len(tag_bytes) + len(value_bytes)
1121
1122    self._cached_byte_size = size
1123    self._cached_byte_size_dirty = False
1124    self._listener_for_children.dirty = False
1125    return size

Returns the serialized size of this message.

Recursively calls ByteSize() on all contained messages.

Returns:

int: The number of bytes required to serialize this message.

def FromString(s):
826  def FromString(s):
827    message = cls()
828    message.MergeFromString(s)
829    return message
VARS_FIELD_NUMBER = 1
vars
668  def getter(self):
669    field_value = self._fields.get(field)
670    if field_value is None:
671      # Construct a new object to represent this field.
672      field_value = field._default_constructor(self)
673
674      # Atomically check if another thread has preempted us and, if not, swap
675      # in the new object we just created.  If someone has preempted us, we
676      # take that object and discard ours.
677      # WARNING:  We are relying on setdefault() being atomic.  This is true
678      #   in CPython but we haven't investigated others.  This warning appears
679      #   in several other locations in this file.
680      field_value = self._fields.setdefault(field, field_value)
681    return field_value

Getter for vars.

COEFFS_FIELD_NUMBER = 2
coeffs
668  def getter(self):
669    field_value = self._fields.get(field)
670    if field_value is None:
671      # Construct a new object to represent this field.
672      field_value = field._default_constructor(self)
673
674      # Atomically check if another thread has preempted us and, if not, swap
675      # in the new object we just created.  If someone has preempted us, we
676      # take that object and discard ours.
677      # WARNING:  We are relying on setdefault() being atomic.  This is true
678      #   in CPython but we haven't investigated others.  This warning appears
679      #   in several other locations in this file.
680      field_value = self._fields.setdefault(field, field_value)
681    return field_value

Getter for coeffs.

DOMAIN_FIELD_NUMBER = 3
domain
668  def getter(self):
669    field_value = self._fields.get(field)
670    if field_value is None:
671      # Construct a new object to represent this field.
672      field_value = field._default_constructor(self)
673
674      # Atomically check if another thread has preempted us and, if not, swap
675      # in the new object we just created.  If someone has preempted us, we
676      # take that object and discard ours.
677      # WARNING:  We are relying on setdefault() being atomic.  This is true
678      #   in CPython but we haven't investigated others.  This warning appears
679      #   in several other locations in this file.
680      field_value = self._fields.setdefault(field, field_value)
681    return field_value

Getter for domain.

def FindInitializationErrors(self):
1305  def FindInitializationErrors(self):
1306    """Finds required fields which are not initialized.
1307
1308    Returns:
1309      A list of strings.  Each string is a path to an uninitialized field from
1310      the top-level message, e.g. "foo.bar[5].baz".
1311    """
1312
1313    errors = []  # simplify things
1314
1315    for field in required_fields:
1316      if not self.HasField(field.name):
1317        errors.append(field.name)
1318
1319    for field, value in self.ListFields():
1320      if field.cpp_type == _FieldDescriptor.CPPTYPE_MESSAGE:
1321        if field.is_extension:
1322          name = '(%s)' % field.full_name
1323        else:
1324          name = field.name
1325
1326        if _IsMapField(field):
1327          if _IsMessageMapField(field):
1328            for key in value:
1329              element = value[key]
1330              prefix = '%s[%s].' % (name, key)
1331              sub_errors = element.FindInitializationErrors()
1332              errors += [prefix + error for error in sub_errors]
1333          else:
1334            # ScalarMaps can't have any initialization errors.
1335            pass
1336        elif field.label == _FieldDescriptor.LABEL_REPEATED:
1337          for i in range(len(value)):
1338            element = value[i]
1339            prefix = '%s[%d].' % (name, i)
1340            sub_errors = element.FindInitializationErrors()
1341            errors += [prefix + error for error in sub_errors]
1342        else:
1343          prefix = name + '.'
1344          sub_errors = value.FindInitializationErrors()
1345          errors += [prefix + error for error in sub_errors]
1346
1347    return errors

Finds required fields which are not initialized.

Returns:

A list of strings. Each string is a path to an uninitialized field from the top-level message, e.g. "foo.bar[5].baz".

class ElementConstraintProto(google.protobuf.message.Message):

Abstract base class for protocol messages.

Protocol message classes are almost always generated by the protocol compiler. These generated types subclass Message and implement the methods shown below.

ElementConstraintProto(**kwargs)
498  def init(self, **kwargs):
499    self._cached_byte_size = 0
500    self._cached_byte_size_dirty = len(kwargs) > 0
501    self._fields = {}
502    # Contains a mapping from oneof field descriptors to the descriptor
503    # of the currently set field in that oneof field.
504    self._oneofs = {}
505
506    # _unknown_fields is () when empty for efficiency, and will be turned into
507    # a list if fields are added.
508    self._unknown_fields = ()
509    self._is_present_in_parent = False
510    self._listener = message_listener_mod.NullMessageListener()
511    self._listener_for_children = _Listener(self)
512    for field_name, field_value in kwargs.items():
513      field = _GetFieldByName(message_descriptor, field_name)
514      if field is None:
515        raise TypeError('%s() got an unexpected keyword argument "%s"' %
516                        (message_descriptor.name, field_name))
517      if field_value is None:
518        # field=None is the same as no field at all.
519        continue
520      if field.label == _FieldDescriptor.LABEL_REPEATED:
521        field_copy = field._default_constructor(self)
522        if field.cpp_type == _FieldDescriptor.CPPTYPE_MESSAGE:  # Composite
523          if _IsMapField(field):
524            if _IsMessageMapField(field):
525              for key in field_value:
526                field_copy[key].MergeFrom(field_value[key])
527            else:
528              field_copy.update(field_value)
529          else:
530            for val in field_value:
531              if isinstance(val, dict):
532                field_copy.add(**val)
533              else:
534                field_copy.add().MergeFrom(val)
535        else:  # Scalar
536          if field.cpp_type == _FieldDescriptor.CPPTYPE_ENUM:
537            field_value = [_GetIntegerEnumValue(field.enum_type, val)
538                           for val in field_value]
539          field_copy.extend(field_value)
540        self._fields[field] = field_copy
541      elif field.cpp_type == _FieldDescriptor.CPPTYPE_MESSAGE:
542        field_copy = field._default_constructor(self)
543        new_val = None
544        if isinstance(field_value, message_mod.Message):
545          new_val = field_value
546        elif isinstance(field_value, dict):
547          if field.message_type.full_name == _StructFullTypeName:
548            field_copy.Clear()
549            if len(field_value) == 1 and 'fields' in field_value:
550              try:
551                field_copy.update(field_value)
552              except:
553                # Fall back to init normal message field
554                field_copy.Clear()
555                new_val = field.message_type._concrete_class(**field_value)
556            else:
557              field_copy.update(field_value)
558          else:
559            new_val = field.message_type._concrete_class(**field_value)
560        elif hasattr(field_copy, '_internal_assign'):
561          field_copy._internal_assign(field_value)
562        else:
563          raise TypeError(
564              'Message field {0}.{1} must be initialized with a '
565              'dict or instance of same class, got {2}.'.format(
566                  message_descriptor.name,
567                  field_name,
568                  type(field_value).__name__,
569              )
570          )
571
572        if new_val != None:
573          try:
574            field_copy.MergeFrom(new_val)
575          except TypeError:
576            _ReraiseTypeErrorWithFieldName(message_descriptor.name, field_name)
577        self._fields[field] = field_copy
578      else:
579        if field.cpp_type == _FieldDescriptor.CPPTYPE_ENUM:
580          field_value = _GetIntegerEnumValue(field.enum_type, field_value)
581        try:
582          setattr(self, field_name, field_value)
583        except TypeError:
584          _ReraiseTypeErrorWithFieldName(message_descriptor.name, field_name)
DESCRIPTOR = <google.protobuf.descriptor.Descriptor object>
def MergeFrom(self, msg):
1364  def MergeFrom(self, msg):
1365    if not isinstance(msg, cls):
1366      raise TypeError(
1367          'Parameter to MergeFrom() must be instance of same class: '
1368          'expected %s got %s.' % (_FullyQualifiedClassName(cls),
1369                                   _FullyQualifiedClassName(msg.__class__)))
1370
1371    assert msg is not self
1372    self._Modified()
1373
1374    fields = self._fields
1375
1376    for field, value in msg._fields.items():
1377      if field.label == LABEL_REPEATED:
1378        field_value = fields.get(field)
1379        if field_value is None:
1380          # Construct a new object to represent this field.
1381          field_value = field._default_constructor(self)
1382          fields[field] = field_value
1383        field_value.MergeFrom(value)
1384      elif field.cpp_type == CPPTYPE_MESSAGE:
1385        if value._is_present_in_parent:
1386          field_value = fields.get(field)
1387          if field_value is None:
1388            # Construct a new object to represent this field.
1389            field_value = field._default_constructor(self)
1390            fields[field] = field_value
1391          field_value.MergeFrom(value)
1392      else:
1393        self._fields[field] = value
1394        if field.containing_oneof:
1395          self._UpdateOneofState(field)
1396
1397    if msg._unknown_fields:
1398      if not self._unknown_fields:
1399        self._unknown_fields = []
1400      self._unknown_fields.extend(msg._unknown_fields)

Merges the contents of the specified message into current message.

This method merges the contents of the specified message into the current message. Singular fields that are set in the specified message overwrite the corresponding fields in the current message. Repeated fields are appended. Singular sub-messages and groups are recursively merged.

Arguments:
  • other_msg (Message): A message to merge into the current message.
def Clear(self):
1423def _Clear(self):
1424  # Clear fields.
1425  self._fields = {}
1426  self._unknown_fields = ()
1427
1428  self._oneofs = {}
1429  self._Modified()

Clears all data that was set in the message.

def SetInParent(self):
1489  def Modified(self):
1490    """Sets the _cached_byte_size_dirty bit to true,
1491    and propagates this to our listener iff this was a state change.
1492    """
1493
1494    # Note:  Some callers check _cached_byte_size_dirty before calling
1495    #   _Modified() as an extra optimization.  So, if this method is ever
1496    #   changed such that it does stuff even when _cached_byte_size_dirty is
1497    #   already true, the callers need to be updated.
1498    if not self._cached_byte_size_dirty:
1499      self._cached_byte_size_dirty = True
1500      self._listener_for_children.dirty = True
1501      self._is_present_in_parent = True
1502      self._listener.Modified()

Sets the _cached_byte_size_dirty bit to true, and propagates this to our listener iff this was a state change.

def IsInitialized(self, errors=None):
1265  def IsInitialized(self, errors=None):
1266    """Checks if all required fields of a message are set.
1267
1268    Args:
1269      errors:  A list which, if provided, will be populated with the field
1270               paths of all missing required fields.
1271
1272    Returns:
1273      True iff the specified message has all required fields set.
1274    """
1275
1276    # Performance is critical so we avoid HasField() and ListFields().
1277
1278    for field in required_fields:
1279      if (field not in self._fields or
1280          (field.cpp_type == _FieldDescriptor.CPPTYPE_MESSAGE and
1281           not self._fields[field]._is_present_in_parent)):
1282        if errors is not None:
1283          errors.extend(self.FindInitializationErrors())
1284        return False
1285
1286    for field, value in list(self._fields.items()):  # dict can change size!
1287      if field.cpp_type == _FieldDescriptor.CPPTYPE_MESSAGE:
1288        if field.label == _FieldDescriptor.LABEL_REPEATED:
1289          if (field.message_type._is_map_entry):
1290            continue
1291          for element in value:
1292            if not element.IsInitialized():
1293              if errors is not None:
1294                errors.extend(self.FindInitializationErrors())
1295              return False
1296        elif value._is_present_in_parent and not value.IsInitialized():
1297          if errors is not None:
1298            errors.extend(self.FindInitializationErrors())
1299          return False
1300
1301    return True

Checks if all required fields of a message are set.

Arguments:
  • errors: A list which, if provided, will be populated with the field paths of all missing required fields.
Returns:

True iff the specified message has all required fields set.

def MergeFromString(self, serialized):
1180  def MergeFromString(self, serialized):
1181    serialized = memoryview(serialized)
1182    length = len(serialized)
1183    try:
1184      if self._InternalParse(serialized, 0, length) != length:
1185        # The only reason _InternalParse would return early is if it
1186        # encountered an end-group tag.
1187        raise message_mod.DecodeError('Unexpected end-group tag.')
1188    except (IndexError, TypeError):
1189      # Now ord(buf[p:p+1]) == ord('') gets TypeError.
1190      raise message_mod.DecodeError('Truncated message.')
1191    except struct.error as e:
1192      raise message_mod.DecodeError(e)
1193    return length   # Return this for legacy reasons.

Merges serialized protocol buffer data into this message.

When we find a field in serialized that is already present in this message:

  • If it's a "repeated" field, we append to the end of our list.
  • Else, if it's a scalar, we overwrite our field.
  • Else, (it's a nonrepeated composite), we recursively merge into the existing composite.
Arguments:
  • serialized (bytes): Any object that allows us to call memoryview(serialized) to access a string of bytes using the buffer interface.
Returns:

int: The number of bytes read from serialized. For non-group messages, this will always be len(serialized), but for messages which are actually groups, this will generally be less than len(serialized), since we must stop when we reach an END_GROUP tag. Note that if we do stop because of an END_GROUP tag, the number of bytes returned does not include the bytes for the END_GROUP tag information.

Raises:
  • DecodeError: if the input cannot be parsed.
def SerializeToString(self, **kwargs):
1133  def SerializeToString(self, **kwargs):
1134    # Check if the message has all of its required fields set.
1135    if not self.IsInitialized():
1136      raise message_mod.EncodeError(
1137          'Message %s is missing required fields: %s' % (
1138          self.DESCRIPTOR.full_name, ','.join(self.FindInitializationErrors())))
1139    return self.SerializePartialToString(**kwargs)

Serializes the protocol message to a binary string.

Keyword Args:

deterministic (bool): If true, requests deterministic serialization of the protobuf, with predictable ordering of map keys.

Returns:

A binary string representation of the message if all of the required fields in the message are set (i.e. the message is initialized).

Raises:
def SerializePartialToString(self, **kwargs):
1146  def SerializePartialToString(self, **kwargs):
1147    out = BytesIO()
1148    self._InternalSerialize(out.write, **kwargs)
1149    return out.getvalue()

Serializes the protocol message to a binary string.

This method is similar to SerializeToString but doesn't check if the message is initialized.

Keyword Args:

deterministic (bool): If true, requests deterministic serialization of the protobuf, with predictable ordering of map keys.

Returns:

bytes: A serialized representation of the partial message.

def ListFields(self):
848  def ListFields(self):
849    all_fields = [item for item in self._fields.items() if _IsPresent(item)]
850    all_fields.sort(key = lambda item: item[0].number)
851    return all_fields

Returns a list of (FieldDescriptor, value) tuples for present fields.

A message field is non-empty if HasField() would return true. A singular primitive field is non-empty if HasField() would return true in proto2 or it is non zero in proto3. A repeated field is non-empty if it contains at least one element. The fields are ordered by field number.

Returns:

list[tuple(FieldDescriptor, value)]: field descriptors and values for all fields in the message which are not empty. The values vary by field type.

def HasField(self, field_name):
872  def HasField(self, field_name):
873    try:
874      field = hassable_fields[field_name]
875    except KeyError as exc:
876      raise ValueError('Protocol message %s has no non-repeated field "%s" '
877                       'nor has presence is not available for this field.' % (
878                           message_descriptor.full_name, field_name)) from exc
879
880    if isinstance(field, descriptor_mod.OneofDescriptor):
881      try:
882        return HasField(self, self._oneofs[field].name)
883      except KeyError:
884        return False
885    else:
886      if field.cpp_type == _FieldDescriptor.CPPTYPE_MESSAGE:
887        value = self._fields.get(field)
888        return value is not None and value._is_present_in_parent
889      else:
890        return field in self._fields

Checks if a certain field is set for the message.

For a oneof group, checks if any field inside is set. Note that if the field_name is not defined in the message descriptor, ValueError will be raised.

Arguments:
  • field_name (str): The name of the field to check for presence.
Returns:

bool: Whether a value has been set for the named field.

Raises:
  • ValueError: if the field_name is not a member of this message.
def ClearField(self, field_name):
897  def ClearField(self, field_name):
898    try:
899      field = message_descriptor.fields_by_name[field_name]
900    except KeyError:
901      try:
902        field = message_descriptor.oneofs_by_name[field_name]
903        if field in self._oneofs:
904          field = self._oneofs[field]
905        else:
906          return
907      except KeyError:
908        raise ValueError('Protocol message %s has no "%s" field.' %
909                         (message_descriptor.name, field_name))
910
911    if field in self._fields:
912      # To match the C++ implementation, we need to invalidate iterators
913      # for map fields when ClearField() happens.
914      if hasattr(self._fields[field], 'InvalidateIterators'):
915        self._fields[field].InvalidateIterators()
916
917      # Note:  If the field is a sub-message, its listener will still point
918      #   at us.  That's fine, because the worst than can happen is that it
919      #   will call _Modified() and invalidate our byte size.  Big deal.
920      del self._fields[field]
921
922      if self._oneofs.get(field.containing_oneof, None) is field:
923        del self._oneofs[field.containing_oneof]
924
925    # Always call _Modified() -- even if nothing was changed, this is
926    # a mutating method, and thus calling it should cause the field to become
927    # present in the parent message.
928    self._Modified()

Clears the contents of a given field.

Inside a oneof group, clears the field set. If the name neither refers to a defined field or oneof group, ValueError is raised.

Arguments:
  • field_name (str): The name of the field to check for presence.
Raises:
  • ValueError: if the field_name is not a member of this message.
def WhichOneof(self, oneof_name):
1406  def WhichOneof(self, oneof_name):
1407    """Returns the name of the currently set field inside a oneof, or None."""
1408    try:
1409      field = message_descriptor.oneofs_by_name[oneof_name]
1410    except KeyError:
1411      raise ValueError(
1412          'Protocol message has no oneof "%s" field.' % oneof_name)
1413
1414    nested_field = self._oneofs.get(field, None)
1415    if nested_field is not None and self.HasField(nested_field.name):
1416      return nested_field.name
1417    else:
1418      return None

Returns the name of the currently set field inside a oneof, or None.

def DiscardUnknownFields(self):
1438def _DiscardUnknownFields(self):
1439  self._unknown_fields = []
1440  for field, value in self.ListFields():
1441    if field.cpp_type == _FieldDescriptor.CPPTYPE_MESSAGE:
1442      if _IsMapField(field):
1443        if _IsMessageMapField(field):
1444          for key in value:
1445            value[key].DiscardUnknownFields()
1446      elif field.label == _FieldDescriptor.LABEL_REPEATED:
1447        for sub_message in value:
1448          sub_message.DiscardUnknownFields()
1449      else:
1450        value.DiscardUnknownFields()

Clears all fields in the UnknownFieldSet.

This operation is recursive for nested message.

def ByteSize(self):
1101  def ByteSize(self):
1102    if not self._cached_byte_size_dirty:
1103      return self._cached_byte_size
1104
1105    size = 0
1106    descriptor = self.DESCRIPTOR
1107    if descriptor._is_map_entry:
1108      # Fields of map entry should always be serialized.
1109      key_field = descriptor.fields_by_name['key']
1110      _MaybeAddEncoder(cls, key_field)
1111      size = key_field._sizer(self.key)
1112      value_field = descriptor.fields_by_name['value']
1113      _MaybeAddEncoder(cls, value_field)
1114      size += value_field._sizer(self.value)
1115    else:
1116      for field_descriptor, field_value in self.ListFields():
1117        _MaybeAddEncoder(cls, field_descriptor)
1118        size += field_descriptor._sizer(field_value)
1119      for tag_bytes, value_bytes in self._unknown_fields:
1120        size += len(tag_bytes) + len(value_bytes)
1121
1122    self._cached_byte_size = size
1123    self._cached_byte_size_dirty = False
1124    self._listener_for_children.dirty = False
1125    return size

Returns the serialized size of this message.

Recursively calls ByteSize() on all contained messages.

Returns:

int: The number of bytes required to serialize this message.

def FromString(s):
826  def FromString(s):
827    message = cls()
828    message.MergeFromString(s)
829    return message
INDEX_FIELD_NUMBER = 1
index
711  def getter(self):
712    # TODO: This may be broken since there may not be
713    # default_value.  Combine with has_default_value somehow.
714    return self._fields.get(field, default_value)

Getter for index.

TARGET_FIELD_NUMBER = 2
target
711  def getter(self):
712    # TODO: This may be broken since there may not be
713    # default_value.  Combine with has_default_value somehow.
714    return self._fields.get(field, default_value)

Getter for target.

VARS_FIELD_NUMBER = 3
vars
668  def getter(self):
669    field_value = self._fields.get(field)
670    if field_value is None:
671      # Construct a new object to represent this field.
672      field_value = field._default_constructor(self)
673
674      # Atomically check if another thread has preempted us and, if not, swap
675      # in the new object we just created.  If someone has preempted us, we
676      # take that object and discard ours.
677      # WARNING:  We are relying on setdefault() being atomic.  This is true
678      #   in CPython but we haven't investigated others.  This warning appears
679      #   in several other locations in this file.
680      field_value = self._fields.setdefault(field, field_value)
681    return field_value

Getter for vars.

LINEAR_INDEX_FIELD_NUMBER = 4
linear_index
767  def getter(self):
768    field_value = self._fields.get(field)
769    if field_value is None:
770      # Construct a new object to represent this field.
771      field_value = field._default_constructor(self)
772
773      # Atomically check if another thread has preempted us and, if not, swap
774      # in the new object we just created.  If someone has preempted us, we
775      # take that object and discard ours.
776      # WARNING:  We are relying on setdefault() being atomic.  This is true
777      #   in CPython but we haven't investigated others.  This warning appears
778      #   in several other locations in this file.
779      field_value = self._fields.setdefault(field, field_value)
780    return field_value

Getter for linear_index.

LINEAR_TARGET_FIELD_NUMBER = 5
linear_target
767  def getter(self):
768    field_value = self._fields.get(field)
769    if field_value is None:
770      # Construct a new object to represent this field.
771      field_value = field._default_constructor(self)
772
773      # Atomically check if another thread has preempted us and, if not, swap
774      # in the new object we just created.  If someone has preempted us, we
775      # take that object and discard ours.
776      # WARNING:  We are relying on setdefault() being atomic.  This is true
777      #   in CPython but we haven't investigated others.  This warning appears
778      #   in several other locations in this file.
779      field_value = self._fields.setdefault(field, field_value)
780    return field_value

Getter for linear_target.

EXPRS_FIELD_NUMBER = 6
exprs
668  def getter(self):
669    field_value = self._fields.get(field)
670    if field_value is None:
671      # Construct a new object to represent this field.
672      field_value = field._default_constructor(self)
673
674      # Atomically check if another thread has preempted us and, if not, swap
675      # in the new object we just created.  If someone has preempted us, we
676      # take that object and discard ours.
677      # WARNING:  We are relying on setdefault() being atomic.  This is true
678      #   in CPython but we haven't investigated others.  This warning appears
679      #   in several other locations in this file.
680      field_value = self._fields.setdefault(field, field_value)
681    return field_value

Getter for exprs.

def FindInitializationErrors(self):
1305  def FindInitializationErrors(self):
1306    """Finds required fields which are not initialized.
1307
1308    Returns:
1309      A list of strings.  Each string is a path to an uninitialized field from
1310      the top-level message, e.g. "foo.bar[5].baz".
1311    """
1312
1313    errors = []  # simplify things
1314
1315    for field in required_fields:
1316      if not self.HasField(field.name):
1317        errors.append(field.name)
1318
1319    for field, value in self.ListFields():
1320      if field.cpp_type == _FieldDescriptor.CPPTYPE_MESSAGE:
1321        if field.is_extension:
1322          name = '(%s)' % field.full_name
1323        else:
1324          name = field.name
1325
1326        if _IsMapField(field):
1327          if _IsMessageMapField(field):
1328            for key in value:
1329              element = value[key]
1330              prefix = '%s[%s].' % (name, key)
1331              sub_errors = element.FindInitializationErrors()
1332              errors += [prefix + error for error in sub_errors]
1333          else:
1334            # ScalarMaps can't have any initialization errors.
1335            pass
1336        elif field.label == _FieldDescriptor.LABEL_REPEATED:
1337          for i in range(len(value)):
1338            element = value[i]
1339            prefix = '%s[%d].' % (name, i)
1340            sub_errors = element.FindInitializationErrors()
1341            errors += [prefix + error for error in sub_errors]
1342        else:
1343          prefix = name + '.'
1344          sub_errors = value.FindInitializationErrors()
1345          errors += [prefix + error for error in sub_errors]
1346
1347    return errors

Finds required fields which are not initialized.

Returns:

A list of strings. Each string is a path to an uninitialized field from the top-level message, e.g. "foo.bar[5].baz".

class IntervalConstraintProto(google.protobuf.message.Message):

Abstract base class for protocol messages.

Protocol message classes are almost always generated by the protocol compiler. These generated types subclass Message and implement the methods shown below.

IntervalConstraintProto(**kwargs)
498  def init(self, **kwargs):
499    self._cached_byte_size = 0
500    self._cached_byte_size_dirty = len(kwargs) > 0
501    self._fields = {}
502    # Contains a mapping from oneof field descriptors to the descriptor
503    # of the currently set field in that oneof field.
504    self._oneofs = {}
505
506    # _unknown_fields is () when empty for efficiency, and will be turned into
507    # a list if fields are added.
508    self._unknown_fields = ()
509    self._is_present_in_parent = False
510    self._listener = message_listener_mod.NullMessageListener()
511    self._listener_for_children = _Listener(self)
512    for field_name, field_value in kwargs.items():
513      field = _GetFieldByName(message_descriptor, field_name)
514      if field is None:
515        raise TypeError('%s() got an unexpected keyword argument "%s"' %
516                        (message_descriptor.name, field_name))
517      if field_value is None:
518        # field=None is the same as no field at all.
519        continue
520      if field.label == _FieldDescriptor.LABEL_REPEATED:
521        field_copy = field._default_constructor(self)
522        if field.cpp_type == _FieldDescriptor.CPPTYPE_MESSAGE:  # Composite
523          if _IsMapField(field):
524            if _IsMessageMapField(field):
525              for key in field_value:
526                field_copy[key].MergeFrom(field_value[key])
527            else:
528              field_copy.update(field_value)
529          else:
530            for val in field_value:
531              if isinstance(val, dict):
532                field_copy.add(**val)
533              else:
534                field_copy.add().MergeFrom(val)
535        else:  # Scalar
536          if field.cpp_type == _FieldDescriptor.CPPTYPE_ENUM:
537            field_value = [_GetIntegerEnumValue(field.enum_type, val)
538                           for val in field_value]
539          field_copy.extend(field_value)
540        self._fields[field] = field_copy
541      elif field.cpp_type == _FieldDescriptor.CPPTYPE_MESSAGE:
542        field_copy = field._default_constructor(self)
543        new_val = None
544        if isinstance(field_value, message_mod.Message):
545          new_val = field_value
546        elif isinstance(field_value, dict):
547          if field.message_type.full_name == _StructFullTypeName:
548            field_copy.Clear()
549            if len(field_value) == 1 and 'fields' in field_value:
550              try:
551                field_copy.update(field_value)
552              except:
553                # Fall back to init normal message field
554                field_copy.Clear()
555                new_val = field.message_type._concrete_class(**field_value)
556            else:
557              field_copy.update(field_value)
558          else:
559            new_val = field.message_type._concrete_class(**field_value)
560        elif hasattr(field_copy, '_internal_assign'):
561          field_copy._internal_assign(field_value)
562        else:
563          raise TypeError(
564              'Message field {0}.{1} must be initialized with a '
565              'dict or instance of same class, got {2}.'.format(
566                  message_descriptor.name,
567                  field_name,
568                  type(field_value).__name__,
569              )
570          )
571
572        if new_val != None:
573          try:
574            field_copy.MergeFrom(new_val)
575          except TypeError:
576            _ReraiseTypeErrorWithFieldName(message_descriptor.name, field_name)
577        self._fields[field] = field_copy
578      else:
579        if field.cpp_type == _FieldDescriptor.CPPTYPE_ENUM:
580          field_value = _GetIntegerEnumValue(field.enum_type, field_value)
581        try:
582          setattr(self, field_name, field_value)
583        except TypeError:
584          _ReraiseTypeErrorWithFieldName(message_descriptor.name, field_name)
DESCRIPTOR = <google.protobuf.descriptor.Descriptor object>
def MergeFrom(self, msg):
1364  def MergeFrom(self, msg):
1365    if not isinstance(msg, cls):
1366      raise TypeError(
1367          'Parameter to MergeFrom() must be instance of same class: '
1368          'expected %s got %s.' % (_FullyQualifiedClassName(cls),
1369                                   _FullyQualifiedClassName(msg.__class__)))
1370
1371    assert msg is not self
1372    self._Modified()
1373
1374    fields = self._fields
1375
1376    for field, value in msg._fields.items():
1377      if field.label == LABEL_REPEATED:
1378        field_value = fields.get(field)
1379        if field_value is None:
1380          # Construct a new object to represent this field.
1381          field_value = field._default_constructor(self)
1382          fields[field] = field_value
1383        field_value.MergeFrom(value)
1384      elif field.cpp_type == CPPTYPE_MESSAGE:
1385        if value._is_present_in_parent:
1386          field_value = fields.get(field)
1387          if field_value is None:
1388            # Construct a new object to represent this field.
1389            field_value = field._default_constructor(self)
1390            fields[field] = field_value
1391          field_value.MergeFrom(value)
1392      else:
1393        self._fields[field] = value
1394        if field.containing_oneof:
1395          self._UpdateOneofState(field)
1396
1397    if msg._unknown_fields:
1398      if not self._unknown_fields:
1399        self._unknown_fields = []
1400      self._unknown_fields.extend(msg._unknown_fields)

Merges the contents of the specified message into current message.

This method merges the contents of the specified message into the current message. Singular fields that are set in the specified message overwrite the corresponding fields in the current message. Repeated fields are appended. Singular sub-messages and groups are recursively merged.

Arguments:
  • other_msg (Message): A message to merge into the current message.
def Clear(self):
1423def _Clear(self):
1424  # Clear fields.
1425  self._fields = {}
1426  self._unknown_fields = ()
1427
1428  self._oneofs = {}
1429  self._Modified()

Clears all data that was set in the message.

def SetInParent(self):
1489  def Modified(self):
1490    """Sets the _cached_byte_size_dirty bit to true,
1491    and propagates this to our listener iff this was a state change.
1492    """
1493
1494    # Note:  Some callers check _cached_byte_size_dirty before calling
1495    #   _Modified() as an extra optimization.  So, if this method is ever
1496    #   changed such that it does stuff even when _cached_byte_size_dirty is
1497    #   already true, the callers need to be updated.
1498    if not self._cached_byte_size_dirty:
1499      self._cached_byte_size_dirty = True
1500      self._listener_for_children.dirty = True
1501      self._is_present_in_parent = True
1502      self._listener.Modified()

Sets the _cached_byte_size_dirty bit to true, and propagates this to our listener iff this was a state change.

def IsInitialized(self, errors=None):
1265  def IsInitialized(self, errors=None):
1266    """Checks if all required fields of a message are set.
1267
1268    Args:
1269      errors:  A list which, if provided, will be populated with the field
1270               paths of all missing required fields.
1271
1272    Returns:
1273      True iff the specified message has all required fields set.
1274    """
1275
1276    # Performance is critical so we avoid HasField() and ListFields().
1277
1278    for field in required_fields:
1279      if (field not in self._fields or
1280          (field.cpp_type == _FieldDescriptor.CPPTYPE_MESSAGE and
1281           not self._fields[field]._is_present_in_parent)):
1282        if errors is not None:
1283          errors.extend(self.FindInitializationErrors())
1284        return False
1285
1286    for field, value in list(self._fields.items()):  # dict can change size!
1287      if field.cpp_type == _FieldDescriptor.CPPTYPE_MESSAGE:
1288        if field.label == _FieldDescriptor.LABEL_REPEATED:
1289          if (field.message_type._is_map_entry):
1290            continue
1291          for element in value:
1292            if not element.IsInitialized():
1293              if errors is not None:
1294                errors.extend(self.FindInitializationErrors())
1295              return False
1296        elif value._is_present_in_parent and not value.IsInitialized():
1297          if errors is not None:
1298            errors.extend(self.FindInitializationErrors())
1299          return False
1300
1301    return True

Checks if all required fields of a message are set.

Arguments:
  • errors: A list which, if provided, will be populated with the field paths of all missing required fields.
Returns:

True iff the specified message has all required fields set.

def MergeFromString(self, serialized):
1180  def MergeFromString(self, serialized):
1181    serialized = memoryview(serialized)
1182    length = len(serialized)
1183    try:
1184      if self._InternalParse(serialized, 0, length) != length:
1185        # The only reason _InternalParse would return early is if it
1186        # encountered an end-group tag.
1187        raise message_mod.DecodeError('Unexpected end-group tag.')
1188    except (IndexError, TypeError):
1189      # Now ord(buf[p:p+1]) == ord('') gets TypeError.
1190      raise message_mod.DecodeError('Truncated message.')
1191    except struct.error as e:
1192      raise message_mod.DecodeError(e)
1193    return length   # Return this for legacy reasons.

Merges serialized protocol buffer data into this message.

When we find a field in serialized that is already present in this message:

  • If it's a "repeated" field, we append to the end of our list.
  • Else, if it's a scalar, we overwrite our field.
  • Else, (it's a nonrepeated composite), we recursively merge into the existing composite.
Arguments:
  • serialized (bytes): Any object that allows us to call memoryview(serialized) to access a string of bytes using the buffer interface.
Returns:

int: The number of bytes read from serialized. For non-group messages, this will always be len(serialized), but for messages which are actually groups, this will generally be less than len(serialized), since we must stop when we reach an END_GROUP tag. Note that if we do stop because of an END_GROUP tag, the number of bytes returned does not include the bytes for the END_GROUP tag information.

Raises:
  • DecodeError: if the input cannot be parsed.
def SerializeToString(self, **kwargs):
1133  def SerializeToString(self, **kwargs):
1134    # Check if the message has all of its required fields set.
1135    if not self.IsInitialized():
1136      raise message_mod.EncodeError(
1137          'Message %s is missing required fields: %s' % (
1138          self.DESCRIPTOR.full_name, ','.join(self.FindInitializationErrors())))
1139    return self.SerializePartialToString(**kwargs)

Serializes the protocol message to a binary string.

Keyword Args:

deterministic (bool): If true, requests deterministic serialization of the protobuf, with predictable ordering of map keys.

Returns:

A binary string representation of the message if all of the required fields in the message are set (i.e. the message is initialized).

Raises:
def SerializePartialToString(self, **kwargs):
1146  def SerializePartialToString(self, **kwargs):
1147    out = BytesIO()
1148    self._InternalSerialize(out.write, **kwargs)
1149    return out.getvalue()

Serializes the protocol message to a binary string.

This method is similar to SerializeToString but doesn't check if the message is initialized.

Keyword Args:

deterministic (bool): If true, requests deterministic serialization of the protobuf, with predictable ordering of map keys.

Returns:

bytes: A serialized representation of the partial message.

def ListFields(self):
848  def ListFields(self):
849    all_fields = [item for item in self._fields.items() if _IsPresent(item)]
850    all_fields.sort(key = lambda item: item[0].number)
851    return all_fields

Returns a list of (FieldDescriptor, value) tuples for present fields.

A message field is non-empty if HasField() would return true. A singular primitive field is non-empty if HasField() would return true in proto2 or it is non zero in proto3. A repeated field is non-empty if it contains at least one element. The fields are ordered by field number.

Returns:

list[tuple(FieldDescriptor, value)]: field descriptors and values for all fields in the message which are not empty. The values vary by field type.

def HasField(self, field_name):
872  def HasField(self, field_name):
873    try:
874      field = hassable_fields[field_name]
875    except KeyError as exc:
876      raise ValueError('Protocol message %s has no non-repeated field "%s" '
877                       'nor has presence is not available for this field.' % (
878                           message_descriptor.full_name, field_name)) from exc
879
880    if isinstance(field, descriptor_mod.OneofDescriptor):
881      try:
882        return HasField(self, self._oneofs[field].name)
883      except KeyError:
884        return False
885    else:
886      if field.cpp_type == _FieldDescriptor.CPPTYPE_MESSAGE:
887        value = self._fields.get(field)
888        return value is not None and value._is_present_in_parent
889      else:
890        return field in self._fields

Checks if a certain field is set for the message.

For a oneof group, checks if any field inside is set. Note that if the field_name is not defined in the message descriptor, ValueError will be raised.

Arguments:
  • field_name (str): The name of the field to check for presence.
Returns:

bool: Whether a value has been set for the named field.

Raises:
  • ValueError: if the field_name is not a member of this message.
def ClearField(self, field_name):
897  def ClearField(self, field_name):
898    try:
899      field = message_descriptor.fields_by_name[field_name]
900    except KeyError:
901      try:
902        field = message_descriptor.oneofs_by_name[field_name]
903        if field in self._oneofs:
904          field = self._oneofs[field]
905        else:
906          return
907      except KeyError:
908        raise ValueError('Protocol message %s has no "%s" field.' %
909                         (message_descriptor.name, field_name))
910
911    if field in self._fields:
912      # To match the C++ implementation, we need to invalidate iterators
913      # for map fields when ClearField() happens.
914      if hasattr(self._fields[field], 'InvalidateIterators'):
915        self._fields[field].InvalidateIterators()
916
917      # Note:  If the field is a sub-message, its listener will still point
918      #   at us.  That's fine, because the worst than can happen is that it
919      #   will call _Modified() and invalidate our byte size.  Big deal.
920      del self._fields[field]
921
922      if self._oneofs.get(field.containing_oneof, None) is field:
923        del self._oneofs[field.containing_oneof]
924
925    # Always call _Modified() -- even if nothing was changed, this is
926    # a mutating method, and thus calling it should cause the field to become
927    # present in the parent message.
928    self._Modified()

Clears the contents of a given field.

Inside a oneof group, clears the field set. If the name neither refers to a defined field or oneof group, ValueError is raised.

Arguments:
  • field_name (str): The name of the field to check for presence.
Raises:
  • ValueError: if the field_name is not a member of this message.
def WhichOneof(self, oneof_name):
1406  def WhichOneof(self, oneof_name):
1407    """Returns the name of the currently set field inside a oneof, or None."""
1408    try:
1409      field = message_descriptor.oneofs_by_name[oneof_name]
1410    except KeyError:
1411      raise ValueError(
1412          'Protocol message has no oneof "%s" field.' % oneof_name)
1413
1414    nested_field = self._oneofs.get(field, None)
1415    if nested_field is not None and self.HasField(nested_field.name):
1416      return nested_field.name
1417    else:
1418      return None

Returns the name of the currently set field inside a oneof, or None.

def DiscardUnknownFields(self):
1438def _DiscardUnknownFields(self):
1439  self._unknown_fields = []
1440  for field, value in self.ListFields():
1441    if field.cpp_type == _FieldDescriptor.CPPTYPE_MESSAGE:
1442      if _IsMapField(field):
1443        if _IsMessageMapField(field):
1444          for key in value:
1445            value[key].DiscardUnknownFields()
1446      elif field.label == _FieldDescriptor.LABEL_REPEATED:
1447        for sub_message in value:
1448          sub_message.DiscardUnknownFields()
1449      else:
1450        value.DiscardUnknownFields()

Clears all fields in the UnknownFieldSet.

This operation is recursive for nested message.

def ByteSize(self):
1101  def ByteSize(self):
1102    if not self._cached_byte_size_dirty:
1103      return self._cached_byte_size
1104
1105    size = 0
1106    descriptor = self.DESCRIPTOR
1107    if descriptor._is_map_entry:
1108      # Fields of map entry should always be serialized.
1109      key_field = descriptor.fields_by_name['key']
1110      _MaybeAddEncoder(cls, key_field)
1111      size = key_field._sizer(self.key)
1112      value_field = descriptor.fields_by_name['value']
1113      _MaybeAddEncoder(cls, value_field)
1114      size += value_field._sizer(self.value)
1115    else:
1116      for field_descriptor, field_value in self.ListFields():
1117        _MaybeAddEncoder(cls, field_descriptor)
1118        size += field_descriptor._sizer(field_value)
1119      for tag_bytes, value_bytes in self._unknown_fields:
1120        size += len(tag_bytes) + len(value_bytes)
1121
1122    self._cached_byte_size = size
1123    self._cached_byte_size_dirty = False
1124    self._listener_for_children.dirty = False
1125    return size

Returns the serialized size of this message.

Recursively calls ByteSize() on all contained messages.

Returns:

int: The number of bytes required to serialize this message.

def FromString(s):
826  def FromString(s):
827    message = cls()
828    message.MergeFromString(s)
829    return message
START_FIELD_NUMBER = 4
start
767  def getter(self):
768    field_value = self._fields.get(field)
769    if field_value is None:
770      # Construct a new object to represent this field.
771      field_value = field._default_constructor(self)
772
773      # Atomically check if another thread has preempted us and, if not, swap
774      # in the new object we just created.  If someone has preempted us, we
775      # take that object and discard ours.
776      # WARNING:  We are relying on setdefault() being atomic.  This is true
777      #   in CPython but we haven't investigated others.  This warning appears
778      #   in several other locations in this file.
779      field_value = self._fields.setdefault(field, field_value)
780    return field_value

Getter for start.

END_FIELD_NUMBER = 5
end
767  def getter(self):
768    field_value = self._fields.get(field)
769    if field_value is None:
770      # Construct a new object to represent this field.
771      field_value = field._default_constructor(self)
772
773      # Atomically check if another thread has preempted us and, if not, swap
774      # in the new object we just created.  If someone has preempted us, we
775      # take that object and discard ours.
776      # WARNING:  We are relying on setdefault() being atomic.  This is true
777      #   in CPython but we haven't investigated others.  This warning appears
778      #   in several other locations in this file.
779      field_value = self._fields.setdefault(field, field_value)
780    return field_value

Getter for end.

SIZE_FIELD_NUMBER = 6
size
767  def getter(self):
768    field_value = self._fields.get(field)
769    if field_value is None:
770      # Construct a new object to represent this field.
771      field_value = field._default_constructor(self)
772
773      # Atomically check if another thread has preempted us and, if not, swap
774      # in the new object we just created.  If someone has preempted us, we
775      # take that object and discard ours.
776      # WARNING:  We are relying on setdefault() being atomic.  This is true
777      #   in CPython but we haven't investigated others.  This warning appears
778      #   in several other locations in this file.
779      field_value = self._fields.setdefault(field, field_value)
780    return field_value

Getter for size.

def FindInitializationErrors(self):
1305  def FindInitializationErrors(self):
1306    """Finds required fields which are not initialized.
1307
1308    Returns:
1309      A list of strings.  Each string is a path to an uninitialized field from
1310      the top-level message, e.g. "foo.bar[5].baz".
1311    """
1312
1313    errors = []  # simplify things
1314
1315    for field in required_fields:
1316      if not self.HasField(field.name):
1317        errors.append(field.name)
1318
1319    for field, value in self.ListFields():
1320      if field.cpp_type == _FieldDescriptor.CPPTYPE_MESSAGE:
1321        if field.is_extension:
1322          name = '(%s)' % field.full_name
1323        else:
1324          name = field.name
1325
1326        if _IsMapField(field):
1327          if _IsMessageMapField(field):
1328            for key in value:
1329              element = value[key]
1330              prefix = '%s[%s].' % (name, key)
1331              sub_errors = element.FindInitializationErrors()
1332              errors += [prefix + error for error in sub_errors]
1333          else:
1334            # ScalarMaps can't have any initialization errors.
1335            pass
1336        elif field.label == _FieldDescriptor.LABEL_REPEATED:
1337          for i in range(len(value)):
1338            element = value[i]
1339            prefix = '%s[%d].' % (name, i)
1340            sub_errors = element.FindInitializationErrors()
1341            errors += [prefix + error for error in sub_errors]
1342        else:
1343          prefix = name + '.'
1344          sub_errors = value.FindInitializationErrors()
1345          errors += [prefix + error for error in sub_errors]
1346
1347    return errors

Finds required fields which are not initialized.

Returns:

A list of strings. Each string is a path to an uninitialized field from the top-level message, e.g. "foo.bar[5].baz".

class NoOverlapConstraintProto(google.protobuf.message.Message):

Abstract base class for protocol messages.

Protocol message classes are almost always generated by the protocol compiler. These generated types subclass Message and implement the methods shown below.

NoOverlapConstraintProto(**kwargs)
498  def init(self, **kwargs):
499    self._cached_byte_size = 0
500    self._cached_byte_size_dirty = len(kwargs) > 0
501    self._fields = {}
502    # Contains a mapping from oneof field descriptors to the descriptor
503    # of the currently set field in that oneof field.
504    self._oneofs = {}
505
506    # _unknown_fields is () when empty for efficiency, and will be turned into
507    # a list if fields are added.
508    self._unknown_fields = ()
509    self._is_present_in_parent = False
510    self._listener = message_listener_mod.NullMessageListener()
511    self._listener_for_children = _Listener(self)
512    for field_name, field_value in kwargs.items():
513      field = _GetFieldByName(message_descriptor, field_name)
514      if field is None:
515        raise TypeError('%s() got an unexpected keyword argument "%s"' %
516                        (message_descriptor.name, field_name))
517      if field_value is None:
518        # field=None is the same as no field at all.
519        continue
520      if field.label == _FieldDescriptor.LABEL_REPEATED:
521        field_copy = field._default_constructor(self)
522        if field.cpp_type == _FieldDescriptor.CPPTYPE_MESSAGE:  # Composite
523          if _IsMapField(field):
524            if _IsMessageMapField(field):
525              for key in field_value:
526                field_copy[key].MergeFrom(field_value[key])
527            else:
528              field_copy.update(field_value)
529          else:
530            for val in field_value:
531              if isinstance(val, dict):
532                field_copy.add(**val)
533              else:
534                field_copy.add().MergeFrom(val)
535        else:  # Scalar
536          if field.cpp_type == _FieldDescriptor.CPPTYPE_ENUM:
537            field_value = [_GetIntegerEnumValue(field.enum_type, val)
538                           for val in field_value]
539          field_copy.extend(field_value)
540        self._fields[field] = field_copy
541      elif field.cpp_type == _FieldDescriptor.CPPTYPE_MESSAGE:
542        field_copy = field._default_constructor(self)
543        new_val = None
544        if isinstance(field_value, message_mod.Message):
545          new_val = field_value
546        elif isinstance(field_value, dict):
547          if field.message_type.full_name == _StructFullTypeName:
548            field_copy.Clear()
549            if len(field_value) == 1 and 'fields' in field_value:
550              try:
551                field_copy.update(field_value)
552              except:
553                # Fall back to init normal message field
554                field_copy.Clear()
555                new_val = field.message_type._concrete_class(**field_value)
556            else:
557              field_copy.update(field_value)
558          else:
559            new_val = field.message_type._concrete_class(**field_value)
560        elif hasattr(field_copy, '_internal_assign'):
561          field_copy._internal_assign(field_value)
562        else:
563          raise TypeError(
564              'Message field {0}.{1} must be initialized with a '
565              'dict or instance of same class, got {2}.'.format(
566                  message_descriptor.name,
567                  field_name,
568                  type(field_value).__name__,
569              )
570          )
571
572        if new_val != None:
573          try:
574            field_copy.MergeFrom(new_val)
575          except TypeError:
576            _ReraiseTypeErrorWithFieldName(message_descriptor.name, field_name)
577        self._fields[field] = field_copy
578      else:
579        if field.cpp_type == _FieldDescriptor.CPPTYPE_ENUM:
580          field_value = _GetIntegerEnumValue(field.enum_type, field_value)
581        try:
582          setattr(self, field_name, field_value)
583        except TypeError:
584          _ReraiseTypeErrorWithFieldName(message_descriptor.name, field_name)
DESCRIPTOR = <google.protobuf.descriptor.Descriptor object>
def MergeFrom(self, msg):
1364  def MergeFrom(self, msg):
1365    if not isinstance(msg, cls):
1366      raise TypeError(
1367          'Parameter to MergeFrom() must be instance of same class: '
1368          'expected %s got %s.' % (_FullyQualifiedClassName(cls),
1369                                   _FullyQualifiedClassName(msg.__class__)))
1370
1371    assert msg is not self
1372    self._Modified()
1373
1374    fields = self._fields
1375
1376    for field, value in msg._fields.items():
1377      if field.label == LABEL_REPEATED:
1378        field_value = fields.get(field)
1379        if field_value is None:
1380          # Construct a new object to represent this field.
1381          field_value = field._default_constructor(self)
1382          fields[field] = field_value
1383        field_value.MergeFrom(value)
1384      elif field.cpp_type == CPPTYPE_MESSAGE:
1385        if value._is_present_in_parent:
1386          field_value = fields.get(field)
1387          if field_value is None:
1388            # Construct a new object to represent this field.
1389            field_value = field._default_constructor(self)
1390            fields[field] = field_value
1391          field_value.MergeFrom(value)
1392      else:
1393        self._fields[field] = value
1394        if field.containing_oneof:
1395          self._UpdateOneofState(field)
1396
1397    if msg._unknown_fields:
1398      if not self._unknown_fields:
1399        self._unknown_fields = []
1400      self._unknown_fields.extend(msg._unknown_fields)

Merges the contents of the specified message into current message.

This method merges the contents of the specified message into the current message. Singular fields that are set in the specified message overwrite the corresponding fields in the current message. Repeated fields are appended. Singular sub-messages and groups are recursively merged.

Arguments:
  • other_msg (Message): A message to merge into the current message.
def Clear(self):
1423def _Clear(self):
1424  # Clear fields.
1425  self._fields = {}
1426  self._unknown_fields = ()
1427
1428  self._oneofs = {}
1429  self._Modified()

Clears all data that was set in the message.

def SetInParent(self):
1489  def Modified(self):
1490    """Sets the _cached_byte_size_dirty bit to true,
1491    and propagates this to our listener iff this was a state change.
1492    """
1493
1494    # Note:  Some callers check _cached_byte_size_dirty before calling
1495    #   _Modified() as an extra optimization.  So, if this method is ever
1496    #   changed such that it does stuff even when _cached_byte_size_dirty is
1497    #   already true, the callers need to be updated.
1498    if not self._cached_byte_size_dirty:
1499      self._cached_byte_size_dirty = True
1500      self._listener_for_children.dirty = True
1501      self._is_present_in_parent = True
1502      self._listener.Modified()

Sets the _cached_byte_size_dirty bit to true, and propagates this to our listener iff this was a state change.

def IsInitialized(self, errors=None):
1265  def IsInitialized(self, errors=None):
1266    """Checks if all required fields of a message are set.
1267
1268    Args:
1269      errors:  A list which, if provided, will be populated with the field
1270               paths of all missing required fields.
1271
1272    Returns:
1273      True iff the specified message has all required fields set.
1274    """
1275
1276    # Performance is critical so we avoid HasField() and ListFields().
1277
1278    for field in required_fields:
1279      if (field not in self._fields or
1280          (field.cpp_type == _FieldDescriptor.CPPTYPE_MESSAGE and
1281           not self._fields[field]._is_present_in_parent)):
1282        if errors is not None:
1283          errors.extend(self.FindInitializationErrors())
1284        return False
1285
1286    for field, value in list(self._fields.items()):  # dict can change size!
1287      if field.cpp_type == _FieldDescriptor.CPPTYPE_MESSAGE:
1288        if field.label == _FieldDescriptor.LABEL_REPEATED:
1289          if (field.message_type._is_map_entry):
1290            continue
1291          for element in value:
1292            if not element.IsInitialized():
1293              if errors is not None:
1294                errors.extend(self.FindInitializationErrors())
1295              return False
1296        elif value._is_present_in_parent and not value.IsInitialized():
1297          if errors is not None:
1298            errors.extend(self.FindInitializationErrors())
1299          return False
1300
1301    return True

Checks if all required fields of a message are set.

Arguments:
  • errors: A list which, if provided, will be populated with the field paths of all missing required fields.
Returns:

True iff the specified message has all required fields set.

def MergeFromString(self, serialized):
1180  def MergeFromString(self, serialized):
1181    serialized = memoryview(serialized)
1182    length = len(serialized)
1183    try:
1184      if self._InternalParse(serialized, 0, length) != length:
1185        # The only reason _InternalParse would return early is if it
1186        # encountered an end-group tag.
1187        raise message_mod.DecodeError('Unexpected end-group tag.')
1188    except (IndexError, TypeError):
1189      # Now ord(buf[p:p+1]) == ord('') gets TypeError.
1190      raise message_mod.DecodeError('Truncated message.')
1191    except struct.error as e:
1192      raise message_mod.DecodeError(e)
1193    return length   # Return this for legacy reasons.

Merges serialized protocol buffer data into this message.

When we find a field in serialized that is already present in this message:

  • If it's a "repeated" field, we append to the end of our list.
  • Else, if it's a scalar, we overwrite our field.
  • Else, (it's a nonrepeated composite), we recursively merge into the existing composite.
Arguments:
  • serialized (bytes): Any object that allows us to call memoryview(serialized) to access a string of bytes using the buffer interface.
Returns:

int: The number of bytes read from serialized. For non-group messages, this will always be len(serialized), but for messages which are actually groups, this will generally be less than len(serialized), since we must stop when we reach an END_GROUP tag. Note that if we do stop because of an END_GROUP tag, the number of bytes returned does not include the bytes for the END_GROUP tag information.

Raises:
  • DecodeError: if the input cannot be parsed.
def SerializeToString(self, **kwargs):
1133  def SerializeToString(self, **kwargs):
1134    # Check if the message has all of its required fields set.
1135    if not self.IsInitialized():
1136      raise message_mod.EncodeError(
1137          'Message %s is missing required fields: %s' % (
1138          self.DESCRIPTOR.full_name, ','.join(self.FindInitializationErrors())))
1139    return self.SerializePartialToString(**kwargs)

Serializes the protocol message to a binary string.

Keyword Args:

deterministic (bool): If true, requests deterministic serialization of the protobuf, with predictable ordering of map keys.

Returns:

A binary string representation of the message if all of the required fields in the message are set (i.e. the message is initialized).

Raises:
def SerializePartialToString(self, **kwargs):
1146  def SerializePartialToString(self, **kwargs):
1147    out = BytesIO()
1148    self._InternalSerialize(out.write, **kwargs)
1149    return out.getvalue()

Serializes the protocol message to a binary string.

This method is similar to SerializeToString but doesn't check if the message is initialized.

Keyword Args:

deterministic (bool): If true, requests deterministic serialization of the protobuf, with predictable ordering of map keys.

Returns:

bytes: A serialized representation of the partial message.

def ListFields(self):
848  def ListFields(self):
849    all_fields = [item for item in self._fields.items() if _IsPresent(item)]
850    all_fields.sort(key = lambda item: item[0].number)
851    return all_fields

Returns a list of (FieldDescriptor, value) tuples for present fields.

A message field is non-empty if HasField() would return true. A singular primitive field is non-empty if HasField() would return true in proto2 or it is non zero in proto3. A repeated field is non-empty if it contains at least one element. The fields are ordered by field number.

Returns:

list[tuple(FieldDescriptor, value)]: field descriptors and values for all fields in the message which are not empty. The values vary by field type.

def HasField(self, field_name):
872  def HasField(self, field_name):
873    try:
874      field = hassable_fields[field_name]
875    except KeyError as exc:
876      raise ValueError('Protocol message %s has no non-repeated field "%s" '
877                       'nor has presence is not available for this field.' % (
878                           message_descriptor.full_name, field_name)) from exc
879
880    if isinstance(field, descriptor_mod.OneofDescriptor):
881      try:
882        return HasField(self, self._oneofs[field].name)
883      except KeyError:
884        return False
885    else:
886      if field.cpp_type == _FieldDescriptor.CPPTYPE_MESSAGE:
887        value = self._fields.get(field)
888        return value is not None and value._is_present_in_parent
889      else:
890        return field in self._fields

Checks if a certain field is set for the message.

For a oneof group, checks if any field inside is set. Note that if the field_name is not defined in the message descriptor, ValueError will be raised.

Arguments:
  • field_name (str): The name of the field to check for presence.
Returns:

bool: Whether a value has been set for the named field.

Raises:
  • ValueError: if the field_name is not a member of this message.
def ClearField(self, field_name):
897  def ClearField(self, field_name):
898    try:
899      field = message_descriptor.fields_by_name[field_name]
900    except KeyError:
901      try:
902        field = message_descriptor.oneofs_by_name[field_name]
903        if field in self._oneofs:
904          field = self._oneofs[field]
905        else:
906          return
907      except KeyError:
908        raise ValueError('Protocol message %s has no "%s" field.' %
909                         (message_descriptor.name, field_name))
910
911    if field in self._fields:
912      # To match the C++ implementation, we need to invalidate iterators
913      # for map fields when ClearField() happens.
914      if hasattr(self._fields[field], 'InvalidateIterators'):
915        self._fields[field].InvalidateIterators()
916
917      # Note:  If the field is a sub-message, its listener will still point
918      #   at us.  That's fine, because the worst than can happen is that it
919      #   will call _Modified() and invalidate our byte size.  Big deal.
920      del self._fields[field]
921
922      if self._oneofs.get(field.containing_oneof, None) is field:
923        del self._oneofs[field.containing_oneof]
924
925    # Always call _Modified() -- even if nothing was changed, this is
926    # a mutating method, and thus calling it should cause the field to become
927    # present in the parent message.
928    self._Modified()

Clears the contents of a given field.

Inside a oneof group, clears the field set. If the name neither refers to a defined field or oneof group, ValueError is raised.

Arguments:
  • field_name (str): The name of the field to check for presence.
Raises:
  • ValueError: if the field_name is not a member of this message.
def WhichOneof(self, oneof_name):
1406  def WhichOneof(self, oneof_name):
1407    """Returns the name of the currently set field inside a oneof, or None."""
1408    try:
1409      field = message_descriptor.oneofs_by_name[oneof_name]
1410    except KeyError:
1411      raise ValueError(
1412          'Protocol message has no oneof "%s" field.' % oneof_name)
1413
1414    nested_field = self._oneofs.get(field, None)
1415    if nested_field is not None and self.HasField(nested_field.name):
1416      return nested_field.name
1417    else:
1418      return None

Returns the name of the currently set field inside a oneof, or None.

def DiscardUnknownFields(self):
1438def _DiscardUnknownFields(self):
1439  self._unknown_fields = []
1440  for field, value in self.ListFields():
1441    if field.cpp_type == _FieldDescriptor.CPPTYPE_MESSAGE:
1442      if _IsMapField(field):
1443        if _IsMessageMapField(field):
1444          for key in value:
1445            value[key].DiscardUnknownFields()
1446      elif field.label == _FieldDescriptor.LABEL_REPEATED:
1447        for sub_message in value:
1448          sub_message.DiscardUnknownFields()
1449      else:
1450        value.DiscardUnknownFields()

Clears all fields in the UnknownFieldSet.

This operation is recursive for nested message.

def ByteSize(self):
1101  def ByteSize(self):
1102    if not self._cached_byte_size_dirty:
1103      return self._cached_byte_size
1104
1105    size = 0
1106    descriptor = self.DESCRIPTOR
1107    if descriptor._is_map_entry:
1108      # Fields of map entry should always be serialized.
1109      key_field = descriptor.fields_by_name['key']
1110      _MaybeAddEncoder(cls, key_field)
1111      size = key_field._sizer(self.key)
1112      value_field = descriptor.fields_by_name['value']
1113      _MaybeAddEncoder(cls, value_field)
1114      size += value_field._sizer(self.value)
1115    else:
1116      for field_descriptor, field_value in self.ListFields():
1117        _MaybeAddEncoder(cls, field_descriptor)
1118        size += field_descriptor._sizer(field_value)
1119      for tag_bytes, value_bytes in self._unknown_fields:
1120        size += len(tag_bytes) + len(value_bytes)
1121
1122    self._cached_byte_size = size
1123    self._cached_byte_size_dirty = False
1124    self._listener_for_children.dirty = False
1125    return size

Returns the serialized size of this message.

Recursively calls ByteSize() on all contained messages.

Returns:

int: The number of bytes required to serialize this message.

def FromString(s):
826  def FromString(s):
827    message = cls()
828    message.MergeFromString(s)
829    return message
INTERVALS_FIELD_NUMBER = 1
intervals
668  def getter(self):
669    field_value = self._fields.get(field)
670    if field_value is None:
671      # Construct a new object to represent this field.
672      field_value = field._default_constructor(self)
673
674      # Atomically check if another thread has preempted us and, if not, swap
675      # in the new object we just created.  If someone has preempted us, we
676      # take that object and discard ours.
677      # WARNING:  We are relying on setdefault() being atomic.  This is true
678      #   in CPython but we haven't investigated others.  This warning appears
679      #   in several other locations in this file.
680      field_value = self._fields.setdefault(field, field_value)
681    return field_value

Getter for intervals.

def FindInitializationErrors(self):
1305  def FindInitializationErrors(self):
1306    """Finds required fields which are not initialized.
1307
1308    Returns:
1309      A list of strings.  Each string is a path to an uninitialized field from
1310      the top-level message, e.g. "foo.bar[5].baz".
1311    """
1312
1313    errors = []  # simplify things
1314
1315    for field in required_fields:
1316      if not self.HasField(field.name):
1317        errors.append(field.name)
1318
1319    for field, value in self.ListFields():
1320      if field.cpp_type == _FieldDescriptor.CPPTYPE_MESSAGE:
1321        if field.is_extension:
1322          name = '(%s)' % field.full_name
1323        else:
1324          name = field.name
1325
1326        if _IsMapField(field):
1327          if _IsMessageMapField(field):
1328            for key in value:
1329              element = value[key]
1330              prefix = '%s[%s].' % (name, key)
1331              sub_errors = element.FindInitializationErrors()
1332              errors += [prefix + error for error in sub_errors]
1333          else:
1334            # ScalarMaps can't have any initialization errors.
1335            pass
1336        elif field.label == _FieldDescriptor.LABEL_REPEATED:
1337          for i in range(len(value)):
1338            element = value[i]
1339            prefix = '%s[%d].' % (name, i)
1340            sub_errors = element.FindInitializationErrors()
1341            errors += [prefix + error for error in sub_errors]
1342        else:
1343          prefix = name + '.'
1344          sub_errors = value.FindInitializationErrors()
1345          errors += [prefix + error for error in sub_errors]
1346
1347    return errors

Finds required fields which are not initialized.

Returns:

A list of strings. Each string is a path to an uninitialized field from the top-level message, e.g. "foo.bar[5].baz".

class NoOverlap2DConstraintProto(google.protobuf.message.Message):

Abstract base class for protocol messages.

Protocol message classes are almost always generated by the protocol compiler. These generated types subclass Message and implement the methods shown below.

NoOverlap2DConstraintProto(**kwargs)
498  def init(self, **kwargs):
499    self._cached_byte_size = 0
500    self._cached_byte_size_dirty = len(kwargs) > 0
501    self._fields = {}
502    # Contains a mapping from oneof field descriptors to the descriptor
503    # of the currently set field in that oneof field.
504    self._oneofs = {}
505
506    # _unknown_fields is () when empty for efficiency, and will be turned into
507    # a list if fields are added.
508    self._unknown_fields = ()
509    self._is_present_in_parent = False
510    self._listener = message_listener_mod.NullMessageListener()
511    self._listener_for_children = _Listener(self)
512    for field_name, field_value in kwargs.items():
513      field = _GetFieldByName(message_descriptor, field_name)
514      if field is None:
515        raise TypeError('%s() got an unexpected keyword argument "%s"' %
516                        (message_descriptor.name, field_name))
517      if field_value is None:
518        # field=None is the same as no field at all.
519        continue
520      if field.label == _FieldDescriptor.LABEL_REPEATED:
521        field_copy = field._default_constructor(self)
522        if field.cpp_type == _FieldDescriptor.CPPTYPE_MESSAGE:  # Composite
523          if _IsMapField(field):
524            if _IsMessageMapField(field):
525              for key in field_value:
526                field_copy[key].MergeFrom(field_value[key])
527            else:
528              field_copy.update(field_value)
529          else:
530            for val in field_value:
531              if isinstance(val, dict):
532                field_copy.add(**val)
533              else:
534                field_copy.add().MergeFrom(val)
535        else:  # Scalar
536          if field.cpp_type == _FieldDescriptor.CPPTYPE_ENUM:
537            field_value = [_GetIntegerEnumValue(field.enum_type, val)
538                           for val in field_value]
539          field_copy.extend(field_value)
540        self._fields[field] = field_copy
541      elif field.cpp_type == _FieldDescriptor.CPPTYPE_MESSAGE:
542        field_copy = field._default_constructor(self)
543        new_val = None
544        if isinstance(field_value, message_mod.Message):
545          new_val = field_value
546        elif isinstance(field_value, dict):
547          if field.message_type.full_name == _StructFullTypeName:
548            field_copy.Clear()
549            if len(field_value) == 1 and 'fields' in field_value:
550              try:
551                field_copy.update(field_value)
552              except:
553                # Fall back to init normal message field
554                field_copy.Clear()
555                new_val = field.message_type._concrete_class(**field_value)
556            else:
557              field_copy.update(field_value)
558          else:
559            new_val = field.message_type._concrete_class(**field_value)
560        elif hasattr(field_copy, '_internal_assign'):
561          field_copy._internal_assign(field_value)
562        else:
563          raise TypeError(
564              'Message field {0}.{1} must be initialized with a '
565              'dict or instance of same class, got {2}.'.format(
566                  message_descriptor.name,
567                  field_name,
568                  type(field_value).__name__,
569              )
570          )
571
572        if new_val != None:
573          try:
574            field_copy.MergeFrom(new_val)
575          except TypeError:
576            _ReraiseTypeErrorWithFieldName(message_descriptor.name, field_name)
577        self._fields[field] = field_copy
578      else:
579        if field.cpp_type == _FieldDescriptor.CPPTYPE_ENUM:
580          field_value = _GetIntegerEnumValue(field.enum_type, field_value)
581        try:
582          setattr(self, field_name, field_value)
583        except TypeError:
584          _ReraiseTypeErrorWithFieldName(message_descriptor.name, field_name)
DESCRIPTOR = <google.protobuf.descriptor.Descriptor object>
def MergeFrom(self, msg):
1364  def MergeFrom(self, msg):
1365    if not isinstance(msg, cls):
1366      raise TypeError(
1367          'Parameter to MergeFrom() must be instance of same class: '
1368          'expected %s got %s.' % (_FullyQualifiedClassName(cls),
1369                                   _FullyQualifiedClassName(msg.__class__)))
1370
1371    assert msg is not self
1372    self._Modified()
1373
1374    fields = self._fields
1375
1376    for field, value in msg._fields.items():
1377      if field.label == LABEL_REPEATED:
1378        field_value = fields.get(field)
1379        if field_value is None:
1380          # Construct a new object to represent this field.
1381          field_value = field._default_constructor(self)
1382          fields[field] = field_value
1383        field_value.MergeFrom(value)
1384      elif field.cpp_type == CPPTYPE_MESSAGE:
1385        if value._is_present_in_parent:
1386          field_value = fields.get(field)
1387          if field_value is None:
1388            # Construct a new object to represent this field.
1389            field_value = field._default_constructor(self)
1390            fields[field] = field_value
1391          field_value.MergeFrom(value)
1392      else:
1393        self._fields[field] = value
1394        if field.containing_oneof:
1395          self._UpdateOneofState(field)
1396
1397    if msg._unknown_fields:
1398      if not self._unknown_fields:
1399        self._unknown_fields = []
1400      self._unknown_fields.extend(msg._unknown_fields)

Merges the contents of the specified message into current message.

This method merges the contents of the specified message into the current message. Singular fields that are set in the specified message overwrite the corresponding fields in the current message. Repeated fields are appended. Singular sub-messages and groups are recursively merged.

Arguments:
  • other_msg (Message): A message to merge into the current message.
def Clear(self):
1423def _Clear(self):
1424  # Clear fields.
1425  self._fields = {}
1426  self._unknown_fields = ()
1427
1428  self._oneofs = {}
1429  self._Modified()

Clears all data that was set in the message.

def SetInParent(self):
1489  def Modified(self):
1490    """Sets the _cached_byte_size_dirty bit to true,
1491    and propagates this to our listener iff this was a state change.
1492    """
1493
1494    # Note:  Some callers check _cached_byte_size_dirty before calling
1495    #   _Modified() as an extra optimization.  So, if this method is ever
1496    #   changed such that it does stuff even when _cached_byte_size_dirty is
1497    #   already true, the callers need to be updated.
1498    if not self._cached_byte_size_dirty:
1499      self._cached_byte_size_dirty = True
1500      self._listener_for_children.dirty = True
1501      self._is_present_in_parent = True
1502      self._listener.Modified()

Sets the _cached_byte_size_dirty bit to true, and propagates this to our listener iff this was a state change.

def IsInitialized(self, errors=None):
1265  def IsInitialized(self, errors=None):
1266    """Checks if all required fields of a message are set.
1267
1268    Args:
1269      errors:  A list which, if provided, will be populated with the field
1270               paths of all missing required fields.
1271
1272    Returns:
1273      True iff the specified message has all required fields set.
1274    """
1275
1276    # Performance is critical so we avoid HasField() and ListFields().
1277
1278    for field in required_fields:
1279      if (field not in self._fields or
1280          (field.cpp_type == _FieldDescriptor.CPPTYPE_MESSAGE and
1281           not self._fields[field]._is_present_in_parent)):
1282        if errors is not None:
1283          errors.extend(self.FindInitializationErrors())
1284        return False
1285
1286    for field, value in list(self._fields.items()):  # dict can change size!
1287      if field.cpp_type == _FieldDescriptor.CPPTYPE_MESSAGE:
1288        if field.label == _FieldDescriptor.LABEL_REPEATED:
1289          if (field.message_type._is_map_entry):
1290            continue
1291          for element in value:
1292            if not element.IsInitialized():
1293              if errors is not None:
1294                errors.extend(self.FindInitializationErrors())
1295              return False
1296        elif value._is_present_in_parent and not value.IsInitialized():
1297          if errors is not None:
1298            errors.extend(self.FindInitializationErrors())
1299          return False
1300
1301    return True

Checks if all required fields of a message are set.

Arguments:
  • errors: A list which, if provided, will be populated with the field paths of all missing required fields.
Returns:

True iff the specified message has all required fields set.

def MergeFromString(self, serialized):
1180  def MergeFromString(self, serialized):
1181    serialized = memoryview(serialized)
1182    length = len(serialized)
1183    try:
1184      if self._InternalParse(serialized, 0, length) != length:
1185        # The only reason _InternalParse would return early is if it
1186        # encountered an end-group tag.
1187        raise message_mod.DecodeError('Unexpected end-group tag.')
1188    except (IndexError, TypeError):
1189      # Now ord(buf[p:p+1]) == ord('') gets TypeError.
1190      raise message_mod.DecodeError('Truncated message.')
1191    except struct.error as e:
1192      raise message_mod.DecodeError(e)
1193    return length   # Return this for legacy reasons.

Merges serialized protocol buffer data into this message.

When we find a field in serialized that is already present in this message:

  • If it's a "repeated" field, we append to the end of our list.
  • Else, if it's a scalar, we overwrite our field.
  • Else, (it's a nonrepeated composite), we recursively merge into the existing composite.
Arguments:
  • serialized (bytes): Any object that allows us to call memoryview(serialized) to access a string of bytes using the buffer interface.
Returns:

int: The number of bytes read from serialized. For non-group messages, this will always be len(serialized), but for messages which are actually groups, this will generally be less than len(serialized), since we must stop when we reach an END_GROUP tag. Note that if we do stop because of an END_GROUP tag, the number of bytes returned does not include the bytes for the END_GROUP tag information.

Raises:
  • DecodeError: if the input cannot be parsed.
def SerializeToString(self, **kwargs):
1133  def SerializeToString(self, **kwargs):
1134    # Check if the message has all of its required fields set.
1135    if not self.IsInitialized():
1136      raise message_mod.EncodeError(
1137          'Message %s is missing required fields: %s' % (
1138          self.DESCRIPTOR.full_name, ','.join(self.FindInitializationErrors())))
1139    return self.SerializePartialToString(**kwargs)

Serializes the protocol message to a binary string.

Keyword Args:

deterministic (bool): If true, requests deterministic serialization of the protobuf, with predictable ordering of map keys.

Returns:

A binary string representation of the message if all of the required fields in the message are set (i.e. the message is initialized).

Raises:
def SerializePartialToString(self, **kwargs):
1146  def SerializePartialToString(self, **kwargs):
1147    out = BytesIO()
1148    self._InternalSerialize(out.write, **kwargs)
1149    return out.getvalue()

Serializes the protocol message to a binary string.

This method is similar to SerializeToString but doesn't check if the message is initialized.

Keyword Args:

deterministic (bool): If true, requests deterministic serialization of the protobuf, with predictable ordering of map keys.

Returns:

bytes: A serialized representation of the partial message.

def ListFields(self):
848  def ListFields(self):
849    all_fields = [item for item in self._fields.items() if _IsPresent(item)]
850    all_fields.sort(key = lambda item: item[0].number)
851    return all_fields

Returns a list of (FieldDescriptor, value) tuples for present fields.

A message field is non-empty if HasField() would return true. A singular primitive field is non-empty if HasField() would return true in proto2 or it is non zero in proto3. A repeated field is non-empty if it contains at least one element. The fields are ordered by field number.

Returns:

list[tuple(FieldDescriptor, value)]: field descriptors and values for all fields in the message which are not empty. The values vary by field type.

def HasField(self, field_name):
872  def HasField(self, field_name):
873    try:
874      field = hassable_fields[field_name]
875    except KeyError as exc:
876      raise ValueError('Protocol message %s has no non-repeated field "%s" '
877                       'nor has presence is not available for this field.' % (
878                           message_descriptor.full_name, field_name)) from exc
879
880    if isinstance(field, descriptor_mod.OneofDescriptor):
881      try:
882        return HasField(self, self._oneofs[field].name)
883      except KeyError:
884        return False
885    else:
886      if field.cpp_type == _FieldDescriptor.CPPTYPE_MESSAGE:
887        value = self._fields.get(field)
888        return value is not None and value._is_present_in_parent
889      else:
890        return field in self._fields

Checks if a certain field is set for the message.

For a oneof group, checks if any field inside is set. Note that if the field_name is not defined in the message descriptor, ValueError will be raised.

Arguments:
  • field_name (str): The name of the field to check for presence.
Returns:

bool: Whether a value has been set for the named field.

Raises:
  • ValueError: if the field_name is not a member of this message.
def ClearField(self, field_name):
897  def ClearField(self, field_name):
898    try:
899      field = message_descriptor.fields_by_name[field_name]
900    except KeyError:
901      try:
902        field = message_descriptor.oneofs_by_name[field_name]
903        if field in self._oneofs:
904          field = self._oneofs[field]
905        else:
906          return
907      except KeyError:
908        raise ValueError('Protocol message %s has no "%s" field.' %
909                         (message_descriptor.name, field_name))
910
911    if field in self._fields:
912      # To match the C++ implementation, we need to invalidate iterators
913      # for map fields when ClearField() happens.
914      if hasattr(self._fields[field], 'InvalidateIterators'):
915        self._fields[field].InvalidateIterators()
916
917      # Note:  If the field is a sub-message, its listener will still point
918      #   at us.  That's fine, because the worst than can happen is that it
919      #   will call _Modified() and invalidate our byte size.  Big deal.
920      del self._fields[field]
921
922      if self._oneofs.get(field.containing_oneof, None) is field:
923        del self._oneofs[field.containing_oneof]
924
925    # Always call _Modified() -- even if nothing was changed, this is
926    # a mutating method, and thus calling it should cause the field to become
927    # present in the parent message.
928    self._Modified()

Clears the contents of a given field.

Inside a oneof group, clears the field set. If the name neither refers to a defined field or oneof group, ValueError is raised.

Arguments:
  • field_name (str): The name of the field to check for presence.
Raises:
  • ValueError: if the field_name is not a member of this message.
def WhichOneof(self, oneof_name):
1406  def WhichOneof(self, oneof_name):
1407    """Returns the name of the currently set field inside a oneof, or None."""
1408    try:
1409      field = message_descriptor.oneofs_by_name[oneof_name]
1410    except KeyError:
1411      raise ValueError(
1412          'Protocol message has no oneof "%s" field.' % oneof_name)
1413
1414    nested_field = self._oneofs.get(field, None)
1415    if nested_field is not None and self.HasField(nested_field.name):
1416      return nested_field.name
1417    else:
1418      return None

Returns the name of the currently set field inside a oneof, or None.

def DiscardUnknownFields(self):
1438def _DiscardUnknownFields(self):
1439  self._unknown_fields = []
1440  for field, value in self.ListFields():
1441    if field.cpp_type == _FieldDescriptor.CPPTYPE_MESSAGE:
1442      if _IsMapField(field):
1443        if _IsMessageMapField(field):
1444          for key in value:
1445            value[key].DiscardUnknownFields()
1446      elif field.label == _FieldDescriptor.LABEL_REPEATED:
1447        for sub_message in value:
1448          sub_message.DiscardUnknownFields()
1449      else:
1450        value.DiscardUnknownFields()

Clears all fields in the UnknownFieldSet.

This operation is recursive for nested message.

def ByteSize(self):
1101  def ByteSize(self):
1102    if not self._cached_byte_size_dirty:
1103      return self._cached_byte_size
1104
1105    size = 0
1106    descriptor = self.DESCRIPTOR
1107    if descriptor._is_map_entry:
1108      # Fields of map entry should always be serialized.
1109      key_field = descriptor.fields_by_name['key']
1110      _MaybeAddEncoder(cls, key_field)
1111      size = key_field._sizer(self.key)
1112      value_field = descriptor.fields_by_name['value']
1113      _MaybeAddEncoder(cls, value_field)
1114      size += value_field._sizer(self.value)
1115    else:
1116      for field_descriptor, field_value in self.ListFields():
1117        _MaybeAddEncoder(cls, field_descriptor)
1118        size += field_descriptor._sizer(field_value)
1119      for tag_bytes, value_bytes in self._unknown_fields:
1120        size += len(tag_bytes) + len(value_bytes)
1121
1122    self._cached_byte_size = size
1123    self._cached_byte_size_dirty = False
1124    self._listener_for_children.dirty = False
1125    return size

Returns the serialized size of this message.

Recursively calls ByteSize() on all contained messages.

Returns:

int: The number of bytes required to serialize this message.

def FromString(s):
826  def FromString(s):
827    message = cls()
828    message.MergeFromString(s)
829    return message
X_INTERVALS_FIELD_NUMBER = 1
x_intervals
668  def getter(self):
669    field_value = self._fields.get(field)
670    if field_value is None:
671      # Construct a new object to represent this field.
672      field_value = field._default_constructor(self)
673
674      # Atomically check if another thread has preempted us and, if not, swap
675      # in the new object we just created.  If someone has preempted us, we
676      # take that object and discard ours.
677      # WARNING:  We are relying on setdefault() being atomic.  This is true
678      #   in CPython but we haven't investigated others.  This warning appears
679      #   in several other locations in this file.
680      field_value = self._fields.setdefault(field, field_value)
681    return field_value

Getter for x_intervals.

Y_INTERVALS_FIELD_NUMBER = 2
y_intervals
668  def getter(self):
669    field_value = self._fields.get(field)
670    if field_value is None:
671      # Construct a new object to represent this field.
672      field_value = field._default_constructor(self)
673
674      # Atomically check if another thread has preempted us and, if not, swap
675      # in the new object we just created.  If someone has preempted us, we
676      # take that object and discard ours.
677      # WARNING:  We are relying on setdefault() being atomic.  This is true
678      #   in CPython but we haven't investigated others.  This warning appears
679      #   in several other locations in this file.
680      field_value = self._fields.setdefault(field, field_value)
681    return field_value

Getter for y_intervals.

def FindInitializationErrors(self):
1305  def FindInitializationErrors(self):
1306    """Finds required fields which are not initialized.
1307
1308    Returns:
1309      A list of strings.  Each string is a path to an uninitialized field from
1310      the top-level message, e.g. "foo.bar[5].baz".
1311    """
1312
1313    errors = []  # simplify things
1314
1315    for field in required_fields:
1316      if not self.HasField(field.name):
1317        errors.append(field.name)
1318
1319    for field, value in self.ListFields():
1320      if field.cpp_type == _FieldDescriptor.CPPTYPE_MESSAGE:
1321        if field.is_extension:
1322          name = '(%s)' % field.full_name
1323        else:
1324          name = field.name
1325
1326        if _IsMapField(field):
1327          if _IsMessageMapField(field):
1328            for key in value:
1329              element = value[key]
1330              prefix = '%s[%s].' % (name, key)
1331              sub_errors = element.FindInitializationErrors()
1332              errors += [prefix + error for error in sub_errors]
1333          else:
1334            # ScalarMaps can't have any initialization errors.
1335            pass
1336        elif field.label == _FieldDescriptor.LABEL_REPEATED:
1337          for i in range(len(value)):
1338            element = value[i]
1339            prefix = '%s[%d].' % (name, i)
1340            sub_errors = element.FindInitializationErrors()
1341            errors += [prefix + error for error in sub_errors]
1342        else:
1343          prefix = name + '.'
1344          sub_errors = value.FindInitializationErrors()
1345          errors += [prefix + error for error in sub_errors]
1346
1347    return errors

Finds required fields which are not initialized.

Returns:

A list of strings. Each string is a path to an uninitialized field from the top-level message, e.g. "foo.bar[5].baz".

class CumulativeConstraintProto(google.protobuf.message.Message):

Abstract base class for protocol messages.

Protocol message classes are almost always generated by the protocol compiler. These generated types subclass Message and implement the methods shown below.

CumulativeConstraintProto(**kwargs)
498  def init(self, **kwargs):
499    self._cached_byte_size = 0
500    self._cached_byte_size_dirty = len(kwargs) > 0
501    self._fields = {}
502    # Contains a mapping from oneof field descriptors to the descriptor
503    # of the currently set field in that oneof field.
504    self._oneofs = {}
505
506    # _unknown_fields is () when empty for efficiency, and will be turned into
507    # a list if fields are added.
508    self._unknown_fields = ()
509    self._is_present_in_parent = False
510    self._listener = message_listener_mod.NullMessageListener()
511    self._listener_for_children = _Listener(self)
512    for field_name, field_value in kwargs.items():
513      field = _GetFieldByName(message_descriptor, field_name)
514      if field is None:
515        raise TypeError('%s() got an unexpected keyword argument "%s"' %
516                        (message_descriptor.name, field_name))
517      if field_value is None:
518        # field=None is the same as no field at all.
519        continue
520      if field.label == _FieldDescriptor.LABEL_REPEATED:
521        field_copy = field._default_constructor(self)
522        if field.cpp_type == _FieldDescriptor.CPPTYPE_MESSAGE:  # Composite
523          if _IsMapField(field):
524            if _IsMessageMapField(field):
525              for key in field_value:
526                field_copy[key].MergeFrom(field_value[key])
527            else:
528              field_copy.update(field_value)
529          else:
530            for val in field_value:
531              if isinstance(val, dict):
532                field_copy.add(**val)
533              else:
534                field_copy.add().MergeFrom(val)
535        else:  # Scalar
536          if field.cpp_type == _FieldDescriptor.CPPTYPE_ENUM:
537            field_value = [_GetIntegerEnumValue(field.enum_type, val)
538                           for val in field_value]
539          field_copy.extend(field_value)
540        self._fields[field] = field_copy
541      elif field.cpp_type == _FieldDescriptor.CPPTYPE_MESSAGE:
542        field_copy = field._default_constructor(self)
543        new_val = None
544        if isinstance(field_value, message_mod.Message):
545          new_val = field_value
546        elif isinstance(field_value, dict):
547          if field.message_type.full_name == _StructFullTypeName:
548            field_copy.Clear()
549            if len(field_value) == 1 and 'fields' in field_value:
550              try:
551                field_copy.update(field_value)
552              except:
553                # Fall back to init normal message field
554                field_copy.Clear()
555                new_val = field.message_type._concrete_class(**field_value)
556            else:
557              field_copy.update(field_value)
558          else:
559            new_val = field.message_type._concrete_class(**field_value)
560        elif hasattr(field_copy, '_internal_assign'):
561          field_copy._internal_assign(field_value)
562        else:
563          raise TypeError(
564              'Message field {0}.{1} must be initialized with a '
565              'dict or instance of same class, got {2}.'.format(
566                  message_descriptor.name,
567                  field_name,
568                  type(field_value).__name__,
569              )
570          )
571
572        if new_val != None:
573          try:
574            field_copy.MergeFrom(new_val)
575          except TypeError:
576            _ReraiseTypeErrorWithFieldName(message_descriptor.name, field_name)
577        self._fields[field] = field_copy
578      else:
579        if field.cpp_type == _FieldDescriptor.CPPTYPE_ENUM:
580          field_value = _GetIntegerEnumValue(field.enum_type, field_value)
581        try:
582          setattr(self, field_name, field_value)
583        except TypeError:
584          _ReraiseTypeErrorWithFieldName(message_descriptor.name, field_name)
DESCRIPTOR = <google.protobuf.descriptor.Descriptor object>
def MergeFrom(self, msg):
1364  def MergeFrom(self, msg):
1365    if not isinstance(msg, cls):
1366      raise TypeError(
1367          'Parameter to MergeFrom() must be instance of same class: '
1368          'expected %s got %s.' % (_FullyQualifiedClassName(cls),
1369                                   _FullyQualifiedClassName(msg.__class__)))
1370
1371    assert msg is not self
1372    self._Modified()
1373
1374    fields = self._fields
1375
1376    for field, value in msg._fields.items():
1377      if field.label == LABEL_REPEATED:
1378        field_value = fields.get(field)
1379        if field_value is None:
1380          # Construct a new object to represent this field.
1381          field_value = field._default_constructor(self)
1382          fields[field] = field_value
1383        field_value.MergeFrom(value)
1384      elif field.cpp_type == CPPTYPE_MESSAGE:
1385        if value._is_present_in_parent:
1386          field_value = fields.get(field)
1387          if field_value is None:
1388            # Construct a new object to represent this field.
1389            field_value = field._default_constructor(self)
1390            fields[field] = field_value
1391          field_value.MergeFrom(value)
1392      else:
1393        self._fields[field] = value
1394        if field.containing_oneof:
1395          self._UpdateOneofState(field)
1396
1397    if msg._unknown_fields:
1398      if not self._unknown_fields:
1399        self._unknown_fields = []
1400      self._unknown_fields.extend(msg._unknown_fields)

Merges the contents of the specified message into current message.

This method merges the contents of the specified message into the current message. Singular fields that are set in the specified message overwrite the corresponding fields in the current message. Repeated fields are appended. Singular sub-messages and groups are recursively merged.

Arguments:
  • other_msg (Message): A message to merge into the current message.
def Clear(self):
1423def _Clear(self):
1424  # Clear fields.
1425  self._fields = {}
1426  self._unknown_fields = ()
1427
1428  self._oneofs = {}
1429  self._Modified()

Clears all data that was set in the message.

def SetInParent(self):
1489  def Modified(self):
1490    """Sets the _cached_byte_size_dirty bit to true,
1491    and propagates this to our listener iff this was a state change.
1492    """
1493
1494    # Note:  Some callers check _cached_byte_size_dirty before calling
1495    #   _Modified() as an extra optimization.  So, if this method is ever
1496    #   changed such that it does stuff even when _cached_byte_size_dirty is
1497    #   already true, the callers need to be updated.
1498    if not self._cached_byte_size_dirty:
1499      self._cached_byte_size_dirty = True
1500      self._listener_for_children.dirty = True
1501      self._is_present_in_parent = True
1502      self._listener.Modified()

Sets the _cached_byte_size_dirty bit to true, and propagates this to our listener iff this was a state change.

def IsInitialized(self, errors=None):
1265  def IsInitialized(self, errors=None):
1266    """Checks if all required fields of a message are set.
1267
1268    Args:
1269      errors:  A list which, if provided, will be populated with the field
1270               paths of all missing required fields.
1271
1272    Returns:
1273      True iff the specified message has all required fields set.
1274    """
1275
1276    # Performance is critical so we avoid HasField() and ListFields().
1277
1278    for field in required_fields:
1279      if (field not in self._fields or
1280          (field.cpp_type == _FieldDescriptor.CPPTYPE_MESSAGE and
1281           not self._fields[field]._is_present_in_parent)):
1282        if errors is not None:
1283          errors.extend(self.FindInitializationErrors())
1284        return False
1285
1286    for field, value in list(self._fields.items()):  # dict can change size!
1287      if field.cpp_type == _FieldDescriptor.CPPTYPE_MESSAGE:
1288        if field.label == _FieldDescriptor.LABEL_REPEATED:
1289          if (field.message_type._is_map_entry):
1290            continue
1291          for element in value:
1292            if not element.IsInitialized():
1293              if errors is not None:
1294                errors.extend(self.FindInitializationErrors())
1295              return False
1296        elif value._is_present_in_parent and not value.IsInitialized():
1297          if errors is not None:
1298            errors.extend(self.FindInitializationErrors())
1299          return False
1300
1301    return True

Checks if all required fields of a message are set.

Arguments:
  • errors: A list which, if provided, will be populated with the field paths of all missing required fields.
Returns:

True iff the specified message has all required fields set.

def MergeFromString(self, serialized):
1180  def MergeFromString(self, serialized):
1181    serialized = memoryview(serialized)
1182    length = len(serialized)
1183    try:
1184      if self._InternalParse(serialized, 0, length) != length:
1185        # The only reason _InternalParse would return early is if it
1186        # encountered an end-group tag.
1187        raise message_mod.DecodeError('Unexpected end-group tag.')
1188    except (IndexError, TypeError):
1189      # Now ord(buf[p:p+1]) == ord('') gets TypeError.
1190      raise message_mod.DecodeError('Truncated message.')
1191    except struct.error as e:
1192      raise message_mod.DecodeError(e)
1193    return length   # Return this for legacy reasons.

Merges serialized protocol buffer data into this message.

When we find a field in serialized that is already present in this message:

  • If it's a "repeated" field, we append to the end of our list.
  • Else, if it's a scalar, we overwrite our field.
  • Else, (it's a nonrepeated composite), we recursively merge into the existing composite.
Arguments:
  • serialized (bytes): Any object that allows us to call memoryview(serialized) to access a string of bytes using the buffer interface.
Returns:

int: The number of bytes read from serialized. For non-group messages, this will always be len(serialized), but for messages which are actually groups, this will generally be less than len(serialized), since we must stop when we reach an END_GROUP tag. Note that if we do stop because of an END_GROUP tag, the number of bytes returned does not include the bytes for the END_GROUP tag information.

Raises:
  • DecodeError: if the input cannot be parsed.
def SerializeToString(self, **kwargs):
1133  def SerializeToString(self, **kwargs):
1134    # Check if the message has all of its required fields set.
1135    if not self.IsInitialized():
1136      raise message_mod.EncodeError(
1137          'Message %s is missing required fields: %s' % (
1138          self.DESCRIPTOR.full_name, ','.join(self.FindInitializationErrors())))
1139    return self.SerializePartialToString(**kwargs)

Serializes the protocol message to a binary string.

Keyword Args:

deterministic (bool): If true, requests deterministic serialization of the protobuf, with predictable ordering of map keys.

Returns:

A binary string representation of the message if all of the required fields in the message are set (i.e. the message is initialized).

Raises:
def SerializePartialToString(self, **kwargs):
1146  def SerializePartialToString(self, **kwargs):
1147    out = BytesIO()
1148    self._InternalSerialize(out.write, **kwargs)
1149    return out.getvalue()

Serializes the protocol message to a binary string.

This method is similar to SerializeToString but doesn't check if the message is initialized.

Keyword Args:

deterministic (bool): If true, requests deterministic serialization of the protobuf, with predictable ordering of map keys.

Returns:

bytes: A serialized representation of the partial message.

def ListFields(self):
848  def ListFields(self):
849    all_fields = [item for item in self._fields.items() if _IsPresent(item)]
850    all_fields.sort(key = lambda item: item[0].number)
851    return all_fields

Returns a list of (FieldDescriptor, value) tuples for present fields.

A message field is non-empty if HasField() would return true. A singular primitive field is non-empty if HasField() would return true in proto2 or it is non zero in proto3. A repeated field is non-empty if it contains at least one element. The fields are ordered by field number.

Returns:

list[tuple(FieldDescriptor, value)]: field descriptors and values for all fields in the message which are not empty. The values vary by field type.

def HasField(self, field_name):
872  def HasField(self, field_name):
873    try:
874      field = hassable_fields[field_name]
875    except KeyError as exc:
876      raise ValueError('Protocol message %s has no non-repeated field "%s" '
877                       'nor has presence is not available for this field.' % (
878                           message_descriptor.full_name, field_name)) from exc
879
880    if isinstance(field, descriptor_mod.OneofDescriptor):
881      try:
882        return HasField(self, self._oneofs[field].name)
883      except KeyError:
884        return False
885    else:
886      if field.cpp_type == _FieldDescriptor.CPPTYPE_MESSAGE:
887        value = self._fields.get(field)
888        return value is not None and value._is_present_in_parent
889      else:
890        return field in self._fields

Checks if a certain field is set for the message.

For a oneof group, checks if any field inside is set. Note that if the field_name is not defined in the message descriptor, ValueError will be raised.

Arguments:
  • field_name (str): The name of the field to check for presence.
Returns:

bool: Whether a value has been set for the named field.

Raises:
  • ValueError: if the field_name is not a member of this message.
def ClearField(self, field_name):
897  def ClearField(self, field_name):
898    try:
899      field = message_descriptor.fields_by_name[field_name]
900    except KeyError:
901      try:
902        field = message_descriptor.oneofs_by_name[field_name]
903        if field in self._oneofs:
904          field = self._oneofs[field]
905        else:
906          return
907      except KeyError:
908        raise ValueError('Protocol message %s has no "%s" field.' %
909                         (message_descriptor.name, field_name))
910
911    if field in self._fields:
912      # To match the C++ implementation, we need to invalidate iterators
913      # for map fields when ClearField() happens.
914      if hasattr(self._fields[field], 'InvalidateIterators'):
915        self._fields[field].InvalidateIterators()
916
917      # Note:  If the field is a sub-message, its listener will still point
918      #   at us.  That's fine, because the worst than can happen is that it
919      #   will call _Modified() and invalidate our byte size.  Big deal.
920      del self._fields[field]
921
922      if self._oneofs.get(field.containing_oneof, None) is field:
923        del self._oneofs[field.containing_oneof]
924
925    # Always call _Modified() -- even if nothing was changed, this is
926    # a mutating method, and thus calling it should cause the field to become
927    # present in the parent message.
928    self._Modified()

Clears the contents of a given field.

Inside a oneof group, clears the field set. If the name neither refers to a defined field or oneof group, ValueError is raised.

Arguments:
  • field_name (str): The name of the field to check for presence.
Raises:
  • ValueError: if the field_name is not a member of this message.
def WhichOneof(self, oneof_name):
1406  def WhichOneof(self, oneof_name):
1407    """Returns the name of the currently set field inside a oneof, or None."""
1408    try:
1409      field = message_descriptor.oneofs_by_name[oneof_name]
1410    except KeyError:
1411      raise ValueError(
1412          'Protocol message has no oneof "%s" field.' % oneof_name)
1413
1414    nested_field = self._oneofs.get(field, None)
1415    if nested_field is not None and self.HasField(nested_field.name):
1416      return nested_field.name
1417    else:
1418      return None

Returns the name of the currently set field inside a oneof, or None.

def DiscardUnknownFields(self):
1438def _DiscardUnknownFields(self):
1439  self._unknown_fields = []
1440  for field, value in self.ListFields():
1441    if field.cpp_type == _FieldDescriptor.CPPTYPE_MESSAGE:
1442      if _IsMapField(field):
1443        if _IsMessageMapField(field):
1444          for key in value:
1445            value[key].DiscardUnknownFields()
1446      elif field.label == _FieldDescriptor.LABEL_REPEATED:
1447        for sub_message in value:
1448          sub_message.DiscardUnknownFields()
1449      else:
1450        value.DiscardUnknownFields()

Clears all fields in the UnknownFieldSet.

This operation is recursive for nested message.

def ByteSize(self):
1101  def ByteSize(self):
1102    if not self._cached_byte_size_dirty:
1103      return self._cached_byte_size
1104
1105    size = 0
1106    descriptor = self.DESCRIPTOR
1107    if descriptor._is_map_entry:
1108      # Fields of map entry should always be serialized.
1109      key_field = descriptor.fields_by_name['key']
1110      _MaybeAddEncoder(cls, key_field)
1111      size = key_field._sizer(self.key)
1112      value_field = descriptor.fields_by_name['value']
1113      _MaybeAddEncoder(cls, value_field)
1114      size += value_field._sizer(self.value)
1115    else:
1116      for field_descriptor, field_value in self.ListFields():
1117        _MaybeAddEncoder(cls, field_descriptor)
1118        size += field_descriptor._sizer(field_value)
1119      for tag_bytes, value_bytes in self._unknown_fields:
1120        size += len(tag_bytes) + len(value_bytes)
1121
1122    self._cached_byte_size = size
1123    self._cached_byte_size_dirty = False
1124    self._listener_for_children.dirty = False
1125    return size

Returns the serialized size of this message.

Recursively calls ByteSize() on all contained messages.

Returns:

int: The number of bytes required to serialize this message.

def FromString(s):
826  def FromString(s):
827    message = cls()
828    message.MergeFromString(s)
829    return message
CAPACITY_FIELD_NUMBER = 1
capacity
767  def getter(self):
768    field_value = self._fields.get(field)
769    if field_value is None:
770      # Construct a new object to represent this field.
771      field_value = field._default_constructor(self)
772
773      # Atomically check if another thread has preempted us and, if not, swap
774      # in the new object we just created.  If someone has preempted us, we
775      # take that object and discard ours.
776      # WARNING:  We are relying on setdefault() being atomic.  This is true
777      #   in CPython but we haven't investigated others.  This warning appears
778      #   in several other locations in this file.
779      field_value = self._fields.setdefault(field, field_value)
780    return field_value

Getter for capacity.

INTERVALS_FIELD_NUMBER = 2
intervals
668  def getter(self):
669    field_value = self._fields.get(field)
670    if field_value is None:
671      # Construct a new object to represent this field.
672      field_value = field._default_constructor(self)
673
674      # Atomically check if another thread has preempted us and, if not, swap
675      # in the new object we just created.  If someone has preempted us, we
676      # take that object and discard ours.
677      # WARNING:  We are relying on setdefault() being atomic.  This is true
678      #   in CPython but we haven't investigated others.  This warning appears
679      #   in several other locations in this file.
680      field_value = self._fields.setdefault(field, field_value)
681    return field_value

Getter for intervals.

DEMANDS_FIELD_NUMBER = 3
demands
668  def getter(self):
669    field_value = self._fields.get(field)
670    if field_value is None:
671      # Construct a new object to represent this field.
672      field_value = field._default_constructor(self)
673
674      # Atomically check if another thread has preempted us and, if not, swap
675      # in the new object we just created.  If someone has preempted us, we
676      # take that object and discard ours.
677      # WARNING:  We are relying on setdefault() being atomic.  This is true
678      #   in CPython but we haven't investigated others.  This warning appears
679      #   in several other locations in this file.
680      field_value = self._fields.setdefault(field, field_value)
681    return field_value

Getter for demands.

def FindInitializationErrors(self):
1305  def FindInitializationErrors(self):
1306    """Finds required fields which are not initialized.
1307
1308    Returns:
1309      A list of strings.  Each string is a path to an uninitialized field from
1310      the top-level message, e.g. "foo.bar[5].baz".
1311    """
1312
1313    errors = []  # simplify things
1314
1315    for field in required_fields:
1316      if not self.HasField(field.name):
1317        errors.append(field.name)
1318
1319    for field, value in self.ListFields():
1320      if field.cpp_type == _FieldDescriptor.CPPTYPE_MESSAGE:
1321        if field.is_extension:
1322          name = '(%s)' % field.full_name
1323        else:
1324          name = field.name
1325
1326        if _IsMapField(field):
1327          if _IsMessageMapField(field):
1328            for key in value:
1329              element = value[key]
1330              prefix = '%s[%s].' % (name, key)
1331              sub_errors = element.FindInitializationErrors()
1332              errors += [prefix + error for error in sub_errors]
1333          else:
1334            # ScalarMaps can't have any initialization errors.
1335            pass
1336        elif field.label == _FieldDescriptor.LABEL_REPEATED:
1337          for i in range(len(value)):
1338            element = value[i]
1339            prefix = '%s[%d].' % (name, i)
1340            sub_errors = element.FindInitializationErrors()
1341            errors += [prefix + error for error in sub_errors]
1342        else:
1343          prefix = name + '.'
1344          sub_errors = value.FindInitializationErrors()
1345          errors += [prefix + error for error in sub_errors]
1346
1347    return errors

Finds required fields which are not initialized.

Returns:

A list of strings. Each string is a path to an uninitialized field from the top-level message, e.g. "foo.bar[5].baz".

class ReservoirConstraintProto(google.protobuf.message.Message):

Abstract base class for protocol messages.

Protocol message classes are almost always generated by the protocol compiler. These generated types subclass Message and implement the methods shown below.

ReservoirConstraintProto(**kwargs)
498  def init(self, **kwargs):
499    self._cached_byte_size = 0
500    self._cached_byte_size_dirty = len(kwargs) > 0
501    self._fields = {}
502    # Contains a mapping from oneof field descriptors to the descriptor
503    # of the currently set field in that oneof field.
504    self._oneofs = {}
505
506    # _unknown_fields is () when empty for efficiency, and will be turned into
507    # a list if fields are added.
508    self._unknown_fields = ()
509    self._is_present_in_parent = False
510    self._listener = message_listener_mod.NullMessageListener()
511    self._listener_for_children = _Listener(self)
512    for field_name, field_value in kwargs.items():
513      field = _GetFieldByName(message_descriptor, field_name)
514      if field is None:
515        raise TypeError('%s() got an unexpected keyword argument "%s"' %
516                        (message_descriptor.name, field_name))
517      if field_value is None:
518        # field=None is the same as no field at all.
519        continue
520      if field.label == _FieldDescriptor.LABEL_REPEATED:
521        field_copy = field._default_constructor(self)
522        if field.cpp_type == _FieldDescriptor.CPPTYPE_MESSAGE:  # Composite
523          if _IsMapField(field):
524            if _IsMessageMapField(field):
525              for key in field_value:
526                field_copy[key].MergeFrom(field_value[key])
527            else:
528              field_copy.update(field_value)
529          else:
530            for val in field_value:
531              if isinstance(val, dict):
532                field_copy.add(**val)
533              else:
534                field_copy.add().MergeFrom(val)
535        else:  # Scalar
536          if field.cpp_type == _FieldDescriptor.CPPTYPE_ENUM:
537            field_value = [_GetIntegerEnumValue(field.enum_type, val)
538                           for val in field_value]
539          field_copy.extend(field_value)
540        self._fields[field] = field_copy
541      elif field.cpp_type == _FieldDescriptor.CPPTYPE_MESSAGE:
542        field_copy = field._default_constructor(self)
543        new_val = None
544        if isinstance(field_value, message_mod.Message):
545          new_val = field_value
546        elif isinstance(field_value, dict):
547          if field.message_type.full_name == _StructFullTypeName:
548            field_copy.Clear()
549            if len(field_value) == 1 and 'fields' in field_value:
550              try:
551                field_copy.update(field_value)
552              except:
553                # Fall back to init normal message field
554                field_copy.Clear()
555                new_val = field.message_type._concrete_class(**field_value)
556            else:
557              field_copy.update(field_value)
558          else:
559            new_val = field.message_type._concrete_class(**field_value)
560        elif hasattr(field_copy, '_internal_assign'):
561          field_copy._internal_assign(field_value)
562        else:
563          raise TypeError(
564              'Message field {0}.{1} must be initialized with a '
565              'dict or instance of same class, got {2}.'.format(
566                  message_descriptor.name,
567                  field_name,
568                  type(field_value).__name__,
569              )
570          )
571
572        if new_val != None:
573          try:
574            field_copy.MergeFrom(new_val)
575          except TypeError:
576            _ReraiseTypeErrorWithFieldName(message_descriptor.name, field_name)
577        self._fields[field] = field_copy
578      else:
579        if field.cpp_type == _FieldDescriptor.CPPTYPE_ENUM:
580          field_value = _GetIntegerEnumValue(field.enum_type, field_value)
581        try:
582          setattr(self, field_name, field_value)
583        except TypeError:
584          _ReraiseTypeErrorWithFieldName(message_descriptor.name, field_name)
DESCRIPTOR = <google.protobuf.descriptor.Descriptor object>
def MergeFrom(self, msg):
1364  def MergeFrom(self, msg):
1365    if not isinstance(msg, cls):
1366      raise TypeError(
1367          'Parameter to MergeFrom() must be instance of same class: '
1368          'expected %s got %s.' % (_FullyQualifiedClassName(cls),
1369                                   _FullyQualifiedClassName(msg.__class__)))
1370
1371    assert msg is not self
1372    self._Modified()
1373
1374    fields = self._fields
1375
1376    for field, value in msg._fields.items():
1377      if field.label == LABEL_REPEATED:
1378        field_value = fields.get(field)
1379        if field_value is None:
1380          # Construct a new object to represent this field.
1381          field_value = field._default_constructor(self)
1382          fields[field] = field_value
1383        field_value.MergeFrom(value)
1384      elif field.cpp_type == CPPTYPE_MESSAGE:
1385        if value._is_present_in_parent:
1386          field_value = fields.get(field)
1387          if field_value is None:
1388            # Construct a new object to represent this field.
1389            field_value = field._default_constructor(self)
1390            fields[field] = field_value
1391          field_value.MergeFrom(value)
1392      else:
1393        self._fields[field] = value
1394        if field.containing_oneof:
1395          self._UpdateOneofState(field)
1396
1397    if msg._unknown_fields:
1398      if not self._unknown_fields:
1399        self._unknown_fields = []
1400      self._unknown_fields.extend(msg._unknown_fields)

Merges the contents of the specified message into current message.

This method merges the contents of the specified message into the current message. Singular fields that are set in the specified message overwrite the corresponding fields in the current message. Repeated fields are appended. Singular sub-messages and groups are recursively merged.

Arguments:
  • other_msg (Message): A message to merge into the current message.
def Clear(self):
1423def _Clear(self):
1424  # Clear fields.
1425  self._fields = {}
1426  self._unknown_fields = ()
1427
1428  self._oneofs = {}
1429  self._Modified()

Clears all data that was set in the message.

def SetInParent(self):
1489  def Modified(self):
1490    """Sets the _cached_byte_size_dirty bit to true,
1491    and propagates this to our listener iff this was a state change.
1492    """
1493
1494    # Note:  Some callers check _cached_byte_size_dirty before calling
1495    #   _Modified() as an extra optimization.  So, if this method is ever
1496    #   changed such that it does stuff even when _cached_byte_size_dirty is
1497    #   already true, the callers need to be updated.
1498    if not self._cached_byte_size_dirty:
1499      self._cached_byte_size_dirty = True
1500      self._listener_for_children.dirty = True
1501      self._is_present_in_parent = True
1502      self._listener.Modified()

Sets the _cached_byte_size_dirty bit to true, and propagates this to our listener iff this was a state change.

def IsInitialized(self, errors=None):
1265  def IsInitialized(self, errors=None):
1266    """Checks if all required fields of a message are set.
1267
1268    Args:
1269      errors:  A list which, if provided, will be populated with the field
1270               paths of all missing required fields.
1271
1272    Returns:
1273      True iff the specified message has all required fields set.
1274    """
1275
1276    # Performance is critical so we avoid HasField() and ListFields().
1277
1278    for field in required_fields:
1279      if (field not in self._fields or
1280          (field.cpp_type == _FieldDescriptor.CPPTYPE_MESSAGE and
1281           not self._fields[field]._is_present_in_parent)):
1282        if errors is not None:
1283          errors.extend(self.FindInitializationErrors())
1284        return False
1285
1286    for field, value in list(self._fields.items()):  # dict can change size!
1287      if field.cpp_type == _FieldDescriptor.CPPTYPE_MESSAGE:
1288        if field.label == _FieldDescriptor.LABEL_REPEATED:
1289          if (field.message_type._is_map_entry):
1290            continue
1291          for element in value:
1292            if not element.IsInitialized():
1293              if errors is not None:
1294                errors.extend(self.FindInitializationErrors())
1295              return False
1296        elif value._is_present_in_parent and not value.IsInitialized():
1297          if errors is not None:
1298            errors.extend(self.FindInitializationErrors())
1299          return False
1300
1301    return True

Checks if all required fields of a message are set.

Arguments:
  • errors: A list which, if provided, will be populated with the field paths of all missing required fields.
Returns:

True iff the specified message has all required fields set.

def MergeFromString(self, serialized):
1180  def MergeFromString(self, serialized):
1181    serialized = memoryview(serialized)
1182    length = len(serialized)
1183    try:
1184      if self._InternalParse(serialized, 0, length) != length:
1185        # The only reason _InternalParse would return early is if it
1186        # encountered an end-group tag.
1187        raise message_mod.DecodeError('Unexpected end-group tag.')
1188    except (IndexError, TypeError):
1189      # Now ord(buf[p:p+1]) == ord('') gets TypeError.
1190      raise message_mod.DecodeError('Truncated message.')
1191    except struct.error as e:
1192      raise message_mod.DecodeError(e)
1193    return length   # Return this for legacy reasons.

Merges serialized protocol buffer data into this message.

When we find a field in serialized that is already present in this message:

  • If it's a "repeated" field, we append to the end of our list.
  • Else, if it's a scalar, we overwrite our field.
  • Else, (it's a nonrepeated composite), we recursively merge into the existing composite.
Arguments:
  • serialized (bytes): Any object that allows us to call memoryview(serialized) to access a string of bytes using the buffer interface.
Returns:

int: The number of bytes read from serialized. For non-group messages, this will always be len(serialized), but for messages which are actually groups, this will generally be less than len(serialized), since we must stop when we reach an END_GROUP tag. Note that if we do stop because of an END_GROUP tag, the number of bytes returned does not include the bytes for the END_GROUP tag information.

Raises:
  • DecodeError: if the input cannot be parsed.
def SerializeToString(self, **kwargs):
1133  def SerializeToString(self, **kwargs):
1134    # Check if the message has all of its required fields set.
1135    if not self.IsInitialized():
1136      raise message_mod.EncodeError(
1137          'Message %s is missing required fields: %s' % (
1138          self.DESCRIPTOR.full_name, ','.join(self.FindInitializationErrors())))
1139    return self.SerializePartialToString(**kwargs)

Serializes the protocol message to a binary string.

Keyword Args:

deterministic (bool): If true, requests deterministic serialization of the protobuf, with predictable ordering of map keys.

Returns:

A binary string representation of the message if all of the required fields in the message are set (i.e. the message is initialized).

Raises:
def SerializePartialToString(self, **kwargs):
1146  def SerializePartialToString(self, **kwargs):
1147    out = BytesIO()
1148    self._InternalSerialize(out.write, **kwargs)
1149    return out.getvalue()

Serializes the protocol message to a binary string.

This method is similar to SerializeToString but doesn't check if the message is initialized.

Keyword Args:

deterministic (bool): If true, requests deterministic serialization of the protobuf, with predictable ordering of map keys.

Returns:

bytes: A serialized representation of the partial message.

def ListFields(self):
848  def ListFields(self):
849    all_fields = [item for item in self._fields.items() if _IsPresent(item)]
850    all_fields.sort(key = lambda item: item[0].number)
851    return all_fields

Returns a list of (FieldDescriptor, value) tuples for present fields.

A message field is non-empty if HasField() would return true. A singular primitive field is non-empty if HasField() would return true in proto2 or it is non zero in proto3. A repeated field is non-empty if it contains at least one element. The fields are ordered by field number.

Returns:

list[tuple(FieldDescriptor, value)]: field descriptors and values for all fields in the message which are not empty. The values vary by field type.

def HasField(self, field_name):
872  def HasField(self, field_name):
873    try:
874      field = hassable_fields[field_name]
875    except KeyError as exc:
876      raise ValueError('Protocol message %s has no non-repeated field "%s" '
877                       'nor has presence is not available for this field.' % (
878                           message_descriptor.full_name, field_name)) from exc
879
880    if isinstance(field, descriptor_mod.OneofDescriptor):
881      try:
882        return HasField(self, self._oneofs[field].name)
883      except KeyError:
884        return False
885    else:
886      if field.cpp_type == _FieldDescriptor.CPPTYPE_MESSAGE:
887        value = self._fields.get(field)
888        return value is not None and value._is_present_in_parent
889      else:
890        return field in self._fields

Checks if a certain field is set for the message.

For a oneof group, checks if any field inside is set. Note that if the field_name is not defined in the message descriptor, ValueError will be raised.

Arguments:
  • field_name (str): The name of the field to check for presence.
Returns:

bool: Whether a value has been set for the named field.

Raises:
  • ValueError: if the field_name is not a member of this message.
def ClearField(self, field_name):
897  def ClearField(self, field_name):
898    try:
899      field = message_descriptor.fields_by_name[field_name]
900    except KeyError:
901      try:
902        field = message_descriptor.oneofs_by_name[field_name]
903        if field in self._oneofs:
904          field = self._oneofs[field]
905        else:
906          return
907      except KeyError:
908        raise ValueError('Protocol message %s has no "%s" field.' %
909                         (message_descriptor.name, field_name))
910
911    if field in self._fields:
912      # To match the C++ implementation, we need to invalidate iterators
913      # for map fields when ClearField() happens.
914      if hasattr(self._fields[field], 'InvalidateIterators'):
915        self._fields[field].InvalidateIterators()
916
917      # Note:  If the field is a sub-message, its listener will still point
918      #   at us.  That's fine, because the worst than can happen is that it
919      #   will call _Modified() and invalidate our byte size.  Big deal.
920      del self._fields[field]
921
922      if self._oneofs.get(field.containing_oneof, None) is field:
923        del self._oneofs[field.containing_oneof]
924
925    # Always call _Modified() -- even if nothing was changed, this is
926    # a mutating method, and thus calling it should cause the field to become
927    # present in the parent message.
928    self._Modified()

Clears the contents of a given field.

Inside a oneof group, clears the field set. If the name neither refers to a defined field or oneof group, ValueError is raised.

Arguments:
  • field_name (str): The name of the field to check for presence.
Raises:
  • ValueError: if the field_name is not a member of this message.
def WhichOneof(self, oneof_name):
1406  def WhichOneof(self, oneof_name):
1407    """Returns the name of the currently set field inside a oneof, or None."""
1408    try:
1409      field = message_descriptor.oneofs_by_name[oneof_name]
1410    except KeyError:
1411      raise ValueError(
1412          'Protocol message has no oneof "%s" field.' % oneof_name)
1413
1414    nested_field = self._oneofs.get(field, None)
1415    if nested_field is not None and self.HasField(nested_field.name):
1416      return nested_field.name
1417    else:
1418      return None

Returns the name of the currently set field inside a oneof, or None.

def DiscardUnknownFields(self):
1438def _DiscardUnknownFields(self):
1439  self._unknown_fields = []
1440  for field, value in self.ListFields():
1441    if field.cpp_type == _FieldDescriptor.CPPTYPE_MESSAGE:
1442      if _IsMapField(field):
1443        if _IsMessageMapField(field):
1444          for key in value:
1445            value[key].DiscardUnknownFields()
1446      elif field.label == _FieldDescriptor.LABEL_REPEATED:
1447        for sub_message in value:
1448          sub_message.DiscardUnknownFields()
1449      else:
1450        value.DiscardUnknownFields()

Clears all fields in the UnknownFieldSet.

This operation is recursive for nested message.

def ByteSize(self):
1101  def ByteSize(self):
1102    if not self._cached_byte_size_dirty:
1103      return self._cached_byte_size
1104
1105    size = 0
1106    descriptor = self.DESCRIPTOR
1107    if descriptor._is_map_entry:
1108      # Fields of map entry should always be serialized.
1109      key_field = descriptor.fields_by_name['key']
1110      _MaybeAddEncoder(cls, key_field)
1111      size = key_field._sizer(self.key)
1112      value_field = descriptor.fields_by_name['value']
1113      _MaybeAddEncoder(cls, value_field)
1114      size += value_field._sizer(self.value)
1115    else:
1116      for field_descriptor, field_value in self.ListFields():
1117        _MaybeAddEncoder(cls, field_descriptor)
1118        size += field_descriptor._sizer(field_value)
1119      for tag_bytes, value_bytes in self._unknown_fields:
1120        size += len(tag_bytes) + len(value_bytes)
1121
1122    self._cached_byte_size = size
1123    self._cached_byte_size_dirty = False
1124    self._listener_for_children.dirty = False
1125    return size

Returns the serialized size of this message.

Recursively calls ByteSize() on all contained messages.

Returns:

int: The number of bytes required to serialize this message.

def FromString(s):
826  def FromString(s):
827    message = cls()
828    message.MergeFromString(s)
829    return message
MIN_LEVEL_FIELD_NUMBER = 1
min_level
711  def getter(self):
712    # TODO: This may be broken since there may not be
713    # default_value.  Combine with has_default_value somehow.
714    return self._fields.get(field, default_value)

Getter for min_level.

MAX_LEVEL_FIELD_NUMBER = 2
max_level
711  def getter(self):
712    # TODO: This may be broken since there may not be
713    # default_value.  Combine with has_default_value somehow.
714    return self._fields.get(field, default_value)

Getter for max_level.

TIME_EXPRS_FIELD_NUMBER = 3
time_exprs
668  def getter(self):
669    field_value = self._fields.get(field)
670    if field_value is None:
671      # Construct a new object to represent this field.
672      field_value = field._default_constructor(self)
673
674      # Atomically check if another thread has preempted us and, if not, swap
675      # in the new object we just created.  If someone has preempted us, we
676      # take that object and discard ours.
677      # WARNING:  We are relying on setdefault() being atomic.  This is true
678      #   in CPython but we haven't investigated others.  This warning appears
679      #   in several other locations in this file.
680      field_value = self._fields.setdefault(field, field_value)
681    return field_value

Getter for time_exprs.

LEVEL_CHANGES_FIELD_NUMBER = 6
level_changes
668  def getter(self):
669    field_value = self._fields.get(field)
670    if field_value is None:
671      # Construct a new object to represent this field.
672      field_value = field._default_constructor(self)
673
674      # Atomically check if another thread has preempted us and, if not, swap
675      # in the new object we just created.  If someone has preempted us, we
676      # take that object and discard ours.
677      # WARNING:  We are relying on setdefault() being atomic.  This is true
678      #   in CPython but we haven't investigated others.  This warning appears
679      #   in several other locations in this file.
680      field_value = self._fields.setdefault(field, field_value)
681    return field_value

Getter for level_changes.

ACTIVE_LITERALS_FIELD_NUMBER = 5
active_literals
668  def getter(self):
669    field_value = self._fields.get(field)
670    if field_value is None:
671      # Construct a new object to represent this field.
672      field_value = field._default_constructor(self)
673
674      # Atomically check if another thread has preempted us and, if not, swap
675      # in the new object we just created.  If someone has preempted us, we
676      # take that object and discard ours.
677      # WARNING:  We are relying on setdefault() being atomic.  This is true
678      #   in CPython but we haven't investigated others.  This warning appears
679      #   in several other locations in this file.
680      field_value = self._fields.setdefault(field, field_value)
681    return field_value

Getter for active_literals.

def FindInitializationErrors(self):
1305  def FindInitializationErrors(self):
1306    """Finds required fields which are not initialized.
1307
1308    Returns:
1309      A list of strings.  Each string is a path to an uninitialized field from
1310      the top-level message, e.g. "foo.bar[5].baz".
1311    """
1312
1313    errors = []  # simplify things
1314
1315    for field in required_fields:
1316      if not self.HasField(field.name):
1317        errors.append(field.name)
1318
1319    for field, value in self.ListFields():
1320      if field.cpp_type == _FieldDescriptor.CPPTYPE_MESSAGE:
1321        if field.is_extension:
1322          name = '(%s)' % field.full_name
1323        else:
1324          name = field.name
1325
1326        if _IsMapField(field):
1327          if _IsMessageMapField(field):
1328            for key in value:
1329              element = value[key]
1330              prefix = '%s[%s].' % (name, key)
1331              sub_errors = element.FindInitializationErrors()
1332              errors += [prefix + error for error in sub_errors]
1333          else:
1334            # ScalarMaps can't have any initialization errors.
1335            pass
1336        elif field.label == _FieldDescriptor.LABEL_REPEATED:
1337          for i in range(len(value)):
1338            element = value[i]
1339            prefix = '%s[%d].' % (name, i)
1340            sub_errors = element.FindInitializationErrors()
1341            errors += [prefix + error for error in sub_errors]
1342        else:
1343          prefix = name + '.'
1344          sub_errors = value.FindInitializationErrors()
1345          errors += [prefix + error for error in sub_errors]
1346
1347    return errors

Finds required fields which are not initialized.

Returns:

A list of strings. Each string is a path to an uninitialized field from the top-level message, e.g. "foo.bar[5].baz".

class CircuitConstraintProto(google.protobuf.message.Message):

Abstract base class for protocol messages.

Protocol message classes are almost always generated by the protocol compiler. These generated types subclass Message and implement the methods shown below.

CircuitConstraintProto(**kwargs)
498  def init(self, **kwargs):
499    self._cached_byte_size = 0
500    self._cached_byte_size_dirty = len(kwargs) > 0
501    self._fields = {}
502    # Contains a mapping from oneof field descriptors to the descriptor
503    # of the currently set field in that oneof field.
504    self._oneofs = {}
505
506    # _unknown_fields is () when empty for efficiency, and will be turned into
507    # a list if fields are added.
508    self._unknown_fields = ()
509    self._is_present_in_parent = False
510    self._listener = message_listener_mod.NullMessageListener()
511    self._listener_for_children = _Listener(self)
512    for field_name, field_value in kwargs.items():
513      field = _GetFieldByName(message_descriptor, field_name)
514      if field is None:
515        raise TypeError('%s() got an unexpected keyword argument "%s"' %
516                        (message_descriptor.name, field_name))
517      if field_value is None:
518        # field=None is the same as no field at all.
519        continue
520      if field.label == _FieldDescriptor.LABEL_REPEATED:
521        field_copy = field._default_constructor(self)
522        if field.cpp_type == _FieldDescriptor.CPPTYPE_MESSAGE:  # Composite
523          if _IsMapField(field):
524            if _IsMessageMapField(field):
525              for key in field_value:
526                field_copy[key].MergeFrom(field_value[key])
527            else:
528              field_copy.update(field_value)
529          else:
530            for val in field_value:
531              if isinstance(val, dict):
532                field_copy.add(**val)
533              else:
534                field_copy.add().MergeFrom(val)
535        else:  # Scalar
536          if field.cpp_type == _FieldDescriptor.CPPTYPE_ENUM:
537            field_value = [_GetIntegerEnumValue(field.enum_type, val)
538                           for val in field_value]
539          field_copy.extend(field_value)
540        self._fields[field] = field_copy
541      elif field.cpp_type == _FieldDescriptor.CPPTYPE_MESSAGE:
542        field_copy = field._default_constructor(self)
543        new_val = None
544        if isinstance(field_value, message_mod.Message):
545          new_val = field_value
546        elif isinstance(field_value, dict):
547          if field.message_type.full_name == _StructFullTypeName:
548            field_copy.Clear()
549            if len(field_value) == 1 and 'fields' in field_value:
550              try:
551                field_copy.update(field_value)
552              except:
553                # Fall back to init normal message field
554                field_copy.Clear()
555                new_val = field.message_type._concrete_class(**field_value)
556            else:
557              field_copy.update(field_value)
558          else:
559            new_val = field.message_type._concrete_class(**field_value)
560        elif hasattr(field_copy, '_internal_assign'):
561          field_copy._internal_assign(field_value)
562        else:
563          raise TypeError(
564              'Message field {0}.{1} must be initialized with a '
565              'dict or instance of same class, got {2}.'.format(
566                  message_descriptor.name,
567                  field_name,
568                  type(field_value).__name__,
569              )
570          )
571
572        if new_val != None:
573          try:
574            field_copy.MergeFrom(new_val)
575          except TypeError:
576            _ReraiseTypeErrorWithFieldName(message_descriptor.name, field_name)
577        self._fields[field] = field_copy
578      else:
579        if field.cpp_type == _FieldDescriptor.CPPTYPE_ENUM:
580          field_value = _GetIntegerEnumValue(field.enum_type, field_value)
581        try:
582          setattr(self, field_name, field_value)
583        except TypeError:
584          _ReraiseTypeErrorWithFieldName(message_descriptor.name, field_name)
DESCRIPTOR = <google.protobuf.descriptor.Descriptor object>
def MergeFrom(self, msg):
1364  def MergeFrom(self, msg):
1365    if not isinstance(msg, cls):
1366      raise TypeError(
1367          'Parameter to MergeFrom() must be instance of same class: '
1368          'expected %s got %s.' % (_FullyQualifiedClassName(cls),
1369                                   _FullyQualifiedClassName(msg.__class__)))
1370
1371    assert msg is not self
1372    self._Modified()
1373
1374    fields = self._fields
1375
1376    for field, value in msg._fields.items():
1377      if field.label == LABEL_REPEATED:
1378        field_value = fields.get(field)
1379        if field_value is None:
1380          # Construct a new object to represent this field.
1381          field_value = field._default_constructor(self)
1382          fields[field] = field_value
1383        field_value.MergeFrom(value)
1384      elif field.cpp_type == CPPTYPE_MESSAGE:
1385        if value._is_present_in_parent:
1386          field_value = fields.get(field)
1387          if field_value is None:
1388            # Construct a new object to represent this field.
1389            field_value = field._default_constructor(self)
1390            fields[field] = field_value
1391          field_value.MergeFrom(value)
1392      else:
1393        self._fields[field] = value
1394        if field.containing_oneof:
1395          self._UpdateOneofState(field)
1396
1397    if msg._unknown_fields:
1398      if not self._unknown_fields:
1399        self._unknown_fields = []
1400      self._unknown_fields.extend(msg._unknown_fields)

Merges the contents of the specified message into current message.

This method merges the contents of the specified message into the current message. Singular fields that are set in the specified message overwrite the corresponding fields in the current message. Repeated fields are appended. Singular sub-messages and groups are recursively merged.

Arguments:
  • other_msg (Message): A message to merge into the current message.
def Clear(self):
1423def _Clear(self):
1424  # Clear fields.
1425  self._fields = {}
1426  self._unknown_fields = ()
1427
1428  self._oneofs = {}
1429  self._Modified()

Clears all data that was set in the message.

def SetInParent(self):
1489  def Modified(self):
1490    """Sets the _cached_byte_size_dirty bit to true,
1491    and propagates this to our listener iff this was a state change.
1492    """
1493
1494    # Note:  Some callers check _cached_byte_size_dirty before calling
1495    #   _Modified() as an extra optimization.  So, if this method is ever
1496    #   changed such that it does stuff even when _cached_byte_size_dirty is
1497    #   already true, the callers need to be updated.
1498    if not self._cached_byte_size_dirty:
1499      self._cached_byte_size_dirty = True
1500      self._listener_for_children.dirty = True
1501      self._is_present_in_parent = True
1502      self._listener.Modified()

Sets the _cached_byte_size_dirty bit to true, and propagates this to our listener iff this was a state change.

def IsInitialized(self, errors=None):
1265  def IsInitialized(self, errors=None):
1266    """Checks if all required fields of a message are set.
1267
1268    Args:
1269      errors:  A list which, if provided, will be populated with the field
1270               paths of all missing required fields.
1271
1272    Returns:
1273      True iff the specified message has all required fields set.
1274    """
1275
1276    # Performance is critical so we avoid HasField() and ListFields().
1277
1278    for field in required_fields:
1279      if (field not in self._fields or
1280          (field.cpp_type == _FieldDescriptor.CPPTYPE_MESSAGE and
1281           not self._fields[field]._is_present_in_parent)):
1282        if errors is not None:
1283          errors.extend(self.FindInitializationErrors())
1284        return False
1285
1286    for field, value in list(self._fields.items()):  # dict can change size!
1287      if field.cpp_type == _FieldDescriptor.CPPTYPE_MESSAGE:
1288        if field.label == _FieldDescriptor.LABEL_REPEATED:
1289          if (field.message_type._is_map_entry):
1290            continue
1291          for element in value:
1292            if not element.IsInitialized():
1293              if errors is not None:
1294                errors.extend(self.FindInitializationErrors())
1295              return False
1296        elif value._is_present_in_parent and not value.IsInitialized():
1297          if errors is not None:
1298            errors.extend(self.FindInitializationErrors())
1299          return False
1300
1301    return True

Checks if all required fields of a message are set.

Arguments:
  • errors: A list which, if provided, will be populated with the field paths of all missing required fields.
Returns:

True iff the specified message has all required fields set.

def MergeFromString(self, serialized):
1180  def MergeFromString(self, serialized):
1181    serialized = memoryview(serialized)
1182    length = len(serialized)
1183    try:
1184      if self._InternalParse(serialized, 0, length) != length:
1185        # The only reason _InternalParse would return early is if it
1186        # encountered an end-group tag.
1187        raise message_mod.DecodeError('Unexpected end-group tag.')
1188    except (IndexError, TypeError):
1189      # Now ord(buf[p:p+1]) == ord('') gets TypeError.
1190      raise message_mod.DecodeError('Truncated message.')
1191    except struct.error as e:
1192      raise message_mod.DecodeError(e)
1193    return length   # Return this for legacy reasons.

Merges serialized protocol buffer data into this message.

When we find a field in serialized that is already present in this message:

  • If it's a "repeated" field, we append to the end of our list.
  • Else, if it's a scalar, we overwrite our field.
  • Else, (it's a nonrepeated composite), we recursively merge into the existing composite.
Arguments:
  • serialized (bytes): Any object that allows us to call memoryview(serialized) to access a string of bytes using the buffer interface.
Returns:

int: The number of bytes read from serialized. For non-group messages, this will always be len(serialized), but for messages which are actually groups, this will generally be less than len(serialized), since we must stop when we reach an END_GROUP tag. Note that if we do stop because of an END_GROUP tag, the number of bytes returned does not include the bytes for the END_GROUP tag information.

Raises:
  • DecodeError: if the input cannot be parsed.
def SerializeToString(self, **kwargs):
1133  def SerializeToString(self, **kwargs):
1134    # Check if the message has all of its required fields set.
1135    if not self.IsInitialized():
1136      raise message_mod.EncodeError(
1137          'Message %s is missing required fields: %s' % (
1138          self.DESCRIPTOR.full_name, ','.join(self.FindInitializationErrors())))
1139    return self.SerializePartialToString(**kwargs)

Serializes the protocol message to a binary string.

Keyword Args:

deterministic (bool): If true, requests deterministic serialization of the protobuf, with predictable ordering of map keys.

Returns:

A binary string representation of the message if all of the required fields in the message are set (i.e. the message is initialized).

Raises:
def SerializePartialToString(self, **kwargs):
1146  def SerializePartialToString(self, **kwargs):
1147    out = BytesIO()
1148    self._InternalSerialize(out.write, **kwargs)
1149    return out.getvalue()

Serializes the protocol message to a binary string.

This method is similar to SerializeToString but doesn't check if the message is initialized.

Keyword Args:

deterministic (bool): If true, requests deterministic serialization of the protobuf, with predictable ordering of map keys.

Returns:

bytes: A serialized representation of the partial message.

def ListFields(self):
848  def ListFields(self):
849    all_fields = [item for item in self._fields.items() if _IsPresent(item)]
850    all_fields.sort(key = lambda item: item[0].number)
851    return all_fields

Returns a list of (FieldDescriptor, value) tuples for present fields.

A message field is non-empty if HasField() would return true. A singular primitive field is non-empty if HasField() would return true in proto2 or it is non zero in proto3. A repeated field is non-empty if it contains at least one element. The fields are ordered by field number.

Returns:

list[tuple(FieldDescriptor, value)]: field descriptors and values for all fields in the message which are not empty. The values vary by field type.

def HasField(self, field_name):
872  def HasField(self, field_name):
873    try:
874      field = hassable_fields[field_name]
875    except KeyError as exc:
876      raise ValueError('Protocol message %s has no non-repeated field "%s" '
877                       'nor has presence is not available for this field.' % (
878                           message_descriptor.full_name, field_name)) from exc
879
880    if isinstance(field, descriptor_mod.OneofDescriptor):
881      try:
882        return HasField(self, self._oneofs[field].name)
883      except KeyError:
884        return False
885    else:
886      if field.cpp_type == _FieldDescriptor.CPPTYPE_MESSAGE:
887        value = self._fields.get(field)
888        return value is not None and value._is_present_in_parent
889      else:
890        return field in self._fields

Checks if a certain field is set for the message.

For a oneof group, checks if any field inside is set. Note that if the field_name is not defined in the message descriptor, ValueError will be raised.

Arguments:
  • field_name (str): The name of the field to check for presence.
Returns:

bool: Whether a value has been set for the named field.

Raises:
  • ValueError: if the field_name is not a member of this message.
def ClearField(self, field_name):
897  def ClearField(self, field_name):
898    try:
899      field = message_descriptor.fields_by_name[field_name]
900    except KeyError:
901      try:
902        field = message_descriptor.oneofs_by_name[field_name]
903        if field in self._oneofs:
904          field = self._oneofs[field]
905        else:
906          return
907      except KeyError:
908        raise ValueError('Protocol message %s has no "%s" field.' %
909                         (message_descriptor.name, field_name))
910
911    if field in self._fields:
912      # To match the C++ implementation, we need to invalidate iterators
913      # for map fields when ClearField() happens.
914      if hasattr(self._fields[field], 'InvalidateIterators'):
915        self._fields[field].InvalidateIterators()
916
917      # Note:  If the field is a sub-message, its listener will still point
918      #   at us.  That's fine, because the worst than can happen is that it
919      #   will call _Modified() and invalidate our byte size.  Big deal.
920      del self._fields[field]
921
922      if self._oneofs.get(field.containing_oneof, None) is field:
923        del self._oneofs[field.containing_oneof]
924
925    # Always call _Modified() -- even if nothing was changed, this is
926    # a mutating method, and thus calling it should cause the field to become
927    # present in the parent message.
928    self._Modified()

Clears the contents of a given field.

Inside a oneof group, clears the field set. If the name neither refers to a defined field or oneof group, ValueError is raised.

Arguments:
  • field_name (str): The name of the field to check for presence.
Raises:
  • ValueError: if the field_name is not a member of this message.
def WhichOneof(self, oneof_name):
1406  def WhichOneof(self, oneof_name):
1407    """Returns the name of the currently set field inside a oneof, or None."""
1408    try:
1409      field = message_descriptor.oneofs_by_name[oneof_name]
1410    except KeyError:
1411      raise ValueError(
1412          'Protocol message has no oneof "%s" field.' % oneof_name)
1413
1414    nested_field = self._oneofs.get(field, None)
1415    if nested_field is not None and self.HasField(nested_field.name):
1416      return nested_field.name
1417    else:
1418      return None

Returns the name of the currently set field inside a oneof, or None.

def DiscardUnknownFields(self):
1438def _DiscardUnknownFields(self):
1439  self._unknown_fields = []
1440  for field, value in self.ListFields():
1441    if field.cpp_type == _FieldDescriptor.CPPTYPE_MESSAGE:
1442      if _IsMapField(field):
1443        if _IsMessageMapField(field):
1444          for key in value:
1445            value[key].DiscardUnknownFields()
1446      elif field.label == _FieldDescriptor.LABEL_REPEATED:
1447        for sub_message in value:
1448          sub_message.DiscardUnknownFields()
1449      else:
1450        value.DiscardUnknownFields()

Clears all fields in the UnknownFieldSet.

This operation is recursive for nested message.

def ByteSize(self):
1101  def ByteSize(self):
1102    if not self._cached_byte_size_dirty:
1103      return self._cached_byte_size
1104
1105    size = 0
1106    descriptor = self.DESCRIPTOR
1107    if descriptor._is_map_entry:
1108      # Fields of map entry should always be serialized.
1109      key_field = descriptor.fields_by_name['key']
1110      _MaybeAddEncoder(cls, key_field)
1111      size = key_field._sizer(self.key)
1112      value_field = descriptor.fields_by_name['value']
1113      _MaybeAddEncoder(cls, value_field)
1114      size += value_field._sizer(self.value)
1115    else:
1116      for field_descriptor, field_value in self.ListFields():
1117        _MaybeAddEncoder(cls, field_descriptor)
1118        size += field_descriptor._sizer(field_value)
1119      for tag_bytes, value_bytes in self._unknown_fields:
1120        size += len(tag_bytes) + len(value_bytes)
1121
1122    self._cached_byte_size = size
1123    self._cached_byte_size_dirty = False
1124    self._listener_for_children.dirty = False
1125    return size

Returns the serialized size of this message.

Recursively calls ByteSize() on all contained messages.

Returns:

int: The number of bytes required to serialize this message.

def FromString(s):
826  def FromString(s):
827    message = cls()
828    message.MergeFromString(s)
829    return message
TAILS_FIELD_NUMBER = 3
tails
668  def getter(self):
669    field_value = self._fields.get(field)
670    if field_value is None:
671      # Construct a new object to represent this field.
672      field_value = field._default_constructor(self)
673
674      # Atomically check if another thread has preempted us and, if not, swap
675      # in the new object we just created.  If someone has preempted us, we
676      # take that object and discard ours.
677      # WARNING:  We are relying on setdefault() being atomic.  This is true
678      #   in CPython but we haven't investigated others.  This warning appears
679      #   in several other locations in this file.
680      field_value = self._fields.setdefault(field, field_value)
681    return field_value

Getter for tails.

HEADS_FIELD_NUMBER = 4
heads
668  def getter(self):
669    field_value = self._fields.get(field)
670    if field_value is None:
671      # Construct a new object to represent this field.
672      field_value = field._default_constructor(self)
673
674      # Atomically check if another thread has preempted us and, if not, swap
675      # in the new object we just created.  If someone has preempted us, we
676      # take that object and discard ours.
677      # WARNING:  We are relying on setdefault() being atomic.  This is true
678      #   in CPython but we haven't investigated others.  This warning appears
679      #   in several other locations in this file.
680      field_value = self._fields.setdefault(field, field_value)
681    return field_value

Getter for heads.

LITERALS_FIELD_NUMBER = 5
literals
668  def getter(self):
669    field_value = self._fields.get(field)
670    if field_value is None:
671      # Construct a new object to represent this field.
672      field_value = field._default_constructor(self)
673
674      # Atomically check if another thread has preempted us and, if not, swap
675      # in the new object we just created.  If someone has preempted us, we
676      # take that object and discard ours.
677      # WARNING:  We are relying on setdefault() being atomic.  This is true
678      #   in CPython but we haven't investigated others.  This warning appears
679      #   in several other locations in this file.
680      field_value = self._fields.setdefault(field, field_value)
681    return field_value

Getter for literals.

def FindInitializationErrors(self):
1305  def FindInitializationErrors(self):
1306    """Finds required fields which are not initialized.
1307
1308    Returns:
1309      A list of strings.  Each string is a path to an uninitialized field from
1310      the top-level message, e.g. "foo.bar[5].baz".
1311    """
1312
1313    errors = []  # simplify things
1314
1315    for field in required_fields:
1316      if not self.HasField(field.name):
1317        errors.append(field.name)
1318
1319    for field, value in self.ListFields():
1320      if field.cpp_type == _FieldDescriptor.CPPTYPE_MESSAGE:
1321        if field.is_extension:
1322          name = '(%s)' % field.full_name
1323        else:
1324          name = field.name
1325
1326        if _IsMapField(field):
1327          if _IsMessageMapField(field):
1328            for key in value:
1329              element = value[key]
1330              prefix = '%s[%s].' % (name, key)
1331              sub_errors = element.FindInitializationErrors()
1332              errors += [prefix + error for error in sub_errors]
1333          else:
1334            # ScalarMaps can't have any initialization errors.
1335            pass
1336        elif field.label == _FieldDescriptor.LABEL_REPEATED:
1337          for i in range(len(value)):
1338            element = value[i]
1339            prefix = '%s[%d].' % (name, i)
1340            sub_errors = element.FindInitializationErrors()
1341            errors += [prefix + error for error in sub_errors]
1342        else:
1343          prefix = name + '.'
1344          sub_errors = value.FindInitializationErrors()
1345          errors += [prefix + error for error in sub_errors]
1346
1347    return errors

Finds required fields which are not initialized.

Returns:

A list of strings. Each string is a path to an uninitialized field from the top-level message, e.g. "foo.bar[5].baz".

class RoutesConstraintProto(google.protobuf.message.Message):

Abstract base class for protocol messages.

Protocol message classes are almost always generated by the protocol compiler. These generated types subclass Message and implement the methods shown below.

RoutesConstraintProto(**kwargs)
498  def init(self, **kwargs):
499    self._cached_byte_size = 0
500    self._cached_byte_size_dirty = len(kwargs) > 0
501    self._fields = {}
502    # Contains a mapping from oneof field descriptors to the descriptor
503    # of the currently set field in that oneof field.
504    self._oneofs = {}
505
506    # _unknown_fields is () when empty for efficiency, and will be turned into
507    # a list if fields are added.
508    self._unknown_fields = ()
509    self._is_present_in_parent = False
510    self._listener = message_listener_mod.NullMessageListener()
511    self._listener_for_children = _Listener(self)
512    for field_name, field_value in kwargs.items():
513      field = _GetFieldByName(message_descriptor, field_name)
514      if field is None:
515        raise TypeError('%s() got an unexpected keyword argument "%s"' %
516                        (message_descriptor.name, field_name))
517      if field_value is None:
518        # field=None is the same as no field at all.
519        continue
520      if field.label == _FieldDescriptor.LABEL_REPEATED:
521        field_copy = field._default_constructor(self)
522        if field.cpp_type == _FieldDescriptor.CPPTYPE_MESSAGE:  # Composite
523          if _IsMapField(field):
524            if _IsMessageMapField(field):
525              for key in field_value:
526                field_copy[key].MergeFrom(field_value[key])
527            else:
528              field_copy.update(field_value)
529          else:
530            for val in field_value:
531              if isinstance(val, dict):
532                field_copy.add(**val)
533              else:
534                field_copy.add().MergeFrom(val)
535        else:  # Scalar
536          if field.cpp_type == _FieldDescriptor.CPPTYPE_ENUM:
537            field_value = [_GetIntegerEnumValue(field.enum_type, val)
538                           for val in field_value]
539          field_copy.extend(field_value)
540        self._fields[field] = field_copy
541      elif field.cpp_type == _FieldDescriptor.CPPTYPE_MESSAGE:
542        field_copy = field._default_constructor(self)
543        new_val = None
544        if isinstance(field_value, message_mod.Message):
545          new_val = field_value
546        elif isinstance(field_value, dict):
547          if field.message_type.full_name == _StructFullTypeName:
548            field_copy.Clear()
549            if len(field_value) == 1 and 'fields' in field_value:
550              try:
551                field_copy.update(field_value)
552              except:
553                # Fall back to init normal message field
554                field_copy.Clear()
555                new_val = field.message_type._concrete_class(**field_value)
556            else:
557              field_copy.update(field_value)
558          else:
559            new_val = field.message_type._concrete_class(**field_value)
560        elif hasattr(field_copy, '_internal_assign'):
561          field_copy._internal_assign(field_value)
562        else:
563          raise TypeError(
564              'Message field {0}.{1} must be initialized with a '
565              'dict or instance of same class, got {2}.'.format(
566                  message_descriptor.name,
567                  field_name,
568                  type(field_value).__name__,
569              )
570          )
571
572        if new_val != None:
573          try:
574            field_copy.MergeFrom(new_val)
575          except TypeError:
576            _ReraiseTypeErrorWithFieldName(message_descriptor.name, field_name)
577        self._fields[field] = field_copy
578      else:
579        if field.cpp_type == _FieldDescriptor.CPPTYPE_ENUM:
580          field_value = _GetIntegerEnumValue(field.enum_type, field_value)
581        try:
582          setattr(self, field_name, field_value)
583        except TypeError:
584          _ReraiseTypeErrorWithFieldName(message_descriptor.name, field_name)
DESCRIPTOR = <google.protobuf.descriptor.Descriptor object>
def MergeFrom(self, msg):
1364  def MergeFrom(self, msg):
1365    if not isinstance(msg, cls):
1366      raise TypeError(
1367          'Parameter to MergeFrom() must be instance of same class: '
1368          'expected %s got %s.' % (_FullyQualifiedClassName(cls),
1369                                   _FullyQualifiedClassName(msg.__class__)))
1370
1371    assert msg is not self
1372    self._Modified()
1373
1374    fields = self._fields
1375
1376    for field, value in msg._fields.items():
1377      if field.label == LABEL_REPEATED:
1378        field_value = fields.get(field)
1379        if field_value is None:
1380          # Construct a new object to represent this field.
1381          field_value = field._default_constructor(self)
1382          fields[field] = field_value
1383        field_value.MergeFrom(value)
1384      elif field.cpp_type == CPPTYPE_MESSAGE:
1385        if value._is_present_in_parent:
1386          field_value = fields.get(field)
1387          if field_value is None:
1388            # Construct a new object to represent this field.
1389            field_value = field._default_constructor(self)
1390            fields[field] = field_value
1391          field_value.MergeFrom(value)
1392      else:
1393        self._fields[field] = value
1394        if field.containing_oneof:
1395          self._UpdateOneofState(field)
1396
1397    if msg._unknown_fields:
1398      if not self._unknown_fields:
1399        self._unknown_fields = []
1400      self._unknown_fields.extend(msg._unknown_fields)

Merges the contents of the specified message into current message.

This method merges the contents of the specified message into the current message. Singular fields that are set in the specified message overwrite the corresponding fields in the current message. Repeated fields are appended. Singular sub-messages and groups are recursively merged.

Arguments:
  • other_msg (Message): A message to merge into the current message.
def Clear(self):
1423def _Clear(self):
1424  # Clear fields.
1425  self._fields = {}
1426  self._unknown_fields = ()
1427
1428  self._oneofs = {}
1429  self._Modified()

Clears all data that was set in the message.

def SetInParent(self):
1489  def Modified(self):
1490    """Sets the _cached_byte_size_dirty bit to true,
1491    and propagates this to our listener iff this was a state change.
1492    """
1493
1494    # Note:  Some callers check _cached_byte_size_dirty before calling
1495    #   _Modified() as an extra optimization.  So, if this method is ever
1496    #   changed such that it does stuff even when _cached_byte_size_dirty is
1497    #   already true, the callers need to be updated.
1498    if not self._cached_byte_size_dirty:
1499      self._cached_byte_size_dirty = True
1500      self._listener_for_children.dirty = True
1501      self._is_present_in_parent = True
1502      self._listener.Modified()

Sets the _cached_byte_size_dirty bit to true, and propagates this to our listener iff this was a state change.

def IsInitialized(self, errors=None):
1265  def IsInitialized(self, errors=None):
1266    """Checks if all required fields of a message are set.
1267
1268    Args:
1269      errors:  A list which, if provided, will be populated with the field
1270               paths of all missing required fields.
1271
1272    Returns:
1273      True iff the specified message has all required fields set.
1274    """
1275
1276    # Performance is critical so we avoid HasField() and ListFields().
1277
1278    for field in required_fields:
1279      if (field not in self._fields or
1280          (field.cpp_type == _FieldDescriptor.CPPTYPE_MESSAGE and
1281           not self._fields[field]._is_present_in_parent)):
1282        if errors is not None:
1283          errors.extend(self.FindInitializationErrors())
1284        return False
1285
1286    for field, value in list(self._fields.items()):  # dict can change size!
1287      if field.cpp_type == _FieldDescriptor.CPPTYPE_MESSAGE:
1288        if field.label == _FieldDescriptor.LABEL_REPEATED:
1289          if (field.message_type._is_map_entry):
1290            continue
1291          for element in value:
1292            if not element.IsInitialized():
1293              if errors is not None:
1294                errors.extend(self.FindInitializationErrors())
1295              return False
1296        elif value._is_present_in_parent and not value.IsInitialized():
1297          if errors is not None:
1298            errors.extend(self.FindInitializationErrors())
1299          return False
1300
1301    return True

Checks if all required fields of a message are set.

Arguments:
  • errors: A list which, if provided, will be populated with the field paths of all missing required fields.
Returns:

True iff the specified message has all required fields set.

def MergeFromString(self, serialized):
1180  def MergeFromString(self, serialized):
1181    serialized = memoryview(serialized)
1182    length = len(serialized)
1183    try:
1184      if self._InternalParse(serialized, 0, length) != length:
1185        # The only reason _InternalParse would return early is if it
1186        # encountered an end-group tag.
1187        raise message_mod.DecodeError('Unexpected end-group tag.')
1188    except (IndexError, TypeError):
1189      # Now ord(buf[p:p+1]) == ord('') gets TypeError.
1190      raise message_mod.DecodeError('Truncated message.')
1191    except struct.error as e:
1192      raise message_mod.DecodeError(e)
1193    return length   # Return this for legacy reasons.

Merges serialized protocol buffer data into this message.

When we find a field in serialized that is already present in this message:

  • If it's a "repeated" field, we append to the end of our list.
  • Else, if it's a scalar, we overwrite our field.
  • Else, (it's a nonrepeated composite), we recursively merge into the existing composite.
Arguments:
  • serialized (bytes): Any object that allows us to call memoryview(serialized) to access a string of bytes using the buffer interface.
Returns:

int: The number of bytes read from serialized. For non-group messages, this will always be len(serialized), but for messages which are actually groups, this will generally be less than len(serialized), since we must stop when we reach an END_GROUP tag. Note that if we do stop because of an END_GROUP tag, the number of bytes returned does not include the bytes for the END_GROUP tag information.

Raises:
  • DecodeError: if the input cannot be parsed.
def SerializeToString(self, **kwargs):
1133  def SerializeToString(self, **kwargs):
1134    # Check if the message has all of its required fields set.
1135    if not self.IsInitialized():
1136      raise message_mod.EncodeError(
1137          'Message %s is missing required fields: %s' % (
1138          self.DESCRIPTOR.full_name, ','.join(self.FindInitializationErrors())))
1139    return self.SerializePartialToString(**kwargs)

Serializes the protocol message to a binary string.

Keyword Args:

deterministic (bool): If true, requests deterministic serialization of the protobuf, with predictable ordering of map keys.

Returns:

A binary string representation of the message if all of the required fields in the message are set (i.e. the message is initialized).

Raises:
def SerializePartialToString(self, **kwargs):
1146  def SerializePartialToString(self, **kwargs):
1147    out = BytesIO()
1148    self._InternalSerialize(out.write, **kwargs)
1149    return out.getvalue()

Serializes the protocol message to a binary string.

This method is similar to SerializeToString but doesn't check if the message is initialized.

Keyword Args:

deterministic (bool): If true, requests deterministic serialization of the protobuf, with predictable ordering of map keys.

Returns:

bytes: A serialized representation of the partial message.

def ListFields(self):
848  def ListFields(self):
849    all_fields = [item for item in self._fields.items() if _IsPresent(item)]
850    all_fields.sort(key = lambda item: item[0].number)
851    return all_fields

Returns a list of (FieldDescriptor, value) tuples for present fields.

A message field is non-empty if HasField() would return true. A singular primitive field is non-empty if HasField() would return true in proto2 or it is non zero in proto3. A repeated field is non-empty if it contains at least one element. The fields are ordered by field number.

Returns:

list[tuple(FieldDescriptor, value)]: field descriptors and values for all fields in the message which are not empty. The values vary by field type.

def HasField(self, field_name):
872  def HasField(self, field_name):
873    try:
874      field = hassable_fields[field_name]
875    except KeyError as exc:
876      raise ValueError('Protocol message %s has no non-repeated field "%s" '
877                       'nor has presence is not available for this field.' % (
878                           message_descriptor.full_name, field_name)) from exc
879
880    if isinstance(field, descriptor_mod.OneofDescriptor):
881      try:
882        return HasField(self, self._oneofs[field].name)
883      except KeyError:
884        return False
885    else:
886      if field.cpp_type == _FieldDescriptor.CPPTYPE_MESSAGE:
887        value = self._fields.get(field)
888        return value is not None and value._is_present_in_parent
889      else:
890        return field in self._fields

Checks if a certain field is set for the message.

For a oneof group, checks if any field inside is set. Note that if the field_name is not defined in the message descriptor, ValueError will be raised.

Arguments:
  • field_name (str): The name of the field to check for presence.
Returns:

bool: Whether a value has been set for the named field.

Raises:
  • ValueError: if the field_name is not a member of this message.
def ClearField(self, field_name):
897  def ClearField(self, field_name):
898    try:
899      field = message_descriptor.fields_by_name[field_name]
900    except KeyError:
901      try:
902        field = message_descriptor.oneofs_by_name[field_name]
903        if field in self._oneofs:
904          field = self._oneofs[field]
905        else:
906          return
907      except KeyError:
908        raise ValueError('Protocol message %s has no "%s" field.' %
909                         (message_descriptor.name, field_name))
910
911    if field in self._fields:
912      # To match the C++ implementation, we need to invalidate iterators
913      # for map fields when ClearField() happens.
914      if hasattr(self._fields[field], 'InvalidateIterators'):
915        self._fields[field].InvalidateIterators()
916
917      # Note:  If the field is a sub-message, its listener will still point
918      #   at us.  That's fine, because the worst than can happen is that it
919      #   will call _Modified() and invalidate our byte size.  Big deal.
920      del self._fields[field]
921
922      if self._oneofs.get(field.containing_oneof, None) is field:
923        del self._oneofs[field.containing_oneof]
924
925    # Always call _Modified() -- even if nothing was changed, this is
926    # a mutating method, and thus calling it should cause the field to become
927    # present in the parent message.
928    self._Modified()

Clears the contents of a given field.

Inside a oneof group, clears the field set. If the name neither refers to a defined field or oneof group, ValueError is raised.

Arguments:
  • field_name (str): The name of the field to check for presence.
Raises:
  • ValueError: if the field_name is not a member of this message.
def WhichOneof(self, oneof_name):
1406  def WhichOneof(self, oneof_name):
1407    """Returns the name of the currently set field inside a oneof, or None."""
1408    try:
1409      field = message_descriptor.oneofs_by_name[oneof_name]
1410    except KeyError:
1411      raise ValueError(
1412          'Protocol message has no oneof "%s" field.' % oneof_name)
1413
1414    nested_field = self._oneofs.get(field, None)
1415    if nested_field is not None and self.HasField(nested_field.name):
1416      return nested_field.name
1417    else:
1418      return None

Returns the name of the currently set field inside a oneof, or None.

def DiscardUnknownFields(self):
1438def _DiscardUnknownFields(self):
1439  self._unknown_fields = []
1440  for field, value in self.ListFields():
1441    if field.cpp_type == _FieldDescriptor.CPPTYPE_MESSAGE:
1442      if _IsMapField(field):
1443        if _IsMessageMapField(field):
1444          for key in value:
1445            value[key].DiscardUnknownFields()
1446      elif field.label == _FieldDescriptor.LABEL_REPEATED:
1447        for sub_message in value:
1448          sub_message.DiscardUnknownFields()
1449      else:
1450        value.DiscardUnknownFields()

Clears all fields in the UnknownFieldSet.

This operation is recursive for nested message.

def ByteSize(self):
1101  def ByteSize(self):
1102    if not self._cached_byte_size_dirty:
1103      return self._cached_byte_size
1104
1105    size = 0
1106    descriptor = self.DESCRIPTOR
1107    if descriptor._is_map_entry:
1108      # Fields of map entry should always be serialized.
1109      key_field = descriptor.fields_by_name['key']
1110      _MaybeAddEncoder(cls, key_field)
1111      size = key_field._sizer(self.key)
1112      value_field = descriptor.fields_by_name['value']
1113      _MaybeAddEncoder(cls, value_field)
1114      size += value_field._sizer(self.value)
1115    else:
1116      for field_descriptor, field_value in self.ListFields():
1117        _MaybeAddEncoder(cls, field_descriptor)
1118        size += field_descriptor._sizer(field_value)
1119      for tag_bytes, value_bytes in self._unknown_fields:
1120        size += len(tag_bytes) + len(value_bytes)
1121
1122    self._cached_byte_size = size
1123    self._cached_byte_size_dirty = False
1124    self._listener_for_children.dirty = False
1125    return size

Returns the serialized size of this message.

Recursively calls ByteSize() on all contained messages.

Returns:

int: The number of bytes required to serialize this message.

def FromString(s):
826  def FromString(s):
827    message = cls()
828    message.MergeFromString(s)
829    return message
TAILS_FIELD_NUMBER = 1
tails
668  def getter(self):
669    field_value = self._fields.get(field)
670    if field_value is None:
671      # Construct a new object to represent this field.
672      field_value = field._default_constructor(self)
673
674      # Atomically check if another thread has preempted us and, if not, swap
675      # in the new object we just created.  If someone has preempted us, we
676      # take that object and discard ours.
677      # WARNING:  We are relying on setdefault() being atomic.  This is true
678      #   in CPython but we haven't investigated others.  This warning appears
679      #   in several other locations in this file.
680      field_value = self._fields.setdefault(field, field_value)
681    return field_value

Getter for tails.

HEADS_FIELD_NUMBER = 2
heads
668  def getter(self):
669    field_value = self._fields.get(field)
670    if field_value is None:
671      # Construct a new object to represent this field.
672      field_value = field._default_constructor(self)
673
674      # Atomically check if another thread has preempted us and, if not, swap
675      # in the new object we just created.  If someone has preempted us, we
676      # take that object and discard ours.
677      # WARNING:  We are relying on setdefault() being atomic.  This is true
678      #   in CPython but we haven't investigated others.  This warning appears
679      #   in several other locations in this file.
680      field_value = self._fields.setdefault(field, field_value)
681    return field_value

Getter for heads.

LITERALS_FIELD_NUMBER = 3
literals
668  def getter(self):
669    field_value = self._fields.get(field)
670    if field_value is None:
671      # Construct a new object to represent this field.
672      field_value = field._default_constructor(self)
673
674      # Atomically check if another thread has preempted us and, if not, swap
675      # in the new object we just created.  If someone has preempted us, we
676      # take that object and discard ours.
677      # WARNING:  We are relying on setdefault() being atomic.  This is true
678      #   in CPython but we haven't investigated others.  This warning appears
679      #   in several other locations in this file.
680      field_value = self._fields.setdefault(field, field_value)
681    return field_value

Getter for literals.

DEMANDS_FIELD_NUMBER = 4
demands
668  def getter(self):
669    field_value = self._fields.get(field)
670    if field_value is None:
671      # Construct a new object to represent this field.
672      field_value = field._default_constructor(self)
673
674      # Atomically check if another thread has preempted us and, if not, swap
675      # in the new object we just created.  If someone has preempted us, we
676      # take that object and discard ours.
677      # WARNING:  We are relying on setdefault() being atomic.  This is true
678      #   in CPython but we haven't investigated others.  This warning appears
679      #   in several other locations in this file.
680      field_value = self._fields.setdefault(field, field_value)
681    return field_value

Getter for demands.

CAPACITY_FIELD_NUMBER = 5
capacity
711  def getter(self):
712    # TODO: This may be broken since there may not be
713    # default_value.  Combine with has_default_value somehow.
714    return self._fields.get(field, default_value)

Getter for capacity.

def FindInitializationErrors(self):
1305  def FindInitializationErrors(self):
1306    """Finds required fields which are not initialized.
1307
1308    Returns:
1309      A list of strings.  Each string is a path to an uninitialized field from
1310      the top-level message, e.g. "foo.bar[5].baz".
1311    """
1312
1313    errors = []  # simplify things
1314
1315    for field in required_fields:
1316      if not self.HasField(field.name):
1317        errors.append(field.name)
1318
1319    for field, value in self.ListFields():
1320      if field.cpp_type == _FieldDescriptor.CPPTYPE_MESSAGE:
1321        if field.is_extension:
1322          name = '(%s)' % field.full_name
1323        else:
1324          name = field.name
1325
1326        if _IsMapField(field):
1327          if _IsMessageMapField(field):
1328            for key in value:
1329              element = value[key]
1330              prefix = '%s[%s].' % (name, key)
1331              sub_errors = element.FindInitializationErrors()
1332              errors += [prefix + error for error in sub_errors]
1333          else:
1334            # ScalarMaps can't have any initialization errors.
1335            pass
1336        elif field.label == _FieldDescriptor.LABEL_REPEATED:
1337          for i in range(len(value)):
1338            element = value[i]
1339            prefix = '%s[%d].' % (name, i)
1340            sub_errors = element.FindInitializationErrors()
1341            errors += [prefix + error for error in sub_errors]
1342        else:
1343          prefix = name + '.'
1344          sub_errors = value.FindInitializationErrors()
1345          errors += [prefix + error for error in sub_errors]
1346
1347    return errors

Finds required fields which are not initialized.

Returns:

A list of strings. Each string is a path to an uninitialized field from the top-level message, e.g. "foo.bar[5].baz".

class TableConstraintProto(google.protobuf.message.Message):

Abstract base class for protocol messages.

Protocol message classes are almost always generated by the protocol compiler. These generated types subclass Message and implement the methods shown below.

TableConstraintProto(**kwargs)
498  def init(self, **kwargs):
499    self._cached_byte_size = 0
500    self._cached_byte_size_dirty = len(kwargs) > 0
501    self._fields = {}
502    # Contains a mapping from oneof field descriptors to the descriptor
503    # of the currently set field in that oneof field.
504    self._oneofs = {}
505
506    # _unknown_fields is () when empty for efficiency, and will be turned into
507    # a list if fields are added.
508    self._unknown_fields = ()
509    self._is_present_in_parent = False
510    self._listener = message_listener_mod.NullMessageListener()
511    self._listener_for_children = _Listener(self)
512    for field_name, field_value in kwargs.items():
513      field = _GetFieldByName(message_descriptor, field_name)
514      if field is None:
515        raise TypeError('%s() got an unexpected keyword argument "%s"' %
516                        (message_descriptor.name, field_name))
517      if field_value is None:
518        # field=None is the same as no field at all.
519        continue
520      if field.label == _FieldDescriptor.LABEL_REPEATED:
521        field_copy = field._default_constructor(self)
522        if field.cpp_type == _FieldDescriptor.CPPTYPE_MESSAGE:  # Composite
523          if _IsMapField(field):
524            if _IsMessageMapField(field):
525              for key in field_value:
526                field_copy[key].MergeFrom(field_value[key])
527            else:
528              field_copy.update(field_value)
529          else:
530            for val in field_value:
531              if isinstance(val, dict):
532                field_copy.add(**val)
533              else:
534                field_copy.add().MergeFrom(val)
535        else:  # Scalar
536          if field.cpp_type == _FieldDescriptor.CPPTYPE_ENUM:
537            field_value = [_GetIntegerEnumValue(field.enum_type, val)
538                           for val in field_value]
539          field_copy.extend(field_value)
540        self._fields[field] = field_copy
541      elif field.cpp_type == _FieldDescriptor.CPPTYPE_MESSAGE:
542        field_copy = field._default_constructor(self)
543        new_val = None
544        if isinstance(field_value, message_mod.Message):
545          new_val = field_value
546        elif isinstance(field_value, dict):
547          if field.message_type.full_name == _StructFullTypeName:
548            field_copy.Clear()
549            if len(field_value) == 1 and 'fields' in field_value:
550              try:
551                field_copy.update(field_value)
552              except:
553                # Fall back to init normal message field
554                field_copy.Clear()
555                new_val = field.message_type._concrete_class(**field_value)
556            else:
557              field_copy.update(field_value)
558          else:
559            new_val = field.message_type._concrete_class(**field_value)
560        elif hasattr(field_copy, '_internal_assign'):
561          field_copy._internal_assign(field_value)
562        else:
563          raise TypeError(
564              'Message field {0}.{1} must be initialized with a '
565              'dict or instance of same class, got {2}.'.format(
566                  message_descriptor.name,
567                  field_name,
568                  type(field_value).__name__,
569              )
570          )
571
572        if new_val != None:
573          try:
574            field_copy.MergeFrom(new_val)
575          except TypeError:
576            _ReraiseTypeErrorWithFieldName(message_descriptor.name, field_name)
577        self._fields[field] = field_copy
578      else:
579        if field.cpp_type == _FieldDescriptor.CPPTYPE_ENUM:
580          field_value = _GetIntegerEnumValue(field.enum_type, field_value)
581        try:
582          setattr(self, field_name, field_value)
583        except TypeError:
584          _ReraiseTypeErrorWithFieldName(message_descriptor.name, field_name)
DESCRIPTOR = <google.protobuf.descriptor.Descriptor object>
def MergeFrom(self, msg):
1364  def MergeFrom(self, msg):
1365    if not isinstance(msg, cls):
1366      raise TypeError(
1367          'Parameter to MergeFrom() must be instance of same class: '
1368          'expected %s got %s.' % (_FullyQualifiedClassName(cls),
1369                                   _FullyQualifiedClassName(msg.__class__)))
1370
1371    assert msg is not self
1372    self._Modified()
1373
1374    fields = self._fields
1375
1376    for field, value in msg._fields.items():
1377      if field.label == LABEL_REPEATED:
1378        field_value = fields.get(field)
1379        if field_value is None:
1380          # Construct a new object to represent this field.
1381          field_value = field._default_constructor(self)
1382          fields[field] = field_value
1383        field_value.MergeFrom(value)
1384      elif field.cpp_type == CPPTYPE_MESSAGE:
1385        if value._is_present_in_parent:
1386          field_value = fields.get(field)
1387          if field_value is None:
1388            # Construct a new object to represent this field.
1389            field_value = field._default_constructor(self)
1390            fields[field] = field_value
1391          field_value.MergeFrom(value)
1392      else:
1393        self._fields[field] = value
1394        if field.containing_oneof:
1395          self._UpdateOneofState(field)
1396
1397    if msg._unknown_fields:
1398      if not self._unknown_fields:
1399        self._unknown_fields = []
1400      self._unknown_fields.extend(msg._unknown_fields)

Merges the contents of the specified message into current message.

This method merges the contents of the specified message into the current message. Singular fields that are set in the specified message overwrite the corresponding fields in the current message. Repeated fields are appended. Singular sub-messages and groups are recursively merged.

Arguments:
  • other_msg (Message): A message to merge into the current message.
def Clear(self):
1423def _Clear(self):
1424  # Clear fields.
1425  self._fields = {}
1426  self._unknown_fields = ()
1427
1428  self._oneofs = {}
1429  self._Modified()

Clears all data that was set in the message.

def SetInParent(self):
1489  def Modified(self):
1490    """Sets the _cached_byte_size_dirty bit to true,
1491    and propagates this to our listener iff this was a state change.
1492    """
1493
1494    # Note:  Some callers check _cached_byte_size_dirty before calling
1495    #   _Modified() as an extra optimization.  So, if this method is ever
1496    #   changed such that it does stuff even when _cached_byte_size_dirty is
1497    #   already true, the callers need to be updated.
1498    if not self._cached_byte_size_dirty:
1499      self._cached_byte_size_dirty = True
1500      self._listener_for_children.dirty = True
1501      self._is_present_in_parent = True
1502      self._listener.Modified()

Sets the _cached_byte_size_dirty bit to true, and propagates this to our listener iff this was a state change.

def IsInitialized(self, errors=None):
1265  def IsInitialized(self, errors=None):
1266    """Checks if all required fields of a message are set.
1267
1268    Args:
1269      errors:  A list which, if provided, will be populated with the field
1270               paths of all missing required fields.
1271
1272    Returns:
1273      True iff the specified message has all required fields set.
1274    """
1275
1276    # Performance is critical so we avoid HasField() and ListFields().
1277
1278    for field in required_fields:
1279      if (field not in self._fields or
1280          (field.cpp_type == _FieldDescriptor.CPPTYPE_MESSAGE and
1281           not self._fields[field]._is_present_in_parent)):
1282        if errors is not None:
1283          errors.extend(self.FindInitializationErrors())
1284        return False
1285
1286    for field, value in list(self._fields.items()):  # dict can change size!
1287      if field.cpp_type == _FieldDescriptor.CPPTYPE_MESSAGE:
1288        if field.label == _FieldDescriptor.LABEL_REPEATED:
1289          if (field.message_type._is_map_entry):
1290            continue
1291          for element in value:
1292            if not element.IsInitialized():
1293              if errors is not None:
1294                errors.extend(self.FindInitializationErrors())
1295              return False
1296        elif value._is_present_in_parent and not value.IsInitialized():
1297          if errors is not None:
1298            errors.extend(self.FindInitializationErrors())
1299          return False
1300
1301    return True

Checks if all required fields of a message are set.

Arguments:
  • errors: A list which, if provided, will be populated with the field paths of all missing required fields.
Returns:

True iff the specified message has all required fields set.

def MergeFromString(self, serialized):
1180  def MergeFromString(self, serialized):
1181    serialized = memoryview(serialized)
1182    length = len(serialized)
1183    try:
1184      if self._InternalParse(serialized, 0, length) != length:
1185        # The only reason _InternalParse would return early is if it
1186        # encountered an end-group tag.
1187        raise message_mod.DecodeError('Unexpected end-group tag.')
1188    except (IndexError, TypeError):
1189      # Now ord(buf[p:p+1]) == ord('') gets TypeError.
1190      raise message_mod.DecodeError('Truncated message.')
1191    except struct.error as e:
1192      raise message_mod.DecodeError(e)
1193    return length   # Return this for legacy reasons.

Merges serialized protocol buffer data into this message.

When we find a field in serialized that is already present in this message:

  • If it's a "repeated" field, we append to the end of our list.
  • Else, if it's a scalar, we overwrite our field.
  • Else, (it's a nonrepeated composite), we recursively merge into the existing composite.
Arguments:
  • serialized (bytes): Any object that allows us to call memoryview(serialized) to access a string of bytes using the buffer interface.
Returns:

int: The number of bytes read from serialized. For non-group messages, this will always be len(serialized), but for messages which are actually groups, this will generally be less than len(serialized), since we must stop when we reach an END_GROUP tag. Note that if we do stop because of an END_GROUP tag, the number of bytes returned does not include the bytes for the END_GROUP tag information.

Raises:
  • DecodeError: if the input cannot be parsed.
def SerializeToString(self, **kwargs):
1133  def SerializeToString(self, **kwargs):
1134    # Check if the message has all of its required fields set.
1135    if not self.IsInitialized():
1136      raise message_mod.EncodeError(
1137          'Message %s is missing required fields: %s' % (
1138          self.DESCRIPTOR.full_name, ','.join(self.FindInitializationErrors())))
1139    return self.SerializePartialToString(**kwargs)

Serializes the protocol message to a binary string.

Keyword Args:

deterministic (bool): If true, requests deterministic serialization of the protobuf, with predictable ordering of map keys.

Returns:

A binary string representation of the message if all of the required fields in the message are set (i.e. the message is initialized).

Raises:
def SerializePartialToString(self, **kwargs):
1146  def SerializePartialToString(self, **kwargs):
1147    out = BytesIO()
1148    self._InternalSerialize(out.write, **kwargs)
1149    return out.getvalue()

Serializes the protocol message to a binary string.

This method is similar to SerializeToString but doesn't check if the message is initialized.

Keyword Args:

deterministic (bool): If true, requests deterministic serialization of the protobuf, with predictable ordering of map keys.

Returns:

bytes: A serialized representation of the partial message.

def ListFields(self):
848  def ListFields(self):
849    all_fields = [item for item in self._fields.items() if _IsPresent(item)]
850    all_fields.sort(key = lambda item: item[0].number)
851    return all_fields

Returns a list of (FieldDescriptor, value) tuples for present fields.

A message field is non-empty if HasField() would return true. A singular primitive field is non-empty if HasField() would return true in proto2 or it is non zero in proto3. A repeated field is non-empty if it contains at least one element. The fields are ordered by field number.

Returns:

list[tuple(FieldDescriptor, value)]: field descriptors and values for all fields in the message which are not empty. The values vary by field type.

def HasField(self, field_name):
872  def HasField(self, field_name):
873    try:
874      field = hassable_fields[field_name]
875    except KeyError as exc:
876      raise ValueError('Protocol message %s has no non-repeated field "%s" '
877                       'nor has presence is not available for this field.' % (
878                           message_descriptor.full_name, field_name)) from exc
879
880    if isinstance(field, descriptor_mod.OneofDescriptor):
881      try:
882        return HasField(self, self._oneofs[field].name)
883      except KeyError:
884        return False
885    else:
886      if field.cpp_type == _FieldDescriptor.CPPTYPE_MESSAGE:
887        value = self._fields.get(field)
888        return value is not None and value._is_present_in_parent
889      else:
890        return field in self._fields

Checks if a certain field is set for the message.

For a oneof group, checks if any field inside is set. Note that if the field_name is not defined in the message descriptor, ValueError will be raised.

Arguments:
  • field_name (str): The name of the field to check for presence.
Returns:

bool: Whether a value has been set for the named field.

Raises:
  • ValueError: if the field_name is not a member of this message.
def ClearField(self, field_name):
897  def ClearField(self, field_name):
898    try:
899      field = message_descriptor.fields_by_name[field_name]
900    except KeyError:
901      try:
902        field = message_descriptor.oneofs_by_name[field_name]
903        if field in self._oneofs:
904          field = self._oneofs[field]
905        else:
906          return
907      except KeyError:
908        raise ValueError('Protocol message %s has no "%s" field.' %
909                         (message_descriptor.name, field_name))
910
911    if field in self._fields:
912      # To match the C++ implementation, we need to invalidate iterators
913      # for map fields when ClearField() happens.
914      if hasattr(self._fields[field], 'InvalidateIterators'):
915        self._fields[field].InvalidateIterators()
916
917      # Note:  If the field is a sub-message, its listener will still point
918      #   at us.  That's fine, because the worst than can happen is that it
919      #   will call _Modified() and invalidate our byte size.  Big deal.
920      del self._fields[field]
921
922      if self._oneofs.get(field.containing_oneof, None) is field:
923        del self._oneofs[field.containing_oneof]
924
925    # Always call _Modified() -- even if nothing was changed, this is
926    # a mutating method, and thus calling it should cause the field to become
927    # present in the parent message.
928    self._Modified()

Clears the contents of a given field.

Inside a oneof group, clears the field set. If the name neither refers to a defined field or oneof group, ValueError is raised.

Arguments:
  • field_name (str): The name of the field to check for presence.
Raises:
  • ValueError: if the field_name is not a member of this message.
def WhichOneof(self, oneof_name):
1406  def WhichOneof(self, oneof_name):
1407    """Returns the name of the currently set field inside a oneof, or None."""
1408    try:
1409      field = message_descriptor.oneofs_by_name[oneof_name]
1410    except KeyError:
1411      raise ValueError(
1412          'Protocol message has no oneof "%s" field.' % oneof_name)
1413
1414    nested_field = self._oneofs.get(field, None)
1415    if nested_field is not None and self.HasField(nested_field.name):
1416      return nested_field.name
1417    else:
1418      return None

Returns the name of the currently set field inside a oneof, or None.

def DiscardUnknownFields(self):
1438def _DiscardUnknownFields(self):
1439  self._unknown_fields = []
1440  for field, value in self.ListFields():
1441    if field.cpp_type == _FieldDescriptor.CPPTYPE_MESSAGE:
1442      if _IsMapField(field):
1443        if _IsMessageMapField(field):
1444          for key in value:
1445            value[key].DiscardUnknownFields()
1446      elif field.label == _FieldDescriptor.LABEL_REPEATED:
1447        for sub_message in value:
1448          sub_message.DiscardUnknownFields()
1449      else:
1450        value.DiscardUnknownFields()

Clears all fields in the UnknownFieldSet.

This operation is recursive for nested message.

def ByteSize(self):
1101  def ByteSize(self):
1102    if not self._cached_byte_size_dirty:
1103      return self._cached_byte_size
1104
1105    size = 0
1106    descriptor = self.DESCRIPTOR
1107    if descriptor._is_map_entry:
1108      # Fields of map entry should always be serialized.
1109      key_field = descriptor.fields_by_name['key']
1110      _MaybeAddEncoder(cls, key_field)
1111      size = key_field._sizer(self.key)
1112      value_field = descriptor.fields_by_name['value']
1113      _MaybeAddEncoder(cls, value_field)
1114      size += value_field._sizer(self.value)
1115    else:
1116      for field_descriptor, field_value in self.ListFields():
1117        _MaybeAddEncoder(cls, field_descriptor)
1118        size += field_descriptor._sizer(field_value)
1119      for tag_bytes, value_bytes in self._unknown_fields:
1120        size += len(tag_bytes) + len(value_bytes)
1121
1122    self._cached_byte_size = size
1123    self._cached_byte_size_dirty = False
1124    self._listener_for_children.dirty = False
1125    return size

Returns the serialized size of this message.

Recursively calls ByteSize() on all contained messages.

Returns:

int: The number of bytes required to serialize this message.

def FromString(s):
826  def FromString(s):
827    message = cls()
828    message.MergeFromString(s)
829    return message
VARS_FIELD_NUMBER = 1
vars
668  def getter(self):
669    field_value = self._fields.get(field)
670    if field_value is None:
671      # Construct a new object to represent this field.
672      field_value = field._default_constructor(self)
673
674      # Atomically check if another thread has preempted us and, if not, swap
675      # in the new object we just created.  If someone has preempted us, we
676      # take that object and discard ours.
677      # WARNING:  We are relying on setdefault() being atomic.  This is true
678      #   in CPython but we haven't investigated others.  This warning appears
679      #   in several other locations in this file.
680      field_value = self._fields.setdefault(field, field_value)
681    return field_value

Getter for vars.

VALUES_FIELD_NUMBER = 2
values
668  def getter(self):
669    field_value = self._fields.get(field)
670    if field_value is None:
671      # Construct a new object to represent this field.
672      field_value = field._default_constructor(self)
673
674      # Atomically check if another thread has preempted us and, if not, swap
675      # in the new object we just created.  If someone has preempted us, we
676      # take that object and discard ours.
677      # WARNING:  We are relying on setdefault() being atomic.  This is true
678      #   in CPython but we haven't investigated others.  This warning appears
679      #   in several other locations in this file.
680      field_value = self._fields.setdefault(field, field_value)
681    return field_value

Getter for values.

EXPRS_FIELD_NUMBER = 4
exprs
668  def getter(self):
669    field_value = self._fields.get(field)
670    if field_value is None:
671      # Construct a new object to represent this field.
672      field_value = field._default_constructor(self)
673
674      # Atomically check if another thread has preempted us and, if not, swap
675      # in the new object we just created.  If someone has preempted us, we
676      # take that object and discard ours.
677      # WARNING:  We are relying on setdefault() being atomic.  This is true
678      #   in CPython but we haven't investigated others.  This warning appears
679      #   in several other locations in this file.
680      field_value = self._fields.setdefault(field, field_value)
681    return field_value

Getter for exprs.

NEGATED_FIELD_NUMBER = 3
negated
711  def getter(self):
712    # TODO: This may be broken since there may not be
713    # default_value.  Combine with has_default_value somehow.
714    return self._fields.get(field, default_value)

Getter for negated.

def FindInitializationErrors(self):
1305  def FindInitializationErrors(self):
1306    """Finds required fields which are not initialized.
1307
1308    Returns:
1309      A list of strings.  Each string is a path to an uninitialized field from
1310      the top-level message, e.g. "foo.bar[5].baz".
1311    """
1312
1313    errors = []  # simplify things
1314
1315    for field in required_fields:
1316      if not self.HasField(field.name):
1317        errors.append(field.name)
1318
1319    for field, value in self.ListFields():
1320      if field.cpp_type == _FieldDescriptor.CPPTYPE_MESSAGE:
1321        if field.is_extension:
1322          name = '(%s)' % field.full_name
1323        else:
1324          name = field.name
1325
1326        if _IsMapField(field):
1327          if _IsMessageMapField(field):
1328            for key in value:
1329              element = value[key]
1330              prefix = '%s[%s].' % (name, key)
1331              sub_errors = element.FindInitializationErrors()
1332              errors += [prefix + error for error in sub_errors]
1333          else:
1334            # ScalarMaps can't have any initialization errors.
1335            pass
1336        elif field.label == _FieldDescriptor.LABEL_REPEATED:
1337          for i in range(len(value)):
1338            element = value[i]
1339            prefix = '%s[%d].' % (name, i)
1340            sub_errors = element.FindInitializationErrors()
1341            errors += [prefix + error for error in sub_errors]
1342        else:
1343          prefix = name + '.'
1344          sub_errors = value.FindInitializationErrors()
1345          errors += [prefix + error for error in sub_errors]
1346
1347    return errors

Finds required fields which are not initialized.

Returns:

A list of strings. Each string is a path to an uninitialized field from the top-level message, e.g. "foo.bar[5].baz".

class InverseConstraintProto(google.protobuf.message.Message):

Abstract base class for protocol messages.

Protocol message classes are almost always generated by the protocol compiler. These generated types subclass Message and implement the methods shown below.

InverseConstraintProto(**kwargs)
498  def init(self, **kwargs):
499    self._cached_byte_size = 0
500    self._cached_byte_size_dirty = len(kwargs) > 0
501    self._fields = {}
502    # Contains a mapping from oneof field descriptors to the descriptor
503    # of the currently set field in that oneof field.
504    self._oneofs = {}
505
506    # _unknown_fields is () when empty for efficiency, and will be turned into
507    # a list if fields are added.
508    self._unknown_fields = ()
509    self._is_present_in_parent = False
510    self._listener = message_listener_mod.NullMessageListener()
511    self._listener_for_children = _Listener(self)
512    for field_name, field_value in kwargs.items():
513      field = _GetFieldByName(message_descriptor, field_name)
514      if field is None:
515        raise TypeError('%s() got an unexpected keyword argument "%s"' %
516                        (message_descriptor.name, field_name))
517      if field_value is None:
518        # field=None is the same as no field at all.
519        continue
520      if field.label == _FieldDescriptor.LABEL_REPEATED:
521        field_copy = field._default_constructor(self)
522        if field.cpp_type == _FieldDescriptor.CPPTYPE_MESSAGE:  # Composite
523          if _IsMapField(field):
524            if _IsMessageMapField(field):
525              for key in field_value:
526                field_copy[key].MergeFrom(field_value[key])
527            else:
528              field_copy.update(field_value)
529          else:
530            for val in field_value:
531              if isinstance(val, dict):
532                field_copy.add(**val)
533              else:
534                field_copy.add().MergeFrom(val)
535        else:  # Scalar
536          if field.cpp_type == _FieldDescriptor.CPPTYPE_ENUM:
537            field_value = [_GetIntegerEnumValue(field.enum_type, val)
538                           for val in field_value]
539          field_copy.extend(field_value)
540        self._fields[field] = field_copy
541      elif field.cpp_type == _FieldDescriptor.CPPTYPE_MESSAGE:
542        field_copy = field._default_constructor(self)
543        new_val = None
544        if isinstance(field_value, message_mod.Message):
545          new_val = field_value
546        elif isinstance(field_value, dict):
547          if field.message_type.full_name == _StructFullTypeName:
548            field_copy.Clear()
549            if len(field_value) == 1 and 'fields' in field_value:
550              try:
551                field_copy.update(field_value)
552              except:
553                # Fall back to init normal message field
554                field_copy.Clear()
555                new_val = field.message_type._concrete_class(**field_value)
556            else:
557              field_copy.update(field_value)
558          else:
559            new_val = field.message_type._concrete_class(**field_value)
560        elif hasattr(field_copy, '_internal_assign'):
561          field_copy._internal_assign(field_value)
562        else:
563          raise TypeError(
564              'Message field {0}.{1} must be initialized with a '
565              'dict or instance of same class, got {2}.'.format(
566                  message_descriptor.name,
567                  field_name,
568                  type(field_value).__name__,
569              )
570          )
571
572        if new_val != None:
573          try:
574            field_copy.MergeFrom(new_val)
575          except TypeError:
576            _ReraiseTypeErrorWithFieldName(message_descriptor.name, field_name)
577        self._fields[field] = field_copy
578      else:
579        if field.cpp_type == _FieldDescriptor.CPPTYPE_ENUM:
580          field_value = _GetIntegerEnumValue(field.enum_type, field_value)
581        try:
582          setattr(self, field_name, field_value)
583        except TypeError:
584          _ReraiseTypeErrorWithFieldName(message_descriptor.name, field_name)
DESCRIPTOR = <google.protobuf.descriptor.Descriptor object>
def MergeFrom(self, msg):
1364  def MergeFrom(self, msg):
1365    if not isinstance(msg, cls):
1366      raise TypeError(
1367          'Parameter to MergeFrom() must be instance of same class: '
1368          'expected %s got %s.' % (_FullyQualifiedClassName(cls),
1369                                   _FullyQualifiedClassName(msg.__class__)))
1370
1371    assert msg is not self
1372    self._Modified()
1373
1374    fields = self._fields
1375
1376    for field, value in msg._fields.items():
1377      if field.label == LABEL_REPEATED:
1378        field_value = fields.get(field)
1379        if field_value is None:
1380          # Construct a new object to represent this field.
1381          field_value = field._default_constructor(self)
1382          fields[field] = field_value
1383        field_value.MergeFrom(value)
1384      elif field.cpp_type == CPPTYPE_MESSAGE:
1385        if value._is_present_in_parent:
1386          field_value = fields.get(field)
1387          if field_value is None:
1388            # Construct a new object to represent this field.
1389            field_value = field._default_constructor(self)
1390            fields[field] = field_value
1391          field_value.MergeFrom(value)
1392      else:
1393        self._fields[field] = value
1394        if field.containing_oneof:
1395          self._UpdateOneofState(field)
1396
1397    if msg._unknown_fields:
1398      if not self._unknown_fields:
1399        self._unknown_fields = []
1400      self._unknown_fields.extend(msg._unknown_fields)

Merges the contents of the specified message into current message.

This method merges the contents of the specified message into the current message. Singular fields that are set in the specified message overwrite the corresponding fields in the current message. Repeated fields are appended. Singular sub-messages and groups are recursively merged.

Arguments:
  • other_msg (Message): A message to merge into the current message.
def Clear(self):
1423def _Clear(self):
1424  # Clear fields.
1425  self._fields = {}
1426  self._unknown_fields = ()
1427
1428  self._oneofs = {}
1429  self._Modified()

Clears all data that was set in the message.

def SetInParent(self):
1489  def Modified(self):
1490    """Sets the _cached_byte_size_dirty bit to true,
1491    and propagates this to our listener iff this was a state change.
1492    """
1493
1494    # Note:  Some callers check _cached_byte_size_dirty before calling
1495    #   _Modified() as an extra optimization.  So, if this method is ever
1496    #   changed such that it does stuff even when _cached_byte_size_dirty is
1497    #   already true, the callers need to be updated.
1498    if not self._cached_byte_size_dirty:
1499      self._cached_byte_size_dirty = True
1500      self._listener_for_children.dirty = True
1501      self._is_present_in_parent = True
1502      self._listener.Modified()

Sets the _cached_byte_size_dirty bit to true, and propagates this to our listener iff this was a state change.

def IsInitialized(self, errors=None):
1265  def IsInitialized(self, errors=None):
1266    """Checks if all required fields of a message are set.
1267
1268    Args:
1269      errors:  A list which, if provided, will be populated with the field
1270               paths of all missing required fields.
1271
1272    Returns:
1273      True iff the specified message has all required fields set.
1274    """
1275
1276    # Performance is critical so we avoid HasField() and ListFields().
1277
1278    for field in required_fields:
1279      if (field not in self._fields or
1280          (field.cpp_type == _FieldDescriptor.CPPTYPE_MESSAGE and
1281           not self._fields[field]._is_present_in_parent)):
1282        if errors is not None:
1283          errors.extend(self.FindInitializationErrors())
1284        return False
1285
1286    for field, value in list(self._fields.items()):  # dict can change size!
1287      if field.cpp_type == _FieldDescriptor.CPPTYPE_MESSAGE:
1288        if field.label == _FieldDescriptor.LABEL_REPEATED:
1289          if (field.message_type._is_map_entry):
1290            continue
1291          for element in value:
1292            if not element.IsInitialized():
1293              if errors is not None:
1294                errors.extend(self.FindInitializationErrors())
1295              return False
1296        elif value._is_present_in_parent and not value.IsInitialized():
1297          if errors is not None:
1298            errors.extend(self.FindInitializationErrors())
1299          return False
1300
1301    return True

Checks if all required fields of a message are set.

Arguments:
  • errors: A list which, if provided, will be populated with the field paths of all missing required fields.
Returns:

True iff the specified message has all required fields set.

def MergeFromString(self, serialized):
1180  def MergeFromString(self, serialized):
1181    serialized = memoryview(serialized)
1182    length = len(serialized)
1183    try:
1184      if self._InternalParse(serialized, 0, length) != length:
1185        # The only reason _InternalParse would return early is if it
1186        # encountered an end-group tag.
1187        raise message_mod.DecodeError('Unexpected end-group tag.')
1188    except (IndexError, TypeError):
1189      # Now ord(buf[p:p+1]) == ord('') gets TypeError.
1190      raise message_mod.DecodeError('Truncated message.')
1191    except struct.error as e:
1192      raise message_mod.DecodeError(e)
1193    return length   # Return this for legacy reasons.

Merges serialized protocol buffer data into this message.

When we find a field in serialized that is already present in this message:

  • If it's a "repeated" field, we append to the end of our list.
  • Else, if it's a scalar, we overwrite our field.
  • Else, (it's a nonrepeated composite), we recursively merge into the existing composite.
Arguments:
  • serialized (bytes): Any object that allows us to call memoryview(serialized) to access a string of bytes using the buffer interface.
Returns:

int: The number of bytes read from serialized. For non-group messages, this will always be len(serialized), but for messages which are actually groups, this will generally be less than len(serialized), since we must stop when we reach an END_GROUP tag. Note that if we do stop because of an END_GROUP tag, the number of bytes returned does not include the bytes for the END_GROUP tag information.

Raises:
  • DecodeError: if the input cannot be parsed.
def SerializeToString(self, **kwargs):
1133  def SerializeToString(self, **kwargs):
1134    # Check if the message has all of its required fields set.
1135    if not self.IsInitialized():
1136      raise message_mod.EncodeError(
1137          'Message %s is missing required fields: %s' % (
1138          self.DESCRIPTOR.full_name, ','.join(self.FindInitializationErrors())))
1139    return self.SerializePartialToString(**kwargs)

Serializes the protocol message to a binary string.

Keyword Args:

deterministic (bool): If true, requests deterministic serialization of the protobuf, with predictable ordering of map keys.

Returns:

A binary string representation of the message if all of the required fields in the message are set (i.e. the message is initialized).

Raises:
def SerializePartialToString(self, **kwargs):
1146  def SerializePartialToString(self, **kwargs):
1147    out = BytesIO()
1148    self._InternalSerialize(out.write, **kwargs)
1149    return out.getvalue()

Serializes the protocol message to a binary string.

This method is similar to SerializeToString but doesn't check if the message is initialized.

Keyword Args:

deterministic (bool): If true, requests deterministic serialization of the protobuf, with predictable ordering of map keys.

Returns:

bytes: A serialized representation of the partial message.

def ListFields(self):
848  def ListFields(self):
849    all_fields = [item for item in self._fields.items() if _IsPresent(item)]
850    all_fields.sort(key = lambda item: item[0].number)
851    return all_fields

Returns a list of (FieldDescriptor, value) tuples for present fields.

A message field is non-empty if HasField() would return true. A singular primitive field is non-empty if HasField() would return true in proto2 or it is non zero in proto3. A repeated field is non-empty if it contains at least one element. The fields are ordered by field number.

Returns:

list[tuple(FieldDescriptor, value)]: field descriptors and values for all fields in the message which are not empty. The values vary by field type.

def HasField(self, field_name):
872  def HasField(self, field_name):
873    try:
874      field = hassable_fields[field_name]
875    except KeyError as exc:
876      raise ValueError('Protocol message %s has no non-repeated field "%s" '
877                       'nor has presence is not available for this field.' % (
878                           message_descriptor.full_name, field_name)) from exc
879
880    if isinstance(field, descriptor_mod.OneofDescriptor):
881      try:
882        return HasField(self, self._oneofs[field].name)
883      except KeyError:
884        return False
885    else:
886      if field.cpp_type == _FieldDescriptor.CPPTYPE_MESSAGE:
887        value = self._fields.get(field)
888        return value is not None and value._is_present_in_parent
889      else:
890        return field in self._fields

Checks if a certain field is set for the message.

For a oneof group, checks if any field inside is set. Note that if the field_name is not defined in the message descriptor, ValueError will be raised.

Arguments:
  • field_name (str): The name of the field to check for presence.
Returns:

bool: Whether a value has been set for the named field.

Raises:
  • ValueError: if the field_name is not a member of this message.
def ClearField(self, field_name):
897  def ClearField(self, field_name):
898    try:
899      field = message_descriptor.fields_by_name[field_name]
900    except KeyError:
901      try:
902        field = message_descriptor.oneofs_by_name[field_name]
903        if field in self._oneofs:
904          field = self._oneofs[field]
905        else:
906          return
907      except KeyError:
908        raise ValueError('Protocol message %s has no "%s" field.' %
909                         (message_descriptor.name, field_name))
910
911    if field in self._fields:
912      # To match the C++ implementation, we need to invalidate iterators
913      # for map fields when ClearField() happens.
914      if hasattr(self._fields[field], 'InvalidateIterators'):
915        self._fields[field].InvalidateIterators()
916
917      # Note:  If the field is a sub-message, its listener will still point
918      #   at us.  That's fine, because the worst than can happen is that it
919      #   will call _Modified() and invalidate our byte size.  Big deal.
920      del self._fields[field]
921
922      if self._oneofs.get(field.containing_oneof, None) is field:
923        del self._oneofs[field.containing_oneof]
924
925    # Always call _Modified() -- even if nothing was changed, this is
926    # a mutating method, and thus calling it should cause the field to become
927    # present in the parent message.
928    self._Modified()

Clears the contents of a given field.

Inside a oneof group, clears the field set. If the name neither refers to a defined field or oneof group, ValueError is raised.

Arguments:
  • field_name (str): The name of the field to check for presence.
Raises:
  • ValueError: if the field_name is not a member of this message.
def WhichOneof(self, oneof_name):
1406  def WhichOneof(self, oneof_name):
1407    """Returns the name of the currently set field inside a oneof, or None."""
1408    try:
1409      field = message_descriptor.oneofs_by_name[oneof_name]
1410    except KeyError:
1411      raise ValueError(
1412          'Protocol message has no oneof "%s" field.' % oneof_name)
1413
1414    nested_field = self._oneofs.get(field, None)
1415    if nested_field is not None and self.HasField(nested_field.name):
1416      return nested_field.name
1417    else:
1418      return None

Returns the name of the currently set field inside a oneof, or None.

def DiscardUnknownFields(self):
1438def _DiscardUnknownFields(self):
1439  self._unknown_fields = []
1440  for field, value in self.ListFields():
1441    if field.cpp_type == _FieldDescriptor.CPPTYPE_MESSAGE:
1442      if _IsMapField(field):
1443        if _IsMessageMapField(field):
1444          for key in value:
1445            value[key].DiscardUnknownFields()
1446      elif field.label == _FieldDescriptor.LABEL_REPEATED:
1447        for sub_message in value:
1448          sub_message.DiscardUnknownFields()
1449      else:
1450        value.DiscardUnknownFields()

Clears all fields in the UnknownFieldSet.

This operation is recursive for nested message.

def ByteSize(self):
1101  def ByteSize(self):
1102    if not self._cached_byte_size_dirty:
1103      return self._cached_byte_size
1104
1105    size = 0
1106    descriptor = self.DESCRIPTOR
1107    if descriptor._is_map_entry:
1108      # Fields of map entry should always be serialized.
1109      key_field = descriptor.fields_by_name['key']
1110      _MaybeAddEncoder(cls, key_field)
1111      size = key_field._sizer(self.key)
1112      value_field = descriptor.fields_by_name['value']
1113      _MaybeAddEncoder(cls, value_field)
1114      size += value_field._sizer(self.value)
1115    else:
1116      for field_descriptor, field_value in self.ListFields():
1117        _MaybeAddEncoder(cls, field_descriptor)
1118        size += field_descriptor._sizer(field_value)
1119      for tag_bytes, value_bytes in self._unknown_fields:
1120        size += len(tag_bytes) + len(value_bytes)
1121
1122    self._cached_byte_size = size
1123    self._cached_byte_size_dirty = False
1124    self._listener_for_children.dirty = False
1125    return size

Returns the serialized size of this message.

Recursively calls ByteSize() on all contained messages.

Returns:

int: The number of bytes required to serialize this message.

def FromString(s):
826  def FromString(s):
827    message = cls()
828    message.MergeFromString(s)
829    return message
F_DIRECT_FIELD_NUMBER = 1
f_direct
668  def getter(self):
669    field_value = self._fields.get(field)
670    if field_value is None:
671      # Construct a new object to represent this field.
672      field_value = field._default_constructor(self)
673
674      # Atomically check if another thread has preempted us and, if not, swap
675      # in the new object we just created.  If someone has preempted us, we
676      # take that object and discard ours.
677      # WARNING:  We are relying on setdefault() being atomic.  This is true
678      #   in CPython but we haven't investigated others.  This warning appears
679      #   in several other locations in this file.
680      field_value = self._fields.setdefault(field, field_value)
681    return field_value

Getter for f_direct.

F_INVERSE_FIELD_NUMBER = 2
f_inverse
668  def getter(self):
669    field_value = self._fields.get(field)
670    if field_value is None:
671      # Construct a new object to represent this field.
672      field_value = field._default_constructor(self)
673
674      # Atomically check if another thread has preempted us and, if not, swap
675      # in the new object we just created.  If someone has preempted us, we
676      # take that object and discard ours.
677      # WARNING:  We are relying on setdefault() being atomic.  This is true
678      #   in CPython but we haven't investigated others.  This warning appears
679      #   in several other locations in this file.
680      field_value = self._fields.setdefault(field, field_value)
681    return field_value

Getter for f_inverse.

def FindInitializationErrors(self):
1305  def FindInitializationErrors(self):
1306    """Finds required fields which are not initialized.
1307
1308    Returns:
1309      A list of strings.  Each string is a path to an uninitialized field from
1310      the top-level message, e.g. "foo.bar[5].baz".
1311    """
1312
1313    errors = []  # simplify things
1314
1315    for field in required_fields:
1316      if not self.HasField(field.name):
1317        errors.append(field.name)
1318
1319    for field, value in self.ListFields():
1320      if field.cpp_type == _FieldDescriptor.CPPTYPE_MESSAGE:
1321        if field.is_extension:
1322          name = '(%s)' % field.full_name
1323        else:
1324          name = field.name
1325
1326        if _IsMapField(field):
1327          if _IsMessageMapField(field):
1328            for key in value:
1329              element = value[key]
1330              prefix = '%s[%s].' % (name, key)
1331              sub_errors = element.FindInitializationErrors()
1332              errors += [prefix + error for error in sub_errors]
1333          else:
1334            # ScalarMaps can't have any initialization errors.
1335            pass
1336        elif field.label == _FieldDescriptor.LABEL_REPEATED:
1337          for i in range(len(value)):
1338            element = value[i]
1339            prefix = '%s[%d].' % (name, i)
1340            sub_errors = element.FindInitializationErrors()
1341            errors += [prefix + error for error in sub_errors]
1342        else:
1343          prefix = name + '.'
1344          sub_errors = value.FindInitializationErrors()
1345          errors += [prefix + error for error in sub_errors]
1346
1347    return errors

Finds required fields which are not initialized.

Returns:

A list of strings. Each string is a path to an uninitialized field from the top-level message, e.g. "foo.bar[5].baz".

class AutomatonConstraintProto(google.protobuf.message.Message):

Abstract base class for protocol messages.

Protocol message classes are almost always generated by the protocol compiler. These generated types subclass Message and implement the methods shown below.

AutomatonConstraintProto(**kwargs)
498  def init(self, **kwargs):
499    self._cached_byte_size = 0
500    self._cached_byte_size_dirty = len(kwargs) > 0
501    self._fields = {}
502    # Contains a mapping from oneof field descriptors to the descriptor
503    # of the currently set field in that oneof field.
504    self._oneofs = {}
505
506    # _unknown_fields is () when empty for efficiency, and will be turned into
507    # a list if fields are added.
508    self._unknown_fields = ()
509    self._is_present_in_parent = False
510    self._listener = message_listener_mod.NullMessageListener()
511    self._listener_for_children = _Listener(self)
512    for field_name, field_value in kwargs.items():
513      field = _GetFieldByName(message_descriptor, field_name)
514      if field is None:
515        raise TypeError('%s() got an unexpected keyword argument "%s"' %
516                        (message_descriptor.name, field_name))
517      if field_value is None:
518        # field=None is the same as no field at all.
519        continue
520      if field.label == _FieldDescriptor.LABEL_REPEATED:
521        field_copy = field._default_constructor(self)
522        if field.cpp_type == _FieldDescriptor.CPPTYPE_MESSAGE:  # Composite
523          if _IsMapField(field):
524            if _IsMessageMapField(field):
525              for key in field_value:
526                field_copy[key].MergeFrom(field_value[key])
527            else:
528              field_copy.update(field_value)
529          else:
530            for val in field_value:
531              if isinstance(val, dict):
532                field_copy.add(**val)
533              else:
534                field_copy.add().MergeFrom(val)
535        else:  # Scalar
536          if field.cpp_type == _FieldDescriptor.CPPTYPE_ENUM:
537            field_value = [_GetIntegerEnumValue(field.enum_type, val)
538                           for val in field_value]
539          field_copy.extend(field_value)
540        self._fields[field] = field_copy
541      elif field.cpp_type == _FieldDescriptor.CPPTYPE_MESSAGE:
542        field_copy = field._default_constructor(self)
543        new_val = None
544        if isinstance(field_value, message_mod.Message):
545          new_val = field_value
546        elif isinstance(field_value, dict):
547          if field.message_type.full_name == _StructFullTypeName:
548            field_copy.Clear()
549            if len(field_value) == 1 and 'fields' in field_value:
550              try:
551                field_copy.update(field_value)
552              except:
553                # Fall back to init normal message field
554                field_copy.Clear()
555                new_val = field.message_type._concrete_class(**field_value)
556            else:
557              field_copy.update(field_value)
558          else:
559            new_val = field.message_type._concrete_class(**field_value)
560        elif hasattr(field_copy, '_internal_assign'):
561          field_copy._internal_assign(field_value)
562        else:
563          raise TypeError(
564              'Message field {0}.{1} must be initialized with a '
565              'dict or instance of same class, got {2}.'.format(
566                  message_descriptor.name,
567                  field_name,
568                  type(field_value).__name__,
569              )
570          )
571
572        if new_val != None:
573          try:
574            field_copy.MergeFrom(new_val)
575          except TypeError:
576            _ReraiseTypeErrorWithFieldName(message_descriptor.name, field_name)
577        self._fields[field] = field_copy
578      else:
579        if field.cpp_type == _FieldDescriptor.CPPTYPE_ENUM:
580          field_value = _GetIntegerEnumValue(field.enum_type, field_value)
581        try:
582          setattr(self, field_name, field_value)
583        except TypeError:
584          _ReraiseTypeErrorWithFieldName(message_descriptor.name, field_name)
DESCRIPTOR = <google.protobuf.descriptor.Descriptor object>
def MergeFrom(self, msg):
1364  def MergeFrom(self, msg):
1365    if not isinstance(msg, cls):
1366      raise TypeError(
1367          'Parameter to MergeFrom() must be instance of same class: '
1368          'expected %s got %s.' % (_FullyQualifiedClassName(cls),
1369                                   _FullyQualifiedClassName(msg.__class__)))
1370
1371    assert msg is not self
1372    self._Modified()
1373
1374    fields = self._fields
1375
1376    for field, value in msg._fields.items():
1377      if field.label == LABEL_REPEATED:
1378        field_value = fields.get(field)
1379        if field_value is None:
1380          # Construct a new object to represent this field.
1381          field_value = field._default_constructor(self)
1382          fields[field] = field_value
1383        field_value.MergeFrom(value)
1384      elif field.cpp_type == CPPTYPE_MESSAGE:
1385        if value._is_present_in_parent:
1386          field_value = fields.get(field)
1387          if field_value is None:
1388            # Construct a new object to represent this field.
1389            field_value = field._default_constructor(self)
1390            fields[field] = field_value
1391          field_value.MergeFrom(value)
1392      else:
1393        self._fields[field] = value
1394        if field.containing_oneof:
1395          self._UpdateOneofState(field)
1396
1397    if msg._unknown_fields:
1398      if not self._unknown_fields:
1399        self._unknown_fields = []
1400      self._unknown_fields.extend(msg._unknown_fields)

Merges the contents of the specified message into current message.

This method merges the contents of the specified message into the current message. Singular fields that are set in the specified message overwrite the corresponding fields in the current message. Repeated fields are appended. Singular sub-messages and groups are recursively merged.

Arguments:
  • other_msg (Message): A message to merge into the current message.
def Clear(self):
1423def _Clear(self):
1424  # Clear fields.
1425  self._fields = {}
1426  self._unknown_fields = ()
1427
1428  self._oneofs = {}
1429  self._Modified()

Clears all data that was set in the message.

def SetInParent(self):
1489  def Modified(self):
1490    """Sets the _cached_byte_size_dirty bit to true,
1491    and propagates this to our listener iff this was a state change.
1492    """
1493
1494    # Note:  Some callers check _cached_byte_size_dirty before calling
1495    #   _Modified() as an extra optimization.  So, if this method is ever
1496    #   changed such that it does stuff even when _cached_byte_size_dirty is
1497    #   already true, the callers need to be updated.
1498    if not self._cached_byte_size_dirty:
1499      self._cached_byte_size_dirty = True
1500      self._listener_for_children.dirty = True
1501      self._is_present_in_parent = True
1502      self._listener.Modified()

Sets the _cached_byte_size_dirty bit to true, and propagates this to our listener iff this was a state change.

def IsInitialized(self, errors=None):
1265  def IsInitialized(self, errors=None):
1266    """Checks if all required fields of a message are set.
1267
1268    Args:
1269      errors:  A list which, if provided, will be populated with the field
1270               paths of all missing required fields.
1271
1272    Returns:
1273      True iff the specified message has all required fields set.
1274    """
1275
1276    # Performance is critical so we avoid HasField() and ListFields().
1277
1278    for field in required_fields:
1279      if (field not in self._fields or
1280          (field.cpp_type == _FieldDescriptor.CPPTYPE_MESSAGE and
1281           not self._fields[field]._is_present_in_parent)):
1282        if errors is not None:
1283          errors.extend(self.FindInitializationErrors())
1284        return False
1285
1286    for field, value in list(self._fields.items()):  # dict can change size!
1287      if field.cpp_type == _FieldDescriptor.CPPTYPE_MESSAGE:
1288        if field.label == _FieldDescriptor.LABEL_REPEATED:
1289          if (field.message_type._is_map_entry):
1290            continue
1291          for element in value:
1292            if not element.IsInitialized():
1293              if errors is not None:
1294                errors.extend(self.FindInitializationErrors())
1295              return False
1296        elif value._is_present_in_parent and not value.IsInitialized():
1297          if errors is not None:
1298            errors.extend(self.FindInitializationErrors())
1299          return False
1300
1301    return True

Checks if all required fields of a message are set.

Arguments:
  • errors: A list which, if provided, will be populated with the field paths of all missing required fields.
Returns:

True iff the specified message has all required fields set.

def MergeFromString(self, serialized):
1180  def MergeFromString(self, serialized):
1181    serialized = memoryview(serialized)
1182    length = len(serialized)
1183    try:
1184      if self._InternalParse(serialized, 0, length) != length:
1185        # The only reason _InternalParse would return early is if it
1186        # encountered an end-group tag.
1187        raise message_mod.DecodeError('Unexpected end-group tag.')
1188    except (IndexError, TypeError):
1189      # Now ord(buf[p:p+1]) == ord('') gets TypeError.
1190      raise message_mod.DecodeError('Truncated message.')
1191    except struct.error as e:
1192      raise message_mod.DecodeError(e)
1193    return length   # Return this for legacy reasons.

Merges serialized protocol buffer data into this message.

When we find a field in serialized that is already present in this message:

  • If it's a "repeated" field, we append to the end of our list.
  • Else, if it's a scalar, we overwrite our field.
  • Else, (it's a nonrepeated composite), we recursively merge into the existing composite.
Arguments:
  • serialized (bytes): Any object that allows us to call memoryview(serialized) to access a string of bytes using the buffer interface.
Returns:

int: The number of bytes read from serialized. For non-group messages, this will always be len(serialized), but for messages which are actually groups, this will generally be less than len(serialized), since we must stop when we reach an END_GROUP tag. Note that if we do stop because of an END_GROUP tag, the number of bytes returned does not include the bytes for the END_GROUP tag information.

Raises:
  • DecodeError: if the input cannot be parsed.
def SerializeToString(self, **kwargs):
1133  def SerializeToString(self, **kwargs):
1134    # Check if the message has all of its required fields set.
1135    if not self.IsInitialized():
1136      raise message_mod.EncodeError(
1137          'Message %s is missing required fields: %s' % (
1138          self.DESCRIPTOR.full_name, ','.join(self.FindInitializationErrors())))
1139    return self.SerializePartialToString(**kwargs)

Serializes the protocol message to a binary string.

Keyword Args:

deterministic (bool): If true, requests deterministic serialization of the protobuf, with predictable ordering of map keys.

Returns:

A binary string representation of the message if all of the required fields in the message are set (i.e. the message is initialized).

Raises:
def SerializePartialToString(self, **kwargs):
1146  def SerializePartialToString(self, **kwargs):
1147    out = BytesIO()
1148    self._InternalSerialize(out.write, **kwargs)
1149    return out.getvalue()

Serializes the protocol message to a binary string.

This method is similar to SerializeToString but doesn't check if the message is initialized.

Keyword Args:

deterministic (bool): If true, requests deterministic serialization of the protobuf, with predictable ordering of map keys.

Returns:

bytes: A serialized representation of the partial message.

def ListFields(self):
848  def ListFields(self):
849    all_fields = [item for item in self._fields.items() if _IsPresent(item)]
850    all_fields.sort(key = lambda item: item[0].number)
851    return all_fields

Returns a list of (FieldDescriptor, value) tuples for present fields.

A message field is non-empty if HasField() would return true. A singular primitive field is non-empty if HasField() would return true in proto2 or it is non zero in proto3. A repeated field is non-empty if it contains at least one element. The fields are ordered by field number.

Returns:

list[tuple(FieldDescriptor, value)]: field descriptors and values for all fields in the message which are not empty. The values vary by field type.

def HasField(self, field_name):
872  def HasField(self, field_name):
873    try:
874      field = hassable_fields[field_name]
875    except KeyError as exc:
876      raise ValueError('Protocol message %s has no non-repeated field "%s" '
877                       'nor has presence is not available for this field.' % (
878                           message_descriptor.full_name, field_name)) from exc
879
880    if isinstance(field, descriptor_mod.OneofDescriptor):
881      try:
882        return HasField(self, self._oneofs[field].name)
883      except KeyError:
884        return False
885    else:
886      if field.cpp_type == _FieldDescriptor.CPPTYPE_MESSAGE:
887        value = self._fields.get(field)
888        return value is not None and value._is_present_in_parent
889      else:
890        return field in self._fields

Checks if a certain field is set for the message.

For a oneof group, checks if any field inside is set. Note that if the field_name is not defined in the message descriptor, ValueError will be raised.

Arguments:
  • field_name (str): The name of the field to check for presence.
Returns:

bool: Whether a value has been set for the named field.

Raises:
  • ValueError: if the field_name is not a member of this message.
def ClearField(self, field_name):
897  def ClearField(self, field_name):
898    try:
899      field = message_descriptor.fields_by_name[field_name]
900    except KeyError:
901      try:
902        field = message_descriptor.oneofs_by_name[field_name]
903        if field in self._oneofs:
904          field = self._oneofs[field]
905        else:
906          return
907      except KeyError:
908        raise ValueError('Protocol message %s has no "%s" field.' %
909                         (message_descriptor.name, field_name))
910
911    if field in self._fields:
912      # To match the C++ implementation, we need to invalidate iterators
913      # for map fields when ClearField() happens.
914      if hasattr(self._fields[field], 'InvalidateIterators'):
915        self._fields[field].InvalidateIterators()
916
917      # Note:  If the field is a sub-message, its listener will still point
918      #   at us.  That's fine, because the worst than can happen is that it
919      #   will call _Modified() and invalidate our byte size.  Big deal.
920      del self._fields[field]
921
922      if self._oneofs.get(field.containing_oneof, None) is field:
923        del self._oneofs[field.containing_oneof]
924
925    # Always call _Modified() -- even if nothing was changed, this is
926    # a mutating method, and thus calling it should cause the field to become
927    # present in the parent message.
928    self._Modified()

Clears the contents of a given field.

Inside a oneof group, clears the field set. If the name neither refers to a defined field or oneof group, ValueError is raised.

Arguments:
  • field_name (str): The name of the field to check for presence.
Raises:
  • ValueError: if the field_name is not a member of this message.
def WhichOneof(self, oneof_name):
1406  def WhichOneof(self, oneof_name):
1407    """Returns the name of the currently set field inside a oneof, or None."""
1408    try:
1409      field = message_descriptor.oneofs_by_name[oneof_name]
1410    except KeyError:
1411      raise ValueError(
1412          'Protocol message has no oneof "%s" field.' % oneof_name)
1413
1414    nested_field = self._oneofs.get(field, None)
1415    if nested_field is not None and self.HasField(nested_field.name):
1416      return nested_field.name
1417    else:
1418      return None

Returns the name of the currently set field inside a oneof, or None.

def DiscardUnknownFields(self):
1438def _DiscardUnknownFields(self):
1439  self._unknown_fields = []
1440  for field, value in self.ListFields():
1441    if field.cpp_type == _FieldDescriptor.CPPTYPE_MESSAGE:
1442      if _IsMapField(field):
1443        if _IsMessageMapField(field):
1444          for key in value:
1445            value[key].DiscardUnknownFields()
1446      elif field.label == _FieldDescriptor.LABEL_REPEATED:
1447        for sub_message in value:
1448          sub_message.DiscardUnknownFields()
1449      else:
1450        value.DiscardUnknownFields()

Clears all fields in the UnknownFieldSet.

This operation is recursive for nested message.

def ByteSize(self):
1101  def ByteSize(self):
1102    if not self._cached_byte_size_dirty:
1103      return self._cached_byte_size
1104
1105    size = 0
1106    descriptor = self.DESCRIPTOR
1107    if descriptor._is_map_entry:
1108      # Fields of map entry should always be serialized.
1109      key_field = descriptor.fields_by_name['key']
1110      _MaybeAddEncoder(cls, key_field)
1111      size = key_field._sizer(self.key)
1112      value_field = descriptor.fields_by_name['value']
1113      _MaybeAddEncoder(cls, value_field)
1114      size += value_field._sizer(self.value)
1115    else:
1116      for field_descriptor, field_value in self.ListFields():
1117        _MaybeAddEncoder(cls, field_descriptor)
1118        size += field_descriptor._sizer(field_value)
1119      for tag_bytes, value_bytes in self._unknown_fields:
1120        size += len(tag_bytes) + len(value_bytes)
1121
1122    self._cached_byte_size = size
1123    self._cached_byte_size_dirty = False
1124    self._listener_for_children.dirty = False
1125    return size

Returns the serialized size of this message.

Recursively calls ByteSize() on all contained messages.

Returns:

int: The number of bytes required to serialize this message.

def FromString(s):
826  def FromString(s):
827    message = cls()
828    message.MergeFromString(s)
829    return message
STARTING_STATE_FIELD_NUMBER = 2
starting_state
711  def getter(self):
712    # TODO: This may be broken since there may not be
713    # default_value.  Combine with has_default_value somehow.
714    return self._fields.get(field, default_value)

Getter for starting_state.

FINAL_STATES_FIELD_NUMBER = 3
final_states
668  def getter(self):
669    field_value = self._fields.get(field)
670    if field_value is None:
671      # Construct a new object to represent this field.
672      field_value = field._default_constructor(self)
673
674      # Atomically check if another thread has preempted us and, if not, swap
675      # in the new object we just created.  If someone has preempted us, we
676      # take that object and discard ours.
677      # WARNING:  We are relying on setdefault() being atomic.  This is true
678      #   in CPython but we haven't investigated others.  This warning appears
679      #   in several other locations in this file.
680      field_value = self._fields.setdefault(field, field_value)
681    return field_value

Getter for final_states.

TRANSITION_TAIL_FIELD_NUMBER = 4
transition_tail
668  def getter(self):
669    field_value = self._fields.get(field)
670    if field_value is None:
671      # Construct a new object to represent this field.
672      field_value = field._default_constructor(self)
673
674      # Atomically check if another thread has preempted us and, if not, swap
675      # in the new object we just created.  If someone has preempted us, we
676      # take that object and discard ours.
677      # WARNING:  We are relying on setdefault() being atomic.  This is true
678      #   in CPython but we haven't investigated others.  This warning appears
679      #   in several other locations in this file.
680      field_value = self._fields.setdefault(field, field_value)
681    return field_value

Getter for transition_tail.

TRANSITION_HEAD_FIELD_NUMBER = 5
transition_head
668  def getter(self):
669    field_value = self._fields.get(field)
670    if field_value is None:
671      # Construct a new object to represent this field.
672      field_value = field._default_constructor(self)
673
674      # Atomically check if another thread has preempted us and, if not, swap
675      # in the new object we just created.  If someone has preempted us, we
676      # take that object and discard ours.
677      # WARNING:  We are relying on setdefault() being atomic.  This is true
678      #   in CPython but we haven't investigated others.  This warning appears
679      #   in several other locations in this file.
680      field_value = self._fields.setdefault(field, field_value)
681    return field_value

Getter for transition_head.

TRANSITION_LABEL_FIELD_NUMBER = 6
transition_label
668  def getter(self):
669    field_value = self._fields.get(field)
670    if field_value is None:
671      # Construct a new object to represent this field.
672      field_value = field._default_constructor(self)
673
674      # Atomically check if another thread has preempted us and, if not, swap
675      # in the new object we just created.  If someone has preempted us, we
676      # take that object and discard ours.
677      # WARNING:  We are relying on setdefault() being atomic.  This is true
678      #   in CPython but we haven't investigated others.  This warning appears
679      #   in several other locations in this file.
680      field_value = self._fields.setdefault(field, field_value)
681    return field_value

Getter for transition_label.

VARS_FIELD_NUMBER = 7
vars
668  def getter(self):
669    field_value = self._fields.get(field)
670    if field_value is None:
671      # Construct a new object to represent this field.
672      field_value = field._default_constructor(self)
673
674      # Atomically check if another thread has preempted us and, if not, swap
675      # in the new object we just created.  If someone has preempted us, we
676      # take that object and discard ours.
677      # WARNING:  We are relying on setdefault() being atomic.  This is true
678      #   in CPython but we haven't investigated others.  This warning appears
679      #   in several other locations in this file.
680      field_value = self._fields.setdefault(field, field_value)
681    return field_value

Getter for vars.

EXPRS_FIELD_NUMBER = 8
exprs
668  def getter(self):
669    field_value = self._fields.get(field)
670    if field_value is None:
671      # Construct a new object to represent this field.
672      field_value = field._default_constructor(self)
673
674      # Atomically check if another thread has preempted us and, if not, swap
675      # in the new object we just created.  If someone has preempted us, we
676      # take that object and discard ours.
677      # WARNING:  We are relying on setdefault() being atomic.  This is true
678      #   in CPython but we haven't investigated others.  This warning appears
679      #   in several other locations in this file.
680      field_value = self._fields.setdefault(field, field_value)
681    return field_value

Getter for exprs.

def FindInitializationErrors(self):
1305  def FindInitializationErrors(self):
1306    """Finds required fields which are not initialized.
1307
1308    Returns:
1309      A list of strings.  Each string is a path to an uninitialized field from
1310      the top-level message, e.g. "foo.bar[5].baz".
1311    """
1312
1313    errors = []  # simplify things
1314
1315    for field in required_fields:
1316      if not self.HasField(field.name):
1317        errors.append(field.name)
1318
1319    for field, value in self.ListFields():
1320      if field.cpp_type == _FieldDescriptor.CPPTYPE_MESSAGE:
1321        if field.is_extension:
1322          name = '(%s)' % field.full_name
1323        else:
1324          name = field.name
1325
1326        if _IsMapField(field):
1327          if _IsMessageMapField(field):
1328            for key in value:
1329              element = value[key]
1330              prefix = '%s[%s].' % (name, key)
1331              sub_errors = element.FindInitializationErrors()
1332              errors += [prefix + error for error in sub_errors]
1333          else:
1334            # ScalarMaps can't have any initialization errors.
1335            pass
1336        elif field.label == _FieldDescriptor.LABEL_REPEATED:
1337          for i in range(len(value)):
1338            element = value[i]
1339            prefix = '%s[%d].' % (name, i)
1340            sub_errors = element.FindInitializationErrors()
1341            errors += [prefix + error for error in sub_errors]
1342        else:
1343          prefix = name + '.'
1344          sub_errors = value.FindInitializationErrors()
1345          errors += [prefix + error for error in sub_errors]
1346
1347    return errors

Finds required fields which are not initialized.

Returns:

A list of strings. Each string is a path to an uninitialized field from the top-level message, e.g. "foo.bar[5].baz".

class ListOfVariablesProto(google.protobuf.message.Message):

Abstract base class for protocol messages.

Protocol message classes are almost always generated by the protocol compiler. These generated types subclass Message and implement the methods shown below.

ListOfVariablesProto(**kwargs)
498  def init(self, **kwargs):
499    self._cached_byte_size = 0
500    self._cached_byte_size_dirty = len(kwargs) > 0
501    self._fields = {}
502    # Contains a mapping from oneof field descriptors to the descriptor
503    # of the currently set field in that oneof field.
504    self._oneofs = {}
505
506    # _unknown_fields is () when empty for efficiency, and will be turned into
507    # a list if fields are added.
508    self._unknown_fields = ()
509    self._is_present_in_parent = False
510    self._listener = message_listener_mod.NullMessageListener()
511    self._listener_for_children = _Listener(self)
512    for field_name, field_value in kwargs.items():
513      field = _GetFieldByName(message_descriptor, field_name)
514      if field is None:
515        raise TypeError('%s() got an unexpected keyword argument "%s"' %
516                        (message_descriptor.name, field_name))
517      if field_value is None:
518        # field=None is the same as no field at all.
519        continue
520      if field.label == _FieldDescriptor.LABEL_REPEATED:
521        field_copy = field._default_constructor(self)
522        if field.cpp_type == _FieldDescriptor.CPPTYPE_MESSAGE:  # Composite
523          if _IsMapField(field):
524            if _IsMessageMapField(field):
525              for key in field_value:
526                field_copy[key].MergeFrom(field_value[key])
527            else:
528              field_copy.update(field_value)
529          else:
530            for val in field_value:
531              if isinstance(val, dict):
532                field_copy.add(**val)
533              else:
534                field_copy.add().MergeFrom(val)
535        else:  # Scalar
536          if field.cpp_type == _FieldDescriptor.CPPTYPE_ENUM:
537            field_value = [_GetIntegerEnumValue(field.enum_type, val)
538                           for val in field_value]
539          field_copy.extend(field_value)
540        self._fields[field] = field_copy
541      elif field.cpp_type == _FieldDescriptor.CPPTYPE_MESSAGE:
542        field_copy = field._default_constructor(self)
543        new_val = None
544        if isinstance(field_value, message_mod.Message):
545          new_val = field_value
546        elif isinstance(field_value, dict):
547          if field.message_type.full_name == _StructFullTypeName:
548            field_copy.Clear()
549            if len(field_value) == 1 and 'fields' in field_value:
550              try:
551                field_copy.update(field_value)
552              except:
553                # Fall back to init normal message field
554                field_copy.Clear()
555                new_val = field.message_type._concrete_class(**field_value)
556            else:
557              field_copy.update(field_value)
558          else:
559            new_val = field.message_type._concrete_class(**field_value)
560        elif hasattr(field_copy, '_internal_assign'):
561          field_copy._internal_assign(field_value)
562        else:
563          raise TypeError(
564              'Message field {0}.{1} must be initialized with a '
565              'dict or instance of same class, got {2}.'.format(
566                  message_descriptor.name,
567                  field_name,
568                  type(field_value).__name__,
569              )
570          )
571
572        if new_val != None:
573          try:
574            field_copy.MergeFrom(new_val)
575          except TypeError:
576            _ReraiseTypeErrorWithFieldName(message_descriptor.name, field_name)
577        self._fields[field] = field_copy
578      else:
579        if field.cpp_type == _FieldDescriptor.CPPTYPE_ENUM:
580          field_value = _GetIntegerEnumValue(field.enum_type, field_value)
581        try:
582          setattr(self, field_name, field_value)
583        except TypeError:
584          _ReraiseTypeErrorWithFieldName(message_descriptor.name, field_name)
DESCRIPTOR = <google.protobuf.descriptor.Descriptor object>
def MergeFrom(self, msg):
1364  def MergeFrom(self, msg):
1365    if not isinstance(msg, cls):
1366      raise TypeError(
1367          'Parameter to MergeFrom() must be instance of same class: '
1368          'expected %s got %s.' % (_FullyQualifiedClassName(cls),
1369                                   _FullyQualifiedClassName(msg.__class__)))
1370
1371    assert msg is not self
1372    self._Modified()
1373
1374    fields = self._fields
1375
1376    for field, value in msg._fields.items():
1377      if field.label == LABEL_REPEATED:
1378        field_value = fields.get(field)
1379        if field_value is None:
1380          # Construct a new object to represent this field.
1381          field_value = field._default_constructor(self)
1382          fields[field] = field_value
1383        field_value.MergeFrom(value)
1384      elif field.cpp_type == CPPTYPE_MESSAGE:
1385        if value._is_present_in_parent:
1386          field_value = fields.get(field)
1387          if field_value is None:
1388            # Construct a new object to represent this field.
1389            field_value = field._default_constructor(self)
1390            fields[field] = field_value
1391          field_value.MergeFrom(value)
1392      else:
1393        self._fields[field] = value
1394        if field.containing_oneof:
1395          self._UpdateOneofState(field)
1396
1397    if msg._unknown_fields:
1398      if not self._unknown_fields:
1399        self._unknown_fields = []
1400      self._unknown_fields.extend(msg._unknown_fields)

Merges the contents of the specified message into current message.

This method merges the contents of the specified message into the current message. Singular fields that are set in the specified message overwrite the corresponding fields in the current message. Repeated fields are appended. Singular sub-messages and groups are recursively merged.

Arguments:
  • other_msg (Message): A message to merge into the current message.
def Clear(self):
1423def _Clear(self):
1424  # Clear fields.
1425  self._fields = {}
1426  self._unknown_fields = ()
1427
1428  self._oneofs = {}
1429  self._Modified()

Clears all data that was set in the message.

def SetInParent(self):
1489  def Modified(self):
1490    """Sets the _cached_byte_size_dirty bit to true,
1491    and propagates this to our listener iff this was a state change.
1492    """
1493
1494    # Note:  Some callers check _cached_byte_size_dirty before calling
1495    #   _Modified() as an extra optimization.  So, if this method is ever
1496    #   changed such that it does stuff even when _cached_byte_size_dirty is
1497    #   already true, the callers need to be updated.
1498    if not self._cached_byte_size_dirty:
1499      self._cached_byte_size_dirty = True
1500      self._listener_for_children.dirty = True
1501      self._is_present_in_parent = True
1502      self._listener.Modified()

Sets the _cached_byte_size_dirty bit to true, and propagates this to our listener iff this was a state change.

def IsInitialized(self, errors=None):
1265  def IsInitialized(self, errors=None):
1266    """Checks if all required fields of a message are set.
1267
1268    Args:
1269      errors:  A list which, if provided, will be populated with the field
1270               paths of all missing required fields.
1271
1272    Returns:
1273      True iff the specified message has all required fields set.
1274    """
1275
1276    # Performance is critical so we avoid HasField() and ListFields().
1277
1278    for field in required_fields:
1279      if (field not in self._fields or
1280          (field.cpp_type == _FieldDescriptor.CPPTYPE_MESSAGE and
1281           not self._fields[field]._is_present_in_parent)):
1282        if errors is not None:
1283          errors.extend(self.FindInitializationErrors())
1284        return False
1285
1286    for field, value in list(self._fields.items()):  # dict can change size!
1287      if field.cpp_type == _FieldDescriptor.CPPTYPE_MESSAGE:
1288        if field.label == _FieldDescriptor.LABEL_REPEATED:
1289          if (field.message_type._is_map_entry):
1290            continue
1291          for element in value:
1292            if not element.IsInitialized():
1293              if errors is not None:
1294                errors.extend(self.FindInitializationErrors())
1295              return False
1296        elif value._is_present_in_parent and not value.IsInitialized():
1297          if errors is not None:
1298            errors.extend(self.FindInitializationErrors())
1299          return False
1300
1301    return True

Checks if all required fields of a message are set.

Arguments:
  • errors: A list which, if provided, will be populated with the field paths of all missing required fields.
Returns:

True iff the specified message has all required fields set.

def MergeFromString(self, serialized):
1180  def MergeFromString(self, serialized):
1181    serialized = memoryview(serialized)
1182    length = len(serialized)
1183    try:
1184      if self._InternalParse(serialized, 0, length) != length:
1185        # The only reason _InternalParse would return early is if it
1186        # encountered an end-group tag.
1187        raise message_mod.DecodeError('Unexpected end-group tag.')
1188    except (IndexError, TypeError):
1189      # Now ord(buf[p:p+1]) == ord('') gets TypeError.
1190      raise message_mod.DecodeError('Truncated message.')
1191    except struct.error as e:
1192      raise message_mod.DecodeError(e)
1193    return length   # Return this for legacy reasons.

Merges serialized protocol buffer data into this message.

When we find a field in serialized that is already present in this message:

  • If it's a "repeated" field, we append to the end of our list.
  • Else, if it's a scalar, we overwrite our field.
  • Else, (it's a nonrepeated composite), we recursively merge into the existing composite.
Arguments:
  • serialized (bytes): Any object that allows us to call memoryview(serialized) to access a string of bytes using the buffer interface.
Returns:

int: The number of bytes read from serialized. For non-group messages, this will always be len(serialized), but for messages which are actually groups, this will generally be less than len(serialized), since we must stop when we reach an END_GROUP tag. Note that if we do stop because of an END_GROUP tag, the number of bytes returned does not include the bytes for the END_GROUP tag information.

Raises:
  • DecodeError: if the input cannot be parsed.
def SerializeToString(self, **kwargs):
1133  def SerializeToString(self, **kwargs):
1134    # Check if the message has all of its required fields set.
1135    if not self.IsInitialized():
1136      raise message_mod.EncodeError(
1137          'Message %s is missing required fields: %s' % (
1138          self.DESCRIPTOR.full_name, ','.join(self.FindInitializationErrors())))
1139    return self.SerializePartialToString(**kwargs)

Serializes the protocol message to a binary string.

Keyword Args:

deterministic (bool): If true, requests deterministic serialization of the protobuf, with predictable ordering of map keys.

Returns:

A binary string representation of the message if all of the required fields in the message are set (i.e. the message is initialized).

Raises:
def SerializePartialToString(self, **kwargs):
1146  def SerializePartialToString(self, **kwargs):
1147    out = BytesIO()
1148    self._InternalSerialize(out.write, **kwargs)
1149    return out.getvalue()

Serializes the protocol message to a binary string.

This method is similar to SerializeToString but doesn't check if the message is initialized.

Keyword Args:

deterministic (bool): If true, requests deterministic serialization of the protobuf, with predictable ordering of map keys.

Returns:

bytes: A serialized representation of the partial message.

def ListFields(self):
848  def ListFields(self):
849    all_fields = [item for item in self._fields.items() if _IsPresent(item)]
850    all_fields.sort(key = lambda item: item[0].number)
851    return all_fields

Returns a list of (FieldDescriptor, value) tuples for present fields.

A message field is non-empty if HasField() would return true. A singular primitive field is non-empty if HasField() would return true in proto2 or it is non zero in proto3. A repeated field is non-empty if it contains at least one element. The fields are ordered by field number.

Returns:

list[tuple(FieldDescriptor, value)]: field descriptors and values for all fields in the message which are not empty. The values vary by field type.

def HasField(self, field_name):
872  def HasField(self, field_name):
873    try:
874      field = hassable_fields[field_name]
875    except KeyError as exc:
876      raise ValueError('Protocol message %s has no non-repeated field "%s" '
877                       'nor has presence is not available for this field.' % (
878                           message_descriptor.full_name, field_name)) from exc
879
880    if isinstance(field, descriptor_mod.OneofDescriptor):
881      try:
882        return HasField(self, self._oneofs[field].name)
883      except KeyError:
884        return False
885    else:
886      if field.cpp_type == _FieldDescriptor.CPPTYPE_MESSAGE:
887        value = self._fields.get(field)
888        return value is not None and value._is_present_in_parent
889      else:
890        return field in self._fields

Checks if a certain field is set for the message.

For a oneof group, checks if any field inside is set. Note that if the field_name is not defined in the message descriptor, ValueError will be raised.

Arguments:
  • field_name (str): The name of the field to check for presence.
Returns:

bool: Whether a value has been set for the named field.

Raises:
  • ValueError: if the field_name is not a member of this message.
def ClearField(self, field_name):
897  def ClearField(self, field_name):
898    try:
899      field = message_descriptor.fields_by_name[field_name]
900    except KeyError:
901      try:
902        field = message_descriptor.oneofs_by_name[field_name]
903        if field in self._oneofs:
904          field = self._oneofs[field]
905        else:
906          return
907      except KeyError:
908        raise ValueError('Protocol message %s has no "%s" field.' %
909                         (message_descriptor.name, field_name))
910
911    if field in self._fields:
912      # To match the C++ implementation, we need to invalidate iterators
913      # for map fields when ClearField() happens.
914      if hasattr(self._fields[field], 'InvalidateIterators'):
915        self._fields[field].InvalidateIterators()
916
917      # Note:  If the field is a sub-message, its listener will still point
918      #   at us.  That's fine, because the worst than can happen is that it
919      #   will call _Modified() and invalidate our byte size.  Big deal.
920      del self._fields[field]
921
922      if self._oneofs.get(field.containing_oneof, None) is field:
923        del self._oneofs[field.containing_oneof]
924
925    # Always call _Modified() -- even if nothing was changed, this is
926    # a mutating method, and thus calling it should cause the field to become
927    # present in the parent message.
928    self._Modified()

Clears the contents of a given field.

Inside a oneof group, clears the field set. If the name neither refers to a defined field or oneof group, ValueError is raised.

Arguments:
  • field_name (str): The name of the field to check for presence.
Raises:
  • ValueError: if the field_name is not a member of this message.
def WhichOneof(self, oneof_name):
1406  def WhichOneof(self, oneof_name):
1407    """Returns the name of the currently set field inside a oneof, or None."""
1408    try:
1409      field = message_descriptor.oneofs_by_name[oneof_name]
1410    except KeyError:
1411      raise ValueError(
1412          'Protocol message has no oneof "%s" field.' % oneof_name)
1413
1414    nested_field = self._oneofs.get(field, None)
1415    if nested_field is not None and self.HasField(nested_field.name):
1416      return nested_field.name
1417    else:
1418      return None

Returns the name of the currently set field inside a oneof, or None.

def DiscardUnknownFields(self):
1438def _DiscardUnknownFields(self):
1439  self._unknown_fields = []
1440  for field, value in self.ListFields():
1441    if field.cpp_type == _FieldDescriptor.CPPTYPE_MESSAGE:
1442      if _IsMapField(field):
1443        if _IsMessageMapField(field):
1444          for key in value:
1445            value[key].DiscardUnknownFields()
1446      elif field.label == _FieldDescriptor.LABEL_REPEATED:
1447        for sub_message in value:
1448          sub_message.DiscardUnknownFields()
1449      else:
1450        value.DiscardUnknownFields()

Clears all fields in the UnknownFieldSet.

This operation is recursive for nested message.

def ByteSize(self):
1101  def ByteSize(self):
1102    if not self._cached_byte_size_dirty:
1103      return self._cached_byte_size
1104
1105    size = 0
1106    descriptor = self.DESCRIPTOR
1107    if descriptor._is_map_entry:
1108      # Fields of map entry should always be serialized.
1109      key_field = descriptor.fields_by_name['key']
1110      _MaybeAddEncoder(cls, key_field)
1111      size = key_field._sizer(self.key)
1112      value_field = descriptor.fields_by_name['value']
1113      _MaybeAddEncoder(cls, value_field)
1114      size += value_field._sizer(self.value)
1115    else:
1116      for field_descriptor, field_value in self.ListFields():
1117        _MaybeAddEncoder(cls, field_descriptor)
1118        size += field_descriptor._sizer(field_value)
1119      for tag_bytes, value_bytes in self._unknown_fields:
1120        size += len(tag_bytes) + len(value_bytes)
1121
1122    self._cached_byte_size = size
1123    self._cached_byte_size_dirty = False
1124    self._listener_for_children.dirty = False
1125    return size

Returns the serialized size of this message.

Recursively calls ByteSize() on all contained messages.

Returns:

int: The number of bytes required to serialize this message.

def FromString(s):
826  def FromString(s):
827    message = cls()
828    message.MergeFromString(s)
829    return message
VARS_FIELD_NUMBER = 1
vars
668  def getter(self):
669    field_value = self._fields.get(field)
670    if field_value is None:
671      # Construct a new object to represent this field.
672      field_value = field._default_constructor(self)
673
674      # Atomically check if another thread has preempted us and, if not, swap
675      # in the new object we just created.  If someone has preempted us, we
676      # take that object and discard ours.
677      # WARNING:  We are relying on setdefault() being atomic.  This is true
678      #   in CPython but we haven't investigated others.  This warning appears
679      #   in several other locations in this file.
680      field_value = self._fields.setdefault(field, field_value)
681    return field_value

Getter for vars.

def FindInitializationErrors(self):
1305  def FindInitializationErrors(self):
1306    """Finds required fields which are not initialized.
1307
1308    Returns:
1309      A list of strings.  Each string is a path to an uninitialized field from
1310      the top-level message, e.g. "foo.bar[5].baz".
1311    """
1312
1313    errors = []  # simplify things
1314
1315    for field in required_fields:
1316      if not self.HasField(field.name):
1317        errors.append(field.name)
1318
1319    for field, value in self.ListFields():
1320      if field.cpp_type == _FieldDescriptor.CPPTYPE_MESSAGE:
1321        if field.is_extension:
1322          name = '(%s)' % field.full_name
1323        else:
1324          name = field.name
1325
1326        if _IsMapField(field):
1327          if _IsMessageMapField(field):
1328            for key in value:
1329              element = value[key]
1330              prefix = '%s[%s].' % (name, key)
1331              sub_errors = element.FindInitializationErrors()
1332              errors += [prefix + error for error in sub_errors]
1333          else:
1334            # ScalarMaps can't have any initialization errors.
1335            pass
1336        elif field.label == _FieldDescriptor.LABEL_REPEATED:
1337          for i in range(len(value)):
1338            element = value[i]
1339            prefix = '%s[%d].' % (name, i)
1340            sub_errors = element.FindInitializationErrors()
1341            errors += [prefix + error for error in sub_errors]
1342        else:
1343          prefix = name + '.'
1344          sub_errors = value.FindInitializationErrors()
1345          errors += [prefix + error for error in sub_errors]
1346
1347    return errors

Finds required fields which are not initialized.

Returns:

A list of strings. Each string is a path to an uninitialized field from the top-level message, e.g. "foo.bar[5].baz".

class ConstraintProto(google.protobuf.message.Message):

Abstract base class for protocol messages.

Protocol message classes are almost always generated by the protocol compiler. These generated types subclass Message and implement the methods shown below.

ConstraintProto(**kwargs)
498  def init(self, **kwargs):
499    self._cached_byte_size = 0
500    self._cached_byte_size_dirty = len(kwargs) > 0
501    self._fields = {}
502    # Contains a mapping from oneof field descriptors to the descriptor
503    # of the currently set field in that oneof field.
504    self._oneofs = {}
505
506    # _unknown_fields is () when empty for efficiency, and will be turned into
507    # a list if fields are added.
508    self._unknown_fields = ()
509    self._is_present_in_parent = False
510    self._listener = message_listener_mod.NullMessageListener()
511    self._listener_for_children = _Listener(self)
512    for field_name, field_value in kwargs.items():
513      field = _GetFieldByName(message_descriptor, field_name)
514      if field is None:
515        raise TypeError('%s() got an unexpected keyword argument "%s"' %
516                        (message_descriptor.name, field_name))
517      if field_value is None:
518        # field=None is the same as no field at all.
519        continue
520      if field.label == _FieldDescriptor.LABEL_REPEATED:
521        field_copy = field._default_constructor(self)
522        if field.cpp_type == _FieldDescriptor.CPPTYPE_MESSAGE:  # Composite
523          if _IsMapField(field):
524            if _IsMessageMapField(field):
525              for key in field_value:
526                field_copy[key].MergeFrom(field_value[key])
527            else:
528              field_copy.update(field_value)
529          else:
530            for val in field_value:
531              if isinstance(val, dict):
532                field_copy.add(**val)
533              else:
534                field_copy.add().MergeFrom(val)
535        else:  # Scalar
536          if field.cpp_type == _FieldDescriptor.CPPTYPE_ENUM:
537            field_value = [_GetIntegerEnumValue(field.enum_type, val)
538                           for val in field_value]
539          field_copy.extend(field_value)
540        self._fields[field] = field_copy
541      elif field.cpp_type == _FieldDescriptor.CPPTYPE_MESSAGE:
542        field_copy = field._default_constructor(self)
543        new_val = None
544        if isinstance(field_value, message_mod.Message):
545          new_val = field_value
546        elif isinstance(field_value, dict):
547          if field.message_type.full_name == _StructFullTypeName:
548            field_copy.Clear()
549            if len(field_value) == 1 and 'fields' in field_value:
550              try:
551                field_copy.update(field_value)
552              except:
553                # Fall back to init normal message field
554                field_copy.Clear()
555                new_val = field.message_type._concrete_class(**field_value)
556            else:
557              field_copy.update(field_value)
558          else:
559            new_val = field.message_type._concrete_class(**field_value)
560        elif hasattr(field_copy, '_internal_assign'):
561          field_copy._internal_assign(field_value)
562        else:
563          raise TypeError(
564              'Message field {0}.{1} must be initialized with a '
565              'dict or instance of same class, got {2}.'.format(
566                  message_descriptor.name,
567                  field_name,
568                  type(field_value).__name__,
569              )
570          )
571
572        if new_val != None:
573          try:
574            field_copy.MergeFrom(new_val)
575          except TypeError:
576            _ReraiseTypeErrorWithFieldName(message_descriptor.name, field_name)
577        self._fields[field] = field_copy
578      else:
579        if field.cpp_type == _FieldDescriptor.CPPTYPE_ENUM:
580          field_value = _GetIntegerEnumValue(field.enum_type, field_value)
581        try:
582          setattr(self, field_name, field_value)
583        except TypeError:
584          _ReraiseTypeErrorWithFieldName(message_descriptor.name, field_name)
DESCRIPTOR = <google.protobuf.descriptor.Descriptor object>
def MergeFrom(self, msg):
1364  def MergeFrom(self, msg):
1365    if not isinstance(msg, cls):
1366      raise TypeError(
1367          'Parameter to MergeFrom() must be instance of same class: '
1368          'expected %s got %s.' % (_FullyQualifiedClassName(cls),
1369                                   _FullyQualifiedClassName(msg.__class__)))
1370
1371    assert msg is not self
1372    self._Modified()
1373
1374    fields = self._fields
1375
1376    for field, value in msg._fields.items():
1377      if field.label == LABEL_REPEATED:
1378        field_value = fields.get(field)
1379        if field_value is None:
1380          # Construct a new object to represent this field.
1381          field_value = field._default_constructor(self)
1382          fields[field] = field_value
1383        field_value.MergeFrom(value)
1384      elif field.cpp_type == CPPTYPE_MESSAGE:
1385        if value._is_present_in_parent:
1386          field_value = fields.get(field)
1387          if field_value is None:
1388            # Construct a new object to represent this field.
1389            field_value = field._default_constructor(self)
1390            fields[field] = field_value
1391          field_value.MergeFrom(value)
1392      else:
1393        self._fields[field] = value
1394        if field.containing_oneof:
1395          self._UpdateOneofState(field)
1396
1397    if msg._unknown_fields:
1398      if not self._unknown_fields:
1399        self._unknown_fields = []
1400      self._unknown_fields.extend(msg._unknown_fields)

Merges the contents of the specified message into current message.

This method merges the contents of the specified message into the current message. Singular fields that are set in the specified message overwrite the corresponding fields in the current message. Repeated fields are appended. Singular sub-messages and groups are recursively merged.

Arguments:
  • other_msg (Message): A message to merge into the current message.
def Clear(self):
1423def _Clear(self):
1424  # Clear fields.
1425  self._fields = {}
1426  self._unknown_fields = ()
1427
1428  self._oneofs = {}
1429  self._Modified()

Clears all data that was set in the message.

def SetInParent(self):
1489  def Modified(self):
1490    """Sets the _cached_byte_size_dirty bit to true,
1491    and propagates this to our listener iff this was a state change.
1492    """
1493
1494    # Note:  Some callers check _cached_byte_size_dirty before calling
1495    #   _Modified() as an extra optimization.  So, if this method is ever
1496    #   changed such that it does stuff even when _cached_byte_size_dirty is
1497    #   already true, the callers need to be updated.
1498    if not self._cached_byte_size_dirty:
1499      self._cached_byte_size_dirty = True
1500      self._listener_for_children.dirty = True
1501      self._is_present_in_parent = True
1502      self._listener.Modified()

Sets the _cached_byte_size_dirty bit to true, and propagates this to our listener iff this was a state change.

def IsInitialized(self, errors=None):
1265  def IsInitialized(self, errors=None):
1266    """Checks if all required fields of a message are set.
1267
1268    Args:
1269      errors:  A list which, if provided, will be populated with the field
1270               paths of all missing required fields.
1271
1272    Returns:
1273      True iff the specified message has all required fields set.
1274    """
1275
1276    # Performance is critical so we avoid HasField() and ListFields().
1277
1278    for field in required_fields:
1279      if (field not in self._fields or
1280          (field.cpp_type == _FieldDescriptor.CPPTYPE_MESSAGE and
1281           not self._fields[field]._is_present_in_parent)):
1282        if errors is not None:
1283          errors.extend(self.FindInitializationErrors())
1284        return False
1285
1286    for field, value in list(self._fields.items()):  # dict can change size!
1287      if field.cpp_type == _FieldDescriptor.CPPTYPE_MESSAGE:
1288        if field.label == _FieldDescriptor.LABEL_REPEATED:
1289          if (field.message_type._is_map_entry):
1290            continue
1291          for element in value:
1292            if not element.IsInitialized():
1293              if errors is not None:
1294                errors.extend(self.FindInitializationErrors())
1295              return False
1296        elif value._is_present_in_parent and not value.IsInitialized():
1297          if errors is not None:
1298            errors.extend(self.FindInitializationErrors())
1299          return False
1300
1301    return True

Checks if all required fields of a message are set.

Arguments:
  • errors: A list which, if provided, will be populated with the field paths of all missing required fields.
Returns:

True iff the specified message has all required fields set.

def MergeFromString(self, serialized):
1180  def MergeFromString(self, serialized):
1181    serialized = memoryview(serialized)
1182    length = len(serialized)
1183    try:
1184      if self._InternalParse(serialized, 0, length) != length:
1185        # The only reason _InternalParse would return early is if it
1186        # encountered an end-group tag.
1187        raise message_mod.DecodeError('Unexpected end-group tag.')
1188    except (IndexError, TypeError):
1189      # Now ord(buf[p:p+1]) == ord('') gets TypeError.
1190      raise message_mod.DecodeError('Truncated message.')
1191    except struct.error as e:
1192      raise message_mod.DecodeError(e)
1193    return length   # Return this for legacy reasons.

Merges serialized protocol buffer data into this message.

When we find a field in serialized that is already present in this message:

  • If it's a "repeated" field, we append to the end of our list.
  • Else, if it's a scalar, we overwrite our field.
  • Else, (it's a nonrepeated composite), we recursively merge into the existing composite.
Arguments:
  • serialized (bytes): Any object that allows us to call memoryview(serialized) to access a string of bytes using the buffer interface.
Returns:

int: The number of bytes read from serialized. For non-group messages, this will always be len(serialized), but for messages which are actually groups, this will generally be less than len(serialized), since we must stop when we reach an END_GROUP tag. Note that if we do stop because of an END_GROUP tag, the number of bytes returned does not include the bytes for the END_GROUP tag information.

Raises:
  • DecodeError: if the input cannot be parsed.
def SerializeToString(self, **kwargs):
1133  def SerializeToString(self, **kwargs):
1134    # Check if the message has all of its required fields set.
1135    if not self.IsInitialized():
1136      raise message_mod.EncodeError(
1137          'Message %s is missing required fields: %s' % (
1138          self.DESCRIPTOR.full_name, ','.join(self.FindInitializationErrors())))
1139    return self.SerializePartialToString(**kwargs)

Serializes the protocol message to a binary string.

Keyword Args:

deterministic (bool): If true, requests deterministic serialization of the protobuf, with predictable ordering of map keys.

Returns:

A binary string representation of the message if all of the required fields in the message are set (i.e. the message is initialized).

Raises:
def SerializePartialToString(self, **kwargs):
1146  def SerializePartialToString(self, **kwargs):
1147    out = BytesIO()
1148    self._InternalSerialize(out.write, **kwargs)
1149    return out.getvalue()

Serializes the protocol message to a binary string.

This method is similar to SerializeToString but doesn't check if the message is initialized.

Keyword Args:

deterministic (bool): If true, requests deterministic serialization of the protobuf, with predictable ordering of map keys.

Returns:

bytes: A serialized representation of the partial message.

def ListFields(self):
848  def ListFields(self):
849    all_fields = [item for item in self._fields.items() if _IsPresent(item)]
850    all_fields.sort(key = lambda item: item[0].number)
851    return all_fields

Returns a list of (FieldDescriptor, value) tuples for present fields.

A message field is non-empty if HasField() would return true. A singular primitive field is non-empty if HasField() would return true in proto2 or it is non zero in proto3. A repeated field is non-empty if it contains at least one element. The fields are ordered by field number.

Returns:

list[tuple(FieldDescriptor, value)]: field descriptors and values for all fields in the message which are not empty. The values vary by field type.

def HasField(self, field_name):
872  def HasField(self, field_name):
873    try:
874      field = hassable_fields[field_name]
875    except KeyError as exc:
876      raise ValueError('Protocol message %s has no non-repeated field "%s" '
877                       'nor has presence is not available for this field.' % (
878                           message_descriptor.full_name, field_name)) from exc
879
880    if isinstance(field, descriptor_mod.OneofDescriptor):
881      try:
882        return HasField(self, self._oneofs[field].name)
883      except KeyError:
884        return False
885    else:
886      if field.cpp_type == _FieldDescriptor.CPPTYPE_MESSAGE:
887        value = self._fields.get(field)
888        return value is not None and value._is_present_in_parent
889      else:
890        return field in self._fields

Checks if a certain field is set for the message.

For a oneof group, checks if any field inside is set. Note that if the field_name is not defined in the message descriptor, ValueError will be raised.

Arguments:
  • field_name (str): The name of the field to check for presence.
Returns:

bool: Whether a value has been set for the named field.

Raises:
  • ValueError: if the field_name is not a member of this message.
def ClearField(self, field_name):
897  def ClearField(self, field_name):
898    try:
899      field = message_descriptor.fields_by_name[field_name]
900    except KeyError:
901      try:
902        field = message_descriptor.oneofs_by_name[field_name]
903        if field in self._oneofs:
904          field = self._oneofs[field]
905        else:
906          return
907      except KeyError:
908        raise ValueError('Protocol message %s has no "%s" field.' %
909                         (message_descriptor.name, field_name))
910
911    if field in self._fields:
912      # To match the C++ implementation, we need to invalidate iterators
913      # for map fields when ClearField() happens.
914      if hasattr(self._fields[field], 'InvalidateIterators'):
915        self._fields[field].InvalidateIterators()
916
917      # Note:  If the field is a sub-message, its listener will still point
918      #   at us.  That's fine, because the worst than can happen is that it
919      #   will call _Modified() and invalidate our byte size.  Big deal.
920      del self._fields[field]
921
922      if self._oneofs.get(field.containing_oneof, None) is field:
923        del self._oneofs[field.containing_oneof]
924
925    # Always call _Modified() -- even if nothing was changed, this is
926    # a mutating method, and thus calling it should cause the field to become
927    # present in the parent message.
928    self._Modified()

Clears the contents of a given field.

Inside a oneof group, clears the field set. If the name neither refers to a defined field or oneof group, ValueError is raised.

Arguments:
  • field_name (str): The name of the field to check for presence.
Raises:
  • ValueError: if the field_name is not a member of this message.
def WhichOneof(self, oneof_name):
1406  def WhichOneof(self, oneof_name):
1407    """Returns the name of the currently set field inside a oneof, or None."""
1408    try:
1409      field = message_descriptor.oneofs_by_name[oneof_name]
1410    except KeyError:
1411      raise ValueError(
1412          'Protocol message has no oneof "%s" field.' % oneof_name)
1413
1414    nested_field = self._oneofs.get(field, None)
1415    if nested_field is not None and self.HasField(nested_field.name):
1416      return nested_field.name
1417    else:
1418      return None

Returns the name of the currently set field inside a oneof, or None.

def DiscardUnknownFields(self):
1438def _DiscardUnknownFields(self):
1439  self._unknown_fields = []
1440  for field, value in self.ListFields():
1441    if field.cpp_type == _FieldDescriptor.CPPTYPE_MESSAGE:
1442      if _IsMapField(field):
1443        if _IsMessageMapField(field):
1444          for key in value:
1445            value[key].DiscardUnknownFields()
1446      elif field.label == _FieldDescriptor.LABEL_REPEATED:
1447        for sub_message in value:
1448          sub_message.DiscardUnknownFields()
1449      else:
1450        value.DiscardUnknownFields()

Clears all fields in the UnknownFieldSet.

This operation is recursive for nested message.

def ByteSize(self):
1101  def ByteSize(self):
1102    if not self._cached_byte_size_dirty:
1103      return self._cached_byte_size
1104
1105    size = 0
1106    descriptor = self.DESCRIPTOR
1107    if descriptor._is_map_entry:
1108      # Fields of map entry should always be serialized.
1109      key_field = descriptor.fields_by_name['key']
1110      _MaybeAddEncoder(cls, key_field)
1111      size = key_field._sizer(self.key)
1112      value_field = descriptor.fields_by_name['value']
1113      _MaybeAddEncoder(cls, value_field)
1114      size += value_field._sizer(self.value)
1115    else:
1116      for field_descriptor, field_value in self.ListFields():
1117        _MaybeAddEncoder(cls, field_descriptor)
1118        size += field_descriptor._sizer(field_value)
1119      for tag_bytes, value_bytes in self._unknown_fields:
1120        size += len(tag_bytes) + len(value_bytes)
1121
1122    self._cached_byte_size = size
1123    self._cached_byte_size_dirty = False
1124    self._listener_for_children.dirty = False
1125    return size

Returns the serialized size of this message.

Recursively calls ByteSize() on all contained messages.

Returns:

int: The number of bytes required to serialize this message.

def FromString(s):
826  def FromString(s):
827    message = cls()
828    message.MergeFromString(s)
829    return message
NAME_FIELD_NUMBER = 1
name
711  def getter(self):
712    # TODO: This may be broken since there may not be
713    # default_value.  Combine with has_default_value somehow.
714    return self._fields.get(field, default_value)

Getter for name.

ENFORCEMENT_LITERAL_FIELD_NUMBER = 2
enforcement_literal
668  def getter(self):
669    field_value = self._fields.get(field)
670    if field_value is None:
671      # Construct a new object to represent this field.
672      field_value = field._default_constructor(self)
673
674      # Atomically check if another thread has preempted us and, if not, swap
675      # in the new object we just created.  If someone has preempted us, we
676      # take that object and discard ours.
677      # WARNING:  We are relying on setdefault() being atomic.  This is true
678      #   in CPython but we haven't investigated others.  This warning appears
679      #   in several other locations in this file.
680      field_value = self._fields.setdefault(field, field_value)
681    return field_value

Getter for enforcement_literal.

BOOL_OR_FIELD_NUMBER = 3
bool_or
767  def getter(self):
768    field_value = self._fields.get(field)
769    if field_value is None:
770      # Construct a new object to represent this field.
771      field_value = field._default_constructor(self)
772
773      # Atomically check if another thread has preempted us and, if not, swap
774      # in the new object we just created.  If someone has preempted us, we
775      # take that object and discard ours.
776      # WARNING:  We are relying on setdefault() being atomic.  This is true
777      #   in CPython but we haven't investigated others.  This warning appears
778      #   in several other locations in this file.
779      field_value = self._fields.setdefault(field, field_value)
780    return field_value

Getter for bool_or.

BOOL_AND_FIELD_NUMBER = 4
bool_and
767  def getter(self):
768    field_value = self._fields.get(field)
769    if field_value is None:
770      # Construct a new object to represent this field.
771      field_value = field._default_constructor(self)
772
773      # Atomically check if another thread has preempted us and, if not, swap
774      # in the new object we just created.  If someone has preempted us, we
775      # take that object and discard ours.
776      # WARNING:  We are relying on setdefault() being atomic.  This is true
777      #   in CPython but we haven't investigated others.  This warning appears
778      #   in several other locations in this file.
779      field_value = self._fields.setdefault(field, field_value)
780    return field_value

Getter for bool_and.

AT_MOST_ONE_FIELD_NUMBER = 26
at_most_one
767  def getter(self):
768    field_value = self._fields.get(field)
769    if field_value is None:
770      # Construct a new object to represent this field.
771      field_value = field._default_constructor(self)
772
773      # Atomically check if another thread has preempted us and, if not, swap
774      # in the new object we just created.  If someone has preempted us, we
775      # take that object and discard ours.
776      # WARNING:  We are relying on setdefault() being atomic.  This is true
777      #   in CPython but we haven't investigated others.  This warning appears
778      #   in several other locations in this file.
779      field_value = self._fields.setdefault(field, field_value)
780    return field_value

Getter for at_most_one.

EXACTLY_ONE_FIELD_NUMBER = 29
exactly_one
767  def getter(self):
768    field_value = self._fields.get(field)
769    if field_value is None:
770      # Construct a new object to represent this field.
771      field_value = field._default_constructor(self)
772
773      # Atomically check if another thread has preempted us and, if not, swap
774      # in the new object we just created.  If someone has preempted us, we
775      # take that object and discard ours.
776      # WARNING:  We are relying on setdefault() being atomic.  This is true
777      #   in CPython but we haven't investigated others.  This warning appears
778      #   in several other locations in this file.
779      field_value = self._fields.setdefault(field, field_value)
780    return field_value

Getter for exactly_one.

BOOL_XOR_FIELD_NUMBER = 5
bool_xor
767  def getter(self):
768    field_value = self._fields.get(field)
769    if field_value is None:
770      # Construct a new object to represent this field.
771      field_value = field._default_constructor(self)
772
773      # Atomically check if another thread has preempted us and, if not, swap
774      # in the new object we just created.  If someone has preempted us, we
775      # take that object and discard ours.
776      # WARNING:  We are relying on setdefault() being atomic.  This is true
777      #   in CPython but we haven't investigated others.  This warning appears
778      #   in several other locations in this file.
779      field_value = self._fields.setdefault(field, field_value)
780    return field_value

Getter for bool_xor.

INT_DIV_FIELD_NUMBER = 7
int_div
767  def getter(self):
768    field_value = self._fields.get(field)
769    if field_value is None:
770      # Construct a new object to represent this field.
771      field_value = field._default_constructor(self)
772
773      # Atomically check if another thread has preempted us and, if not, swap
774      # in the new object we just created.  If someone has preempted us, we
775      # take that object and discard ours.
776      # WARNING:  We are relying on setdefault() being atomic.  This is true
777      #   in CPython but we haven't investigated others.  This warning appears
778      #   in several other locations in this file.
779      field_value = self._fields.setdefault(field, field_value)
780    return field_value

Getter for int_div.

INT_MOD_FIELD_NUMBER = 8
int_mod
767  def getter(self):
768    field_value = self._fields.get(field)
769    if field_value is None:
770      # Construct a new object to represent this field.
771      field_value = field._default_constructor(self)
772
773      # Atomically check if another thread has preempted us and, if not, swap
774      # in the new object we just created.  If someone has preempted us, we
775      # take that object and discard ours.
776      # WARNING:  We are relying on setdefault() being atomic.  This is true
777      #   in CPython but we haven't investigated others.  This warning appears
778      #   in several other locations in this file.
779      field_value = self._fields.setdefault(field, field_value)
780    return field_value

Getter for int_mod.

INT_PROD_FIELD_NUMBER = 11
int_prod
767  def getter(self):
768    field_value = self._fields.get(field)
769    if field_value is None:
770      # Construct a new object to represent this field.
771      field_value = field._default_constructor(self)
772
773      # Atomically check if another thread has preempted us and, if not, swap
774      # in the new object we just created.  If someone has preempted us, we
775      # take that object and discard ours.
776      # WARNING:  We are relying on setdefault() being atomic.  This is true
777      #   in CPython but we haven't investigated others.  This warning appears
778      #   in several other locations in this file.
779      field_value = self._fields.setdefault(field, field_value)
780    return field_value

Getter for int_prod.

LIN_MAX_FIELD_NUMBER = 27
lin_max
767  def getter(self):
768    field_value = self._fields.get(field)
769    if field_value is None:
770      # Construct a new object to represent this field.
771      field_value = field._default_constructor(self)
772
773      # Atomically check if another thread has preempted us and, if not, swap
774      # in the new object we just created.  If someone has preempted us, we
775      # take that object and discard ours.
776      # WARNING:  We are relying on setdefault() being atomic.  This is true
777      #   in CPython but we haven't investigated others.  This warning appears
778      #   in several other locations in this file.
779      field_value = self._fields.setdefault(field, field_value)
780    return field_value

Getter for lin_max.

LINEAR_FIELD_NUMBER = 12
linear
767  def getter(self):
768    field_value = self._fields.get(field)
769    if field_value is None:
770      # Construct a new object to represent this field.
771      field_value = field._default_constructor(self)
772
773      # Atomically check if another thread has preempted us and, if not, swap
774      # in the new object we just created.  If someone has preempted us, we
775      # take that object and discard ours.
776      # WARNING:  We are relying on setdefault() being atomic.  This is true
777      #   in CPython but we haven't investigated others.  This warning appears
778      #   in several other locations in this file.
779      field_value = self._fields.setdefault(field, field_value)
780    return field_value

Getter for linear.

ALL_DIFF_FIELD_NUMBER = 13
all_diff
767  def getter(self):
768    field_value = self._fields.get(field)
769    if field_value is None:
770      # Construct a new object to represent this field.
771      field_value = field._default_constructor(self)
772
773      # Atomically check if another thread has preempted us and, if not, swap
774      # in the new object we just created.  If someone has preempted us, we
775      # take that object and discard ours.
776      # WARNING:  We are relying on setdefault() being atomic.  This is true
777      #   in CPython but we haven't investigated others.  This warning appears
778      #   in several other locations in this file.
779      field_value = self._fields.setdefault(field, field_value)
780    return field_value

Getter for all_diff.

ELEMENT_FIELD_NUMBER = 14
element
767  def getter(self):
768    field_value = self._fields.get(field)
769    if field_value is None:
770      # Construct a new object to represent this field.
771      field_value = field._default_constructor(self)
772
773      # Atomically check if another thread has preempted us and, if not, swap
774      # in the new object we just created.  If someone has preempted us, we
775      # take that object and discard ours.
776      # WARNING:  We are relying on setdefault() being atomic.  This is true
777      #   in CPython but we haven't investigated others.  This warning appears
778      #   in several other locations in this file.
779      field_value = self._fields.setdefault(field, field_value)
780    return field_value

Getter for element.

CIRCUIT_FIELD_NUMBER = 15
circuit
767  def getter(self):
768    field_value = self._fields.get(field)
769    if field_value is None:
770      # Construct a new object to represent this field.
771      field_value = field._default_constructor(self)
772
773      # Atomically check if another thread has preempted us and, if not, swap
774      # in the new object we just created.  If someone has preempted us, we
775      # take that object and discard ours.
776      # WARNING:  We are relying on setdefault() being atomic.  This is true
777      #   in CPython but we haven't investigated others.  This warning appears
778      #   in several other locations in this file.
779      field_value = self._fields.setdefault(field, field_value)
780    return field_value

Getter for circuit.

ROUTES_FIELD_NUMBER = 23
routes
767  def getter(self):
768    field_value = self._fields.get(field)
769    if field_value is None:
770      # Construct a new object to represent this field.
771      field_value = field._default_constructor(self)
772
773      # Atomically check if another thread has preempted us and, if not, swap
774      # in the new object we just created.  If someone has preempted us, we
775      # take that object and discard ours.
776      # WARNING:  We are relying on setdefault() being atomic.  This is true
777      #   in CPython but we haven't investigated others.  This warning appears
778      #   in several other locations in this file.
779      field_value = self._fields.setdefault(field, field_value)
780    return field_value

Getter for routes.

TABLE_FIELD_NUMBER = 16
table
767  def getter(self):
768    field_value = self._fields.get(field)
769    if field_value is None:
770      # Construct a new object to represent this field.
771      field_value = field._default_constructor(self)
772
773      # Atomically check if another thread has preempted us and, if not, swap
774      # in the new object we just created.  If someone has preempted us, we
775      # take that object and discard ours.
776      # WARNING:  We are relying on setdefault() being atomic.  This is true
777      #   in CPython but we haven't investigated others.  This warning appears
778      #   in several other locations in this file.
779      field_value = self._fields.setdefault(field, field_value)
780    return field_value

Getter for table.

AUTOMATON_FIELD_NUMBER = 17
automaton
767  def getter(self):
768    field_value = self._fields.get(field)
769    if field_value is None:
770      # Construct a new object to represent this field.
771      field_value = field._default_constructor(self)
772
773      # Atomically check if another thread has preempted us and, if not, swap
774      # in the new object we just created.  If someone has preempted us, we
775      # take that object and discard ours.
776      # WARNING:  We are relying on setdefault() being atomic.  This is true
777      #   in CPython but we haven't investigated others.  This warning appears
778      #   in several other locations in this file.
779      field_value = self._fields.setdefault(field, field_value)
780    return field_value

Getter for automaton.

INVERSE_FIELD_NUMBER = 18
inverse
767  def getter(self):
768    field_value = self._fields.get(field)
769    if field_value is None:
770      # Construct a new object to represent this field.
771      field_value = field._default_constructor(self)
772
773      # Atomically check if another thread has preempted us and, if not, swap
774      # in the new object we just created.  If someone has preempted us, we
775      # take that object and discard ours.
776      # WARNING:  We are relying on setdefault() being atomic.  This is true
777      #   in CPython but we haven't investigated others.  This warning appears
778      #   in several other locations in this file.
779      field_value = self._fields.setdefault(field, field_value)
780    return field_value

Getter for inverse.

RESERVOIR_FIELD_NUMBER = 24
reservoir
767  def getter(self):
768    field_value = self._fields.get(field)
769    if field_value is None:
770      # Construct a new object to represent this field.
771      field_value = field._default_constructor(self)
772
773      # Atomically check if another thread has preempted us and, if not, swap
774      # in the new object we just created.  If someone has preempted us, we
775      # take that object and discard ours.
776      # WARNING:  We are relying on setdefault() being atomic.  This is true
777      #   in CPython but we haven't investigated others.  This warning appears
778      #   in several other locations in this file.
779      field_value = self._fields.setdefault(field, field_value)
780    return field_value

Getter for reservoir.

INTERVAL_FIELD_NUMBER = 19
interval
767  def getter(self):
768    field_value = self._fields.get(field)
769    if field_value is None:
770      # Construct a new object to represent this field.
771      field_value = field._default_constructor(self)
772
773      # Atomically check if another thread has preempted us and, if not, swap
774      # in the new object we just created.  If someone has preempted us, we
775      # take that object and discard ours.
776      # WARNING:  We are relying on setdefault() being atomic.  This is true
777      #   in CPython but we haven't investigated others.  This warning appears
778      #   in several other locations in this file.
779      field_value = self._fields.setdefault(field, field_value)
780    return field_value

Getter for interval.

NO_OVERLAP_FIELD_NUMBER = 20
no_overlap
767  def getter(self):
768    field_value = self._fields.get(field)
769    if field_value is None:
770      # Construct a new object to represent this field.
771      field_value = field._default_constructor(self)
772
773      # Atomically check if another thread has preempted us and, if not, swap
774      # in the new object we just created.  If someone has preempted us, we
775      # take that object and discard ours.
776      # WARNING:  We are relying on setdefault() being atomic.  This is true
777      #   in CPython but we haven't investigated others.  This warning appears
778      #   in several other locations in this file.
779      field_value = self._fields.setdefault(field, field_value)
780    return field_value

Getter for no_overlap.

NO_OVERLAP_2D_FIELD_NUMBER = 21
no_overlap_2d
767  def getter(self):
768    field_value = self._fields.get(field)
769    if field_value is None:
770      # Construct a new object to represent this field.
771      field_value = field._default_constructor(self)
772
773      # Atomically check if another thread has preempted us and, if not, swap
774      # in the new object we just created.  If someone has preempted us, we
775      # take that object and discard ours.
776      # WARNING:  We are relying on setdefault() being atomic.  This is true
777      #   in CPython but we haven't investigated others.  This warning appears
778      #   in several other locations in this file.
779      field_value = self._fields.setdefault(field, field_value)
780    return field_value

Getter for no_overlap_2d.

CUMULATIVE_FIELD_NUMBER = 22
cumulative
767  def getter(self):
768    field_value = self._fields.get(field)
769    if field_value is None:
770      # Construct a new object to represent this field.
771      field_value = field._default_constructor(self)
772
773      # Atomically check if another thread has preempted us and, if not, swap
774      # in the new object we just created.  If someone has preempted us, we
775      # take that object and discard ours.
776      # WARNING:  We are relying on setdefault() being atomic.  This is true
777      #   in CPython but we haven't investigated others.  This warning appears
778      #   in several other locations in this file.
779      field_value = self._fields.setdefault(field, field_value)
780    return field_value

Getter for cumulative.

DUMMY_CONSTRAINT_FIELD_NUMBER = 30
dummy_constraint
767  def getter(self):
768    field_value = self._fields.get(field)
769    if field_value is None:
770      # Construct a new object to represent this field.
771      field_value = field._default_constructor(self)
772
773      # Atomically check if another thread has preempted us and, if not, swap
774      # in the new object we just created.  If someone has preempted us, we
775      # take that object and discard ours.
776      # WARNING:  We are relying on setdefault() being atomic.  This is true
777      #   in CPython but we haven't investigated others.  This warning appears
778      #   in several other locations in this file.
779      field_value = self._fields.setdefault(field, field_value)
780    return field_value

Getter for dummy_constraint.

def FindInitializationErrors(self):
1305  def FindInitializationErrors(self):
1306    """Finds required fields which are not initialized.
1307
1308    Returns:
1309      A list of strings.  Each string is a path to an uninitialized field from
1310      the top-level message, e.g. "foo.bar[5].baz".
1311    """
1312
1313    errors = []  # simplify things
1314
1315    for field in required_fields:
1316      if not self.HasField(field.name):
1317        errors.append(field.name)
1318
1319    for field, value in self.ListFields():
1320      if field.cpp_type == _FieldDescriptor.CPPTYPE_MESSAGE:
1321        if field.is_extension:
1322          name = '(%s)' % field.full_name
1323        else:
1324          name = field.name
1325
1326        if _IsMapField(field):
1327          if _IsMessageMapField(field):
1328            for key in value:
1329              element = value[key]
1330              prefix = '%s[%s].' % (name, key)
1331              sub_errors = element.FindInitializationErrors()
1332              errors += [prefix + error for error in sub_errors]
1333          else:
1334            # ScalarMaps can't have any initialization errors.
1335            pass
1336        elif field.label == _FieldDescriptor.LABEL_REPEATED:
1337          for i in range(len(value)):
1338            element = value[i]
1339            prefix = '%s[%d].' % (name, i)
1340            sub_errors = element.FindInitializationErrors()
1341            errors += [prefix + error for error in sub_errors]
1342        else:
1343          prefix = name + '.'
1344          sub_errors = value.FindInitializationErrors()
1345          errors += [prefix + error for error in sub_errors]
1346
1347    return errors

Finds required fields which are not initialized.

Returns:

A list of strings. Each string is a path to an uninitialized field from the top-level message, e.g. "foo.bar[5].baz".

class CpObjectiveProto(google.protobuf.message.Message):

Abstract base class for protocol messages.

Protocol message classes are almost always generated by the protocol compiler. These generated types subclass Message and implement the methods shown below.

CpObjectiveProto(**kwargs)
498  def init(self, **kwargs):
499    self._cached_byte_size = 0
500    self._cached_byte_size_dirty = len(kwargs) > 0
501    self._fields = {}
502    # Contains a mapping from oneof field descriptors to the descriptor
503    # of the currently set field in that oneof field.
504    self._oneofs = {}
505
506    # _unknown_fields is () when empty for efficiency, and will be turned into
507    # a list if fields are added.
508    self._unknown_fields = ()
509    self._is_present_in_parent = False
510    self._listener = message_listener_mod.NullMessageListener()
511    self._listener_for_children = _Listener(self)
512    for field_name, field_value in kwargs.items():
513      field = _GetFieldByName(message_descriptor, field_name)
514      if field is None:
515        raise TypeError('%s() got an unexpected keyword argument "%s"' %
516                        (message_descriptor.name, field_name))
517      if field_value is None:
518        # field=None is the same as no field at all.
519        continue
520      if field.label == _FieldDescriptor.LABEL_REPEATED:
521        field_copy = field._default_constructor(self)
522        if field.cpp_type == _FieldDescriptor.CPPTYPE_MESSAGE:  # Composite
523          if _IsMapField(field):
524            if _IsMessageMapField(field):
525              for key in field_value:
526                field_copy[key].MergeFrom(field_value[key])
527            else:
528              field_copy.update(field_value)
529          else:
530            for val in field_value:
531              if isinstance(val, dict):
532                field_copy.add(**val)
533              else:
534                field_copy.add().MergeFrom(val)
535        else:  # Scalar
536          if field.cpp_type == _FieldDescriptor.CPPTYPE_ENUM:
537            field_value = [_GetIntegerEnumValue(field.enum_type, val)
538                           for val in field_value]
539          field_copy.extend(field_value)
540        self._fields[field] = field_copy
541      elif field.cpp_type == _FieldDescriptor.CPPTYPE_MESSAGE:
542        field_copy = field._default_constructor(self)
543        new_val = None
544        if isinstance(field_value, message_mod.Message):
545          new_val = field_value
546        elif isinstance(field_value, dict):
547          if field.message_type.full_name == _StructFullTypeName:
548            field_copy.Clear()
549            if len(field_value) == 1 and 'fields' in field_value:
550              try:
551                field_copy.update(field_value)
552              except:
553                # Fall back to init normal message field
554                field_copy.Clear()
555                new_val = field.message_type._concrete_class(**field_value)
556            else:
557              field_copy.update(field_value)
558          else:
559            new_val = field.message_type._concrete_class(**field_value)
560        elif hasattr(field_copy, '_internal_assign'):
561          field_copy._internal_assign(field_value)
562        else:
563          raise TypeError(
564              'Message field {0}.{1} must be initialized with a '
565              'dict or instance of same class, got {2}.'.format(
566                  message_descriptor.name,
567                  field_name,
568                  type(field_value).__name__,
569              )
570          )
571
572        if new_val != None:
573          try:
574            field_copy.MergeFrom(new_val)
575          except TypeError:
576            _ReraiseTypeErrorWithFieldName(message_descriptor.name, field_name)
577        self._fields[field] = field_copy
578      else:
579        if field.cpp_type == _FieldDescriptor.CPPTYPE_ENUM:
580          field_value = _GetIntegerEnumValue(field.enum_type, field_value)
581        try:
582          setattr(self, field_name, field_value)
583        except TypeError:
584          _ReraiseTypeErrorWithFieldName(message_descriptor.name, field_name)
DESCRIPTOR = <google.protobuf.descriptor.Descriptor object>
def MergeFrom(self, msg):
1364  def MergeFrom(self, msg):
1365    if not isinstance(msg, cls):
1366      raise TypeError(
1367          'Parameter to MergeFrom() must be instance of same class: '
1368          'expected %s got %s.' % (_FullyQualifiedClassName(cls),
1369                                   _FullyQualifiedClassName(msg.__class__)))
1370
1371    assert msg is not self
1372    self._Modified()
1373
1374    fields = self._fields
1375
1376    for field, value in msg._fields.items():
1377      if field.label == LABEL_REPEATED:
1378        field_value = fields.get(field)
1379        if field_value is None:
1380          # Construct a new object to represent this field.
1381          field_value = field._default_constructor(self)
1382          fields[field] = field_value
1383        field_value.MergeFrom(value)
1384      elif field.cpp_type == CPPTYPE_MESSAGE:
1385        if value._is_present_in_parent:
1386          field_value = fields.get(field)
1387          if field_value is None:
1388            # Construct a new object to represent this field.
1389            field_value = field._default_constructor(self)
1390            fields[field] = field_value
1391          field_value.MergeFrom(value)
1392      else:
1393        self._fields[field] = value
1394        if field.containing_oneof:
1395          self._UpdateOneofState(field)
1396
1397    if msg._unknown_fields:
1398      if not self._unknown_fields:
1399        self._unknown_fields = []
1400      self._unknown_fields.extend(msg._unknown_fields)

Merges the contents of the specified message into current message.

This method merges the contents of the specified message into the current message. Singular fields that are set in the specified message overwrite the corresponding fields in the current message. Repeated fields are appended. Singular sub-messages and groups are recursively merged.

Arguments:
  • other_msg (Message): A message to merge into the current message.
def Clear(self):
1423def _Clear(self):
1424  # Clear fields.
1425  self._fields = {}
1426  self._unknown_fields = ()
1427
1428  self._oneofs = {}
1429  self._Modified()

Clears all data that was set in the message.

def SetInParent(self):
1489  def Modified(self):
1490    """Sets the _cached_byte_size_dirty bit to true,
1491    and propagates this to our listener iff this was a state change.
1492    """
1493
1494    # Note:  Some callers check _cached_byte_size_dirty before calling
1495    #   _Modified() as an extra optimization.  So, if this method is ever
1496    #   changed such that it does stuff even when _cached_byte_size_dirty is
1497    #   already true, the callers need to be updated.
1498    if not self._cached_byte_size_dirty:
1499      self._cached_byte_size_dirty = True
1500      self._listener_for_children.dirty = True
1501      self._is_present_in_parent = True
1502      self._listener.Modified()

Sets the _cached_byte_size_dirty bit to true, and propagates this to our listener iff this was a state change.

def IsInitialized(self, errors=None):
1265  def IsInitialized(self, errors=None):
1266    """Checks if all required fields of a message are set.
1267
1268    Args:
1269      errors:  A list which, if provided, will be populated with the field
1270               paths of all missing required fields.
1271
1272    Returns:
1273      True iff the specified message has all required fields set.
1274    """
1275
1276    # Performance is critical so we avoid HasField() and ListFields().
1277
1278    for field in required_fields:
1279      if (field not in self._fields or
1280          (field.cpp_type == _FieldDescriptor.CPPTYPE_MESSAGE and
1281           not self._fields[field]._is_present_in_parent)):
1282        if errors is not None:
1283          errors.extend(self.FindInitializationErrors())
1284        return False
1285
1286    for field, value in list(self._fields.items()):  # dict can change size!
1287      if field.cpp_type == _FieldDescriptor.CPPTYPE_MESSAGE:
1288        if field.label == _FieldDescriptor.LABEL_REPEATED:
1289          if (field.message_type._is_map_entry):
1290            continue
1291          for element in value:
1292            if not element.IsInitialized():
1293              if errors is not None:
1294                errors.extend(self.FindInitializationErrors())
1295              return False
1296        elif value._is_present_in_parent and not value.IsInitialized():
1297          if errors is not None:
1298            errors.extend(self.FindInitializationErrors())
1299          return False
1300
1301    return True

Checks if all required fields of a message are set.

Arguments:
  • errors: A list which, if provided, will be populated with the field paths of all missing required fields.
Returns:

True iff the specified message has all required fields set.

def MergeFromString(self, serialized):
1180  def MergeFromString(self, serialized):
1181    serialized = memoryview(serialized)
1182    length = len(serialized)
1183    try:
1184      if self._InternalParse(serialized, 0, length) != length:
1185        # The only reason _InternalParse would return early is if it
1186        # encountered an end-group tag.
1187        raise message_mod.DecodeError('Unexpected end-group tag.')
1188    except (IndexError, TypeError):
1189      # Now ord(buf[p:p+1]) == ord('') gets TypeError.
1190      raise message_mod.DecodeError('Truncated message.')
1191    except struct.error as e:
1192      raise message_mod.DecodeError(e)
1193    return length   # Return this for legacy reasons.

Merges serialized protocol buffer data into this message.

When we find a field in serialized that is already present in this message:

  • If it's a "repeated" field, we append to the end of our list.
  • Else, if it's a scalar, we overwrite our field.
  • Else, (it's a nonrepeated composite), we recursively merge into the existing composite.
Arguments:
  • serialized (bytes): Any object that allows us to call memoryview(serialized) to access a string of bytes using the buffer interface.
Returns:

int: The number of bytes read from serialized. For non-group messages, this will always be len(serialized), but for messages which are actually groups, this will generally be less than len(serialized), since we must stop when we reach an END_GROUP tag. Note that if we do stop because of an END_GROUP tag, the number of bytes returned does not include the bytes for the END_GROUP tag information.

Raises:
  • DecodeError: if the input cannot be parsed.
def SerializeToString(self, **kwargs):
1133  def SerializeToString(self, **kwargs):
1134    # Check if the message has all of its required fields set.
1135    if not self.IsInitialized():
1136      raise message_mod.EncodeError(
1137          'Message %s is missing required fields: %s' % (
1138          self.DESCRIPTOR.full_name, ','.join(self.FindInitializationErrors())))
1139    return self.SerializePartialToString(**kwargs)

Serializes the protocol message to a binary string.

Keyword Args:

deterministic (bool): If true, requests deterministic serialization of the protobuf, with predictable ordering of map keys.

Returns:

A binary string representation of the message if all of the required fields in the message are set (i.e. the message is initialized).

Raises:
def SerializePartialToString(self, **kwargs):
1146  def SerializePartialToString(self, **kwargs):
1147    out = BytesIO()
1148    self._InternalSerialize(out.write, **kwargs)
1149    return out.getvalue()

Serializes the protocol message to a binary string.

This method is similar to SerializeToString but doesn't check if the message is initialized.

Keyword Args:

deterministic (bool): If true, requests deterministic serialization of the protobuf, with predictable ordering of map keys.

Returns:

bytes: A serialized representation of the partial message.

def ListFields(self):
848  def ListFields(self):
849    all_fields = [item for item in self._fields.items() if _IsPresent(item)]
850    all_fields.sort(key = lambda item: item[0].number)
851    return all_fields

Returns a list of (FieldDescriptor, value) tuples for present fields.

A message field is non-empty if HasField() would return true. A singular primitive field is non-empty if HasField() would return true in proto2 or it is non zero in proto3. A repeated field is non-empty if it contains at least one element. The fields are ordered by field number.

Returns:

list[tuple(FieldDescriptor, value)]: field descriptors and values for all fields in the message which are not empty. The values vary by field type.

def HasField(self, field_name):
872  def HasField(self, field_name):
873    try:
874      field = hassable_fields[field_name]
875    except KeyError as exc:
876      raise ValueError('Protocol message %s has no non-repeated field "%s" '
877                       'nor has presence is not available for this field.' % (
878                           message_descriptor.full_name, field_name)) from exc
879
880    if isinstance(field, descriptor_mod.OneofDescriptor):
881      try:
882        return HasField(self, self._oneofs[field].name)
883      except KeyError:
884        return False
885    else:
886      if field.cpp_type == _FieldDescriptor.CPPTYPE_MESSAGE:
887        value = self._fields.get(field)
888        return value is not None and value._is_present_in_parent
889      else:
890        return field in self._fields

Checks if a certain field is set for the message.

For a oneof group, checks if any field inside is set. Note that if the field_name is not defined in the message descriptor, ValueError will be raised.

Arguments:
  • field_name (str): The name of the field to check for presence.
Returns:

bool: Whether a value has been set for the named field.

Raises:
  • ValueError: if the field_name is not a member of this message.
def ClearField(self, field_name):
897  def ClearField(self, field_name):
898    try:
899      field = message_descriptor.fields_by_name[field_name]
900    except KeyError:
901      try:
902        field = message_descriptor.oneofs_by_name[field_name]
903        if field in self._oneofs:
904          field = self._oneofs[field]
905        else:
906          return
907      except KeyError:
908        raise ValueError('Protocol message %s has no "%s" field.' %
909                         (message_descriptor.name, field_name))
910
911    if field in self._fields:
912      # To match the C++ implementation, we need to invalidate iterators
913      # for map fields when ClearField() happens.
914      if hasattr(self._fields[field], 'InvalidateIterators'):
915        self._fields[field].InvalidateIterators()
916
917      # Note:  If the field is a sub-message, its listener will still point
918      #   at us.  That's fine, because the worst than can happen is that it
919      #   will call _Modified() and invalidate our byte size.  Big deal.
920      del self._fields[field]
921
922      if self._oneofs.get(field.containing_oneof, None) is field:
923        del self._oneofs[field.containing_oneof]
924
925    # Always call _Modified() -- even if nothing was changed, this is
926    # a mutating method, and thus calling it should cause the field to become
927    # present in the parent message.
928    self._Modified()

Clears the contents of a given field.

Inside a oneof group, clears the field set. If the name neither refers to a defined field or oneof group, ValueError is raised.

Arguments:
  • field_name (str): The name of the field to check for presence.
Raises:
  • ValueError: if the field_name is not a member of this message.
def WhichOneof(self, oneof_name):
1406  def WhichOneof(self, oneof_name):
1407    """Returns the name of the currently set field inside a oneof, or None."""
1408    try:
1409      field = message_descriptor.oneofs_by_name[oneof_name]
1410    except KeyError:
1411      raise ValueError(
1412          'Protocol message has no oneof "%s" field.' % oneof_name)
1413
1414    nested_field = self._oneofs.get(field, None)
1415    if nested_field is not None and self.HasField(nested_field.name):
1416      return nested_field.name
1417    else:
1418      return None

Returns the name of the currently set field inside a oneof, or None.

def DiscardUnknownFields(self):
1438def _DiscardUnknownFields(self):
1439  self._unknown_fields = []
1440  for field, value in self.ListFields():
1441    if field.cpp_type == _FieldDescriptor.CPPTYPE_MESSAGE:
1442      if _IsMapField(field):
1443        if _IsMessageMapField(field):
1444          for key in value:
1445            value[key].DiscardUnknownFields()
1446      elif field.label == _FieldDescriptor.LABEL_REPEATED:
1447        for sub_message in value:
1448          sub_message.DiscardUnknownFields()
1449      else:
1450        value.DiscardUnknownFields()

Clears all fields in the UnknownFieldSet.

This operation is recursive for nested message.

def ByteSize(self):
1101  def ByteSize(self):
1102    if not self._cached_byte_size_dirty:
1103      return self._cached_byte_size
1104
1105    size = 0
1106    descriptor = self.DESCRIPTOR
1107    if descriptor._is_map_entry:
1108      # Fields of map entry should always be serialized.
1109      key_field = descriptor.fields_by_name['key']
1110      _MaybeAddEncoder(cls, key_field)
1111      size = key_field._sizer(self.key)
1112      value_field = descriptor.fields_by_name['value']
1113      _MaybeAddEncoder(cls, value_field)
1114      size += value_field._sizer(self.value)
1115    else:
1116      for field_descriptor, field_value in self.ListFields():
1117        _MaybeAddEncoder(cls, field_descriptor)
1118        size += field_descriptor._sizer(field_value)
1119      for tag_bytes, value_bytes in self._unknown_fields:
1120        size += len(tag_bytes) + len(value_bytes)
1121
1122    self._cached_byte_size = size
1123    self._cached_byte_size_dirty = False
1124    self._listener_for_children.dirty = False
1125    return size

Returns the serialized size of this message.

Recursively calls ByteSize() on all contained messages.

Returns:

int: The number of bytes required to serialize this message.

def FromString(s):
826  def FromString(s):
827    message = cls()
828    message.MergeFromString(s)
829    return message
VARS_FIELD_NUMBER = 1
vars
668  def getter(self):
669    field_value = self._fields.get(field)
670    if field_value is None:
671      # Construct a new object to represent this field.
672      field_value = field._default_constructor(self)
673
674      # Atomically check if another thread has preempted us and, if not, swap
675      # in the new object we just created.  If someone has preempted us, we
676      # take that object and discard ours.
677      # WARNING:  We are relying on setdefault() being atomic.  This is true
678      #   in CPython but we haven't investigated others.  This warning appears
679      #   in several other locations in this file.
680      field_value = self._fields.setdefault(field, field_value)
681    return field_value

Getter for vars.

COEFFS_FIELD_NUMBER = 4
coeffs
668  def getter(self):
669    field_value = self._fields.get(field)
670    if field_value is None:
671      # Construct a new object to represent this field.
672      field_value = field._default_constructor(self)
673
674      # Atomically check if another thread has preempted us and, if not, swap
675      # in the new object we just created.  If someone has preempted us, we
676      # take that object and discard ours.
677      # WARNING:  We are relying on setdefault() being atomic.  This is true
678      #   in CPython but we haven't investigated others.  This warning appears
679      #   in several other locations in this file.
680      field_value = self._fields.setdefault(field, field_value)
681    return field_value

Getter for coeffs.

OFFSET_FIELD_NUMBER = 2
offset
711  def getter(self):
712    # TODO: This may be broken since there may not be
713    # default_value.  Combine with has_default_value somehow.
714    return self._fields.get(field, default_value)

Getter for offset.

SCALING_FACTOR_FIELD_NUMBER = 3
scaling_factor
711  def getter(self):
712    # TODO: This may be broken since there may not be
713    # default_value.  Combine with has_default_value somehow.
714    return self._fields.get(field, default_value)

Getter for scaling_factor.

DOMAIN_FIELD_NUMBER = 5
domain
668  def getter(self):
669    field_value = self._fields.get(field)
670    if field_value is None:
671      # Construct a new object to represent this field.
672      field_value = field._default_constructor(self)
673
674      # Atomically check if another thread has preempted us and, if not, swap
675      # in the new object we just created.  If someone has preempted us, we
676      # take that object and discard ours.
677      # WARNING:  We are relying on setdefault() being atomic.  This is true
678      #   in CPython but we haven't investigated others.  This warning appears
679      #   in several other locations in this file.
680      field_value = self._fields.setdefault(field, field_value)
681    return field_value

Getter for domain.

SCALING_WAS_EXACT_FIELD_NUMBER = 6
scaling_was_exact
711  def getter(self):
712    # TODO: This may be broken since there may not be
713    # default_value.  Combine with has_default_value somehow.
714    return self._fields.get(field, default_value)

Getter for scaling_was_exact.

INTEGER_BEFORE_OFFSET_FIELD_NUMBER = 7
integer_before_offset
711  def getter(self):
712    # TODO: This may be broken since there may not be
713    # default_value.  Combine with has_default_value somehow.
714    return self._fields.get(field, default_value)

Getter for integer_before_offset.

INTEGER_AFTER_OFFSET_FIELD_NUMBER = 9
integer_after_offset
711  def getter(self):
712    # TODO: This may be broken since there may not be
713    # default_value.  Combine with has_default_value somehow.
714    return self._fields.get(field, default_value)

Getter for integer_after_offset.

INTEGER_SCALING_FACTOR_FIELD_NUMBER = 8
integer_scaling_factor
711  def getter(self):
712    # TODO: This may be broken since there may not be
713    # default_value.  Combine with has_default_value somehow.
714    return self._fields.get(field, default_value)

Getter for integer_scaling_factor.

def FindInitializationErrors(self):
1305  def FindInitializationErrors(self):
1306    """Finds required fields which are not initialized.
1307
1308    Returns:
1309      A list of strings.  Each string is a path to an uninitialized field from
1310      the top-level message, e.g. "foo.bar[5].baz".
1311    """
1312
1313    errors = []  # simplify things
1314
1315    for field in required_fields:
1316      if not self.HasField(field.name):
1317        errors.append(field.name)
1318
1319    for field, value in self.ListFields():
1320      if field.cpp_type == _FieldDescriptor.CPPTYPE_MESSAGE:
1321        if field.is_extension:
1322          name = '(%s)' % field.full_name
1323        else:
1324          name = field.name
1325
1326        if _IsMapField(field):
1327          if _IsMessageMapField(field):
1328            for key in value:
1329              element = value[key]
1330              prefix = '%s[%s].' % (name, key)
1331              sub_errors = element.FindInitializationErrors()
1332              errors += [prefix + error for error in sub_errors]
1333          else:
1334            # ScalarMaps can't have any initialization errors.
1335            pass
1336        elif field.label == _FieldDescriptor.LABEL_REPEATED:
1337          for i in range(len(value)):
1338            element = value[i]
1339            prefix = '%s[%d].' % (name, i)
1340            sub_errors = element.FindInitializationErrors()
1341            errors += [prefix + error for error in sub_errors]
1342        else:
1343          prefix = name + '.'
1344          sub_errors = value.FindInitializationErrors()
1345          errors += [prefix + error for error in sub_errors]
1346
1347    return errors

Finds required fields which are not initialized.

Returns:

A list of strings. Each string is a path to an uninitialized field from the top-level message, e.g. "foo.bar[5].baz".

class FloatObjectiveProto(google.protobuf.message.Message):

Abstract base class for protocol messages.

Protocol message classes are almost always generated by the protocol compiler. These generated types subclass Message and implement the methods shown below.

FloatObjectiveProto(**kwargs)
498  def init(self, **kwargs):
499    self._cached_byte_size = 0
500    self._cached_byte_size_dirty = len(kwargs) > 0
501    self._fields = {}
502    # Contains a mapping from oneof field descriptors to the descriptor
503    # of the currently set field in that oneof field.
504    self._oneofs = {}
505
506    # _unknown_fields is () when empty for efficiency, and will be turned into
507    # a list if fields are added.
508    self._unknown_fields = ()
509    self._is_present_in_parent = False
510    self._listener = message_listener_mod.NullMessageListener()
511    self._listener_for_children = _Listener(self)
512    for field_name, field_value in kwargs.items():
513      field = _GetFieldByName(message_descriptor, field_name)
514      if field is None:
515        raise TypeError('%s() got an unexpected keyword argument "%s"' %
516                        (message_descriptor.name, field_name))
517      if field_value is None:
518        # field=None is the same as no field at all.
519        continue
520      if field.label == _FieldDescriptor.LABEL_REPEATED:
521        field_copy = field._default_constructor(self)
522        if field.cpp_type == _FieldDescriptor.CPPTYPE_MESSAGE:  # Composite
523          if _IsMapField(field):
524            if _IsMessageMapField(field):
525              for key in field_value:
526                field_copy[key].MergeFrom(field_value[key])
527            else:
528              field_copy.update(field_value)
529          else:
530            for val in field_value:
531              if isinstance(val, dict):
532                field_copy.add(**val)
533              else:
534                field_copy.add().MergeFrom(val)
535        else:  # Scalar
536          if field.cpp_type == _FieldDescriptor.CPPTYPE_ENUM:
537            field_value = [_GetIntegerEnumValue(field.enum_type, val)
538                           for val in field_value]
539          field_copy.extend(field_value)
540        self._fields[field] = field_copy
541      elif field.cpp_type == _FieldDescriptor.CPPTYPE_MESSAGE:
542        field_copy = field._default_constructor(self)
543        new_val = None
544        if isinstance(field_value, message_mod.Message):
545          new_val = field_value
546        elif isinstance(field_value, dict):
547          if field.message_type.full_name == _StructFullTypeName:
548            field_copy.Clear()
549            if len(field_value) == 1 and 'fields' in field_value:
550              try:
551                field_copy.update(field_value)
552              except:
553                # Fall back to init normal message field
554                field_copy.Clear()
555                new_val = field.message_type._concrete_class(**field_value)
556            else:
557              field_copy.update(field_value)
558          else:
559            new_val = field.message_type._concrete_class(**field_value)
560        elif hasattr(field_copy, '_internal_assign'):
561          field_copy._internal_assign(field_value)
562        else:
563          raise TypeError(
564              'Message field {0}.{1} must be initialized with a '
565              'dict or instance of same class, got {2}.'.format(
566                  message_descriptor.name,
567                  field_name,
568                  type(field_value).__name__,
569              )
570          )
571
572        if new_val != None:
573          try:
574            field_copy.MergeFrom(new_val)
575          except TypeError:
576            _ReraiseTypeErrorWithFieldName(message_descriptor.name, field_name)
577        self._fields[field] = field_copy
578      else:
579        if field.cpp_type == _FieldDescriptor.CPPTYPE_ENUM:
580          field_value = _GetIntegerEnumValue(field.enum_type, field_value)
581        try:
582          setattr(self, field_name, field_value)
583        except TypeError:
584          _ReraiseTypeErrorWithFieldName(message_descriptor.name, field_name)
DESCRIPTOR = <google.protobuf.descriptor.Descriptor object>
def MergeFrom(self, msg):
1364  def MergeFrom(self, msg):
1365    if not isinstance(msg, cls):
1366      raise TypeError(
1367          'Parameter to MergeFrom() must be instance of same class: '
1368          'expected %s got %s.' % (_FullyQualifiedClassName(cls),
1369                                   _FullyQualifiedClassName(msg.__class__)))
1370
1371    assert msg is not self
1372    self._Modified()
1373
1374    fields = self._fields
1375
1376    for field, value in msg._fields.items():
1377      if field.label == LABEL_REPEATED:
1378        field_value = fields.get(field)
1379        if field_value is None:
1380          # Construct a new object to represent this field.
1381          field_value = field._default_constructor(self)
1382          fields[field] = field_value
1383        field_value.MergeFrom(value)
1384      elif field.cpp_type == CPPTYPE_MESSAGE:
1385        if value._is_present_in_parent:
1386          field_value = fields.get(field)
1387          if field_value is None:
1388            # Construct a new object to represent this field.
1389            field_value = field._default_constructor(self)
1390            fields[field] = field_value
1391          field_value.MergeFrom(value)
1392      else:
1393        self._fields[field] = value
1394        if field.containing_oneof:
1395          self._UpdateOneofState(field)
1396
1397    if msg._unknown_fields:
1398      if not self._unknown_fields:
1399        self._unknown_fields = []
1400      self._unknown_fields.extend(msg._unknown_fields)

Merges the contents of the specified message into current message.

This method merges the contents of the specified message into the current message. Singular fields that are set in the specified message overwrite the corresponding fields in the current message. Repeated fields are appended. Singular sub-messages and groups are recursively merged.

Arguments:
  • other_msg (Message): A message to merge into the current message.
def Clear(self):
1423def _Clear(self):
1424  # Clear fields.
1425  self._fields = {}
1426  self._unknown_fields = ()
1427
1428  self._oneofs = {}
1429  self._Modified()

Clears all data that was set in the message.

def SetInParent(self):
1489  def Modified(self):
1490    """Sets the _cached_byte_size_dirty bit to true,
1491    and propagates this to our listener iff this was a state change.
1492    """
1493
1494    # Note:  Some callers check _cached_byte_size_dirty before calling
1495    #   _Modified() as an extra optimization.  So, if this method is ever
1496    #   changed such that it does stuff even when _cached_byte_size_dirty is
1497    #   already true, the callers need to be updated.
1498    if not self._cached_byte_size_dirty:
1499      self._cached_byte_size_dirty = True
1500      self._listener_for_children.dirty = True
1501      self._is_present_in_parent = True
1502      self._listener.Modified()

Sets the _cached_byte_size_dirty bit to true, and propagates this to our listener iff this was a state change.

def IsInitialized(self, errors=None):
1265  def IsInitialized(self, errors=None):
1266    """Checks if all required fields of a message are set.
1267
1268    Args:
1269      errors:  A list which, if provided, will be populated with the field
1270               paths of all missing required fields.
1271
1272    Returns:
1273      True iff the specified message has all required fields set.
1274    """
1275
1276    # Performance is critical so we avoid HasField() and ListFields().
1277
1278    for field in required_fields:
1279      if (field not in self._fields or
1280          (field.cpp_type == _FieldDescriptor.CPPTYPE_MESSAGE and
1281           not self._fields[field]._is_present_in_parent)):
1282        if errors is not None:
1283          errors.extend(self.FindInitializationErrors())
1284        return False
1285
1286    for field, value in list(self._fields.items()):  # dict can change size!
1287      if field.cpp_type == _FieldDescriptor.CPPTYPE_MESSAGE:
1288        if field.label == _FieldDescriptor.LABEL_REPEATED:
1289          if (field.message_type._is_map_entry):
1290            continue
1291          for element in value:
1292            if not element.IsInitialized():
1293              if errors is not None:
1294                errors.extend(self.FindInitializationErrors())
1295              return False
1296        elif value._is_present_in_parent and not value.IsInitialized():
1297          if errors is not None:
1298            errors.extend(self.FindInitializationErrors())
1299          return False
1300
1301    return True

Checks if all required fields of a message are set.

Arguments:
  • errors: A list which, if provided, will be populated with the field paths of all missing required fields.
Returns:

True iff the specified message has all required fields set.

def MergeFromString(self, serialized):
1180  def MergeFromString(self, serialized):
1181    serialized = memoryview(serialized)
1182    length = len(serialized)
1183    try:
1184      if self._InternalParse(serialized, 0, length) != length:
1185        # The only reason _InternalParse would return early is if it
1186        # encountered an end-group tag.
1187        raise message_mod.DecodeError('Unexpected end-group tag.')
1188    except (IndexError, TypeError):
1189      # Now ord(buf[p:p+1]) == ord('') gets TypeError.
1190      raise message_mod.DecodeError('Truncated message.')
1191    except struct.error as e:
1192      raise message_mod.DecodeError(e)
1193    return length   # Return this for legacy reasons.

Merges serialized protocol buffer data into this message.

When we find a field in serialized that is already present in this message:

  • If it's a "repeated" field, we append to the end of our list.
  • Else, if it's a scalar, we overwrite our field.
  • Else, (it's a nonrepeated composite), we recursively merge into the existing composite.
Arguments:
  • serialized (bytes): Any object that allows us to call memoryview(serialized) to access a string of bytes using the buffer interface.
Returns:

int: The number of bytes read from serialized. For non-group messages, this will always be len(serialized), but for messages which are actually groups, this will generally be less than len(serialized), since we must stop when we reach an END_GROUP tag. Note that if we do stop because of an END_GROUP tag, the number of bytes returned does not include the bytes for the END_GROUP tag information.

Raises:
  • DecodeError: if the input cannot be parsed.
def SerializeToString(self, **kwargs):
1133  def SerializeToString(self, **kwargs):
1134    # Check if the message has all of its required fields set.
1135    if not self.IsInitialized():
1136      raise message_mod.EncodeError(
1137          'Message %s is missing required fields: %s' % (
1138          self.DESCRIPTOR.full_name, ','.join(self.FindInitializationErrors())))
1139    return self.SerializePartialToString(**kwargs)

Serializes the protocol message to a binary string.

Keyword Args:

deterministic (bool): If true, requests deterministic serialization of the protobuf, with predictable ordering of map keys.

Returns:

A binary string representation of the message if all of the required fields in the message are set (i.e. the message is initialized).

Raises:
def SerializePartialToString(self, **kwargs):
1146  def SerializePartialToString(self, **kwargs):
1147    out = BytesIO()
1148    self._InternalSerialize(out.write, **kwargs)
1149    return out.getvalue()

Serializes the protocol message to a binary string.

This method is similar to SerializeToString but doesn't check if the message is initialized.

Keyword Args:

deterministic (bool): If true, requests deterministic serialization of the protobuf, with predictable ordering of map keys.

Returns:

bytes: A serialized representation of the partial message.

def ListFields(self):
848  def ListFields(self):
849    all_fields = [item for item in self._fields.items() if _IsPresent(item)]
850    all_fields.sort(key = lambda item: item[0].number)
851    return all_fields

Returns a list of (FieldDescriptor, value) tuples for present fields.

A message field is non-empty if HasField() would return true. A singular primitive field is non-empty if HasField() would return true in proto2 or it is non zero in proto3. A repeated field is non-empty if it contains at least one element. The fields are ordered by field number.

Returns:

list[tuple(FieldDescriptor, value)]: field descriptors and values for all fields in the message which are not empty. The values vary by field type.

def HasField(self, field_name):
872  def HasField(self, field_name):
873    try:
874      field = hassable_fields[field_name]
875    except KeyError as exc:
876      raise ValueError('Protocol message %s has no non-repeated field "%s" '
877                       'nor has presence is not available for this field.' % (
878                           message_descriptor.full_name, field_name)) from exc
879
880    if isinstance(field, descriptor_mod.OneofDescriptor):
881      try:
882        return HasField(self, self._oneofs[field].name)
883      except KeyError:
884        return False
885    else:
886      if field.cpp_type == _FieldDescriptor.CPPTYPE_MESSAGE:
887        value = self._fields.get(field)
888        return value is not None and value._is_present_in_parent
889      else:
890        return field in self._fields

Checks if a certain field is set for the message.

For a oneof group, checks if any field inside is set. Note that if the field_name is not defined in the message descriptor, ValueError will be raised.

Arguments:
  • field_name (str): The name of the field to check for presence.
Returns:

bool: Whether a value has been set for the named field.

Raises:
  • ValueError: if the field_name is not a member of this message.
def ClearField(self, field_name):
897  def ClearField(self, field_name):
898    try:
899      field = message_descriptor.fields_by_name[field_name]
900    except KeyError:
901      try:
902        field = message_descriptor.oneofs_by_name[field_name]
903        if field in self._oneofs:
904          field = self._oneofs[field]
905        else:
906          return
907      except KeyError:
908        raise ValueError('Protocol message %s has no "%s" field.' %
909                         (message_descriptor.name, field_name))
910
911    if field in self._fields:
912      # To match the C++ implementation, we need to invalidate iterators
913      # for map fields when ClearField() happens.
914      if hasattr(self._fields[field], 'InvalidateIterators'):
915        self._fields[field].InvalidateIterators()
916
917      # Note:  If the field is a sub-message, its listener will still point
918      #   at us.  That's fine, because the worst than can happen is that it
919      #   will call _Modified() and invalidate our byte size.  Big deal.
920      del self._fields[field]
921
922      if self._oneofs.get(field.containing_oneof, None) is field:
923        del self._oneofs[field.containing_oneof]
924
925    # Always call _Modified() -- even if nothing was changed, this is
926    # a mutating method, and thus calling it should cause the field to become
927    # present in the parent message.
928    self._Modified()

Clears the contents of a given field.

Inside a oneof group, clears the field set. If the name neither refers to a defined field or oneof group, ValueError is raised.

Arguments:
  • field_name (str): The name of the field to check for presence.
Raises:
  • ValueError: if the field_name is not a member of this message.
def WhichOneof(self, oneof_name):
1406  def WhichOneof(self, oneof_name):
1407    """Returns the name of the currently set field inside a oneof, or None."""
1408    try:
1409      field = message_descriptor.oneofs_by_name[oneof_name]
1410    except KeyError:
1411      raise ValueError(
1412          'Protocol message has no oneof "%s" field.' % oneof_name)
1413
1414    nested_field = self._oneofs.get(field, None)
1415    if nested_field is not None and self.HasField(nested_field.name):
1416      return nested_field.name
1417    else:
1418      return None

Returns the name of the currently set field inside a oneof, or None.

def DiscardUnknownFields(self):
1438def _DiscardUnknownFields(self):
1439  self._unknown_fields = []
1440  for field, value in self.ListFields():
1441    if field.cpp_type == _FieldDescriptor.CPPTYPE_MESSAGE:
1442      if _IsMapField(field):
1443        if _IsMessageMapField(field):
1444          for key in value:
1445            value[key].DiscardUnknownFields()
1446      elif field.label == _FieldDescriptor.LABEL_REPEATED:
1447        for sub_message in value:
1448          sub_message.DiscardUnknownFields()
1449      else:
1450        value.DiscardUnknownFields()

Clears all fields in the UnknownFieldSet.

This operation is recursive for nested message.

def ByteSize(self):
1101  def ByteSize(self):
1102    if not self._cached_byte_size_dirty:
1103      return self._cached_byte_size
1104
1105    size = 0
1106    descriptor = self.DESCRIPTOR
1107    if descriptor._is_map_entry:
1108      # Fields of map entry should always be serialized.
1109      key_field = descriptor.fields_by_name['key']
1110      _MaybeAddEncoder(cls, key_field)
1111      size = key_field._sizer(self.key)
1112      value_field = descriptor.fields_by_name['value']
1113      _MaybeAddEncoder(cls, value_field)
1114      size += value_field._sizer(self.value)
1115    else:
1116      for field_descriptor, field_value in self.ListFields():
1117        _MaybeAddEncoder(cls, field_descriptor)
1118        size += field_descriptor._sizer(field_value)
1119      for tag_bytes, value_bytes in self._unknown_fields:
1120        size += len(tag_bytes) + len(value_bytes)
1121
1122    self._cached_byte_size = size
1123    self._cached_byte_size_dirty = False
1124    self._listener_for_children.dirty = False
1125    return size

Returns the serialized size of this message.

Recursively calls ByteSize() on all contained messages.

Returns:

int: The number of bytes required to serialize this message.

def FromString(s):
826  def FromString(s):
827    message = cls()
828    message.MergeFromString(s)
829    return message
VARS_FIELD_NUMBER = 1
vars
668  def getter(self):
669    field_value = self._fields.get(field)
670    if field_value is None:
671      # Construct a new object to represent this field.
672      field_value = field._default_constructor(self)
673
674      # Atomically check if another thread has preempted us and, if not, swap
675      # in the new object we just created.  If someone has preempted us, we
676      # take that object and discard ours.
677      # WARNING:  We are relying on setdefault() being atomic.  This is true
678      #   in CPython but we haven't investigated others.  This warning appears
679      #   in several other locations in this file.
680      field_value = self._fields.setdefault(field, field_value)
681    return field_value

Getter for vars.

COEFFS_FIELD_NUMBER = 2
coeffs
668  def getter(self):
669    field_value = self._fields.get(field)
670    if field_value is None:
671      # Construct a new object to represent this field.
672      field_value = field._default_constructor(self)
673
674      # Atomically check if another thread has preempted us and, if not, swap
675      # in the new object we just created.  If someone has preempted us, we
676      # take that object and discard ours.
677      # WARNING:  We are relying on setdefault() being atomic.  This is true
678      #   in CPython but we haven't investigated others.  This warning appears
679      #   in several other locations in this file.
680      field_value = self._fields.setdefault(field, field_value)
681    return field_value

Getter for coeffs.

OFFSET_FIELD_NUMBER = 3
offset
711  def getter(self):
712    # TODO: This may be broken since there may not be
713    # default_value.  Combine with has_default_value somehow.
714    return self._fields.get(field, default_value)

Getter for offset.

MAXIMIZE_FIELD_NUMBER = 4
maximize
711  def getter(self):
712    # TODO: This may be broken since there may not be
713    # default_value.  Combine with has_default_value somehow.
714    return self._fields.get(field, default_value)

Getter for maximize.

def FindInitializationErrors(self):
1305  def FindInitializationErrors(self):
1306    """Finds required fields which are not initialized.
1307
1308    Returns:
1309      A list of strings.  Each string is a path to an uninitialized field from
1310      the top-level message, e.g. "foo.bar[5].baz".
1311    """
1312
1313    errors = []  # simplify things
1314
1315    for field in required_fields:
1316      if not self.HasField(field.name):
1317        errors.append(field.name)
1318
1319    for field, value in self.ListFields():
1320      if field.cpp_type == _FieldDescriptor.CPPTYPE_MESSAGE:
1321        if field.is_extension:
1322          name = '(%s)' % field.full_name
1323        else:
1324          name = field.name
1325
1326        if _IsMapField(field):
1327          if _IsMessageMapField(field):
1328            for key in value:
1329              element = value[key]
1330              prefix = '%s[%s].' % (name, key)
1331              sub_errors = element.FindInitializationErrors()
1332              errors += [prefix + error for error in sub_errors]
1333          else:
1334            # ScalarMaps can't have any initialization errors.
1335            pass
1336        elif field.label == _FieldDescriptor.LABEL_REPEATED:
1337          for i in range(len(value)):
1338            element = value[i]
1339            prefix = '%s[%d].' % (name, i)
1340            sub_errors = element.FindInitializationErrors()
1341            errors += [prefix + error for error in sub_errors]
1342        else:
1343          prefix = name + '.'
1344          sub_errors = value.FindInitializationErrors()
1345          errors += [prefix + error for error in sub_errors]
1346
1347    return errors

Finds required fields which are not initialized.

Returns:

A list of strings. Each string is a path to an uninitialized field from the top-level message, e.g. "foo.bar[5].baz".

class DecisionStrategyProto(google.protobuf.message.Message):

Abstract base class for protocol messages.

Protocol message classes are almost always generated by the protocol compiler. These generated types subclass Message and implement the methods shown below.

DecisionStrategyProto(**kwargs)
498  def init(self, **kwargs):
499    self._cached_byte_size = 0
500    self._cached_byte_size_dirty = len(kwargs) > 0
501    self._fields = {}
502    # Contains a mapping from oneof field descriptors to the descriptor
503    # of the currently set field in that oneof field.
504    self._oneofs = {}
505
506    # _unknown_fields is () when empty for efficiency, and will be turned into
507    # a list if fields are added.
508    self._unknown_fields = ()
509    self._is_present_in_parent = False
510    self._listener = message_listener_mod.NullMessageListener()
511    self._listener_for_children = _Listener(self)
512    for field_name, field_value in kwargs.items():
513      field = _GetFieldByName(message_descriptor, field_name)
514      if field is None:
515        raise TypeError('%s() got an unexpected keyword argument "%s"' %
516                        (message_descriptor.name, field_name))
517      if field_value is None:
518        # field=None is the same as no field at all.
519        continue
520      if field.label == _FieldDescriptor.LABEL_REPEATED:
521        field_copy = field._default_constructor(self)
522        if field.cpp_type == _FieldDescriptor.CPPTYPE_MESSAGE:  # Composite
523          if _IsMapField(field):
524            if _IsMessageMapField(field):
525              for key in field_value:
526                field_copy[key].MergeFrom(field_value[key])
527            else:
528              field_copy.update(field_value)
529          else:
530            for val in field_value:
531              if isinstance(val, dict):
532                field_copy.add(**val)
533              else:
534                field_copy.add().MergeFrom(val)
535        else:  # Scalar
536          if field.cpp_type == _FieldDescriptor.CPPTYPE_ENUM:
537            field_value = [_GetIntegerEnumValue(field.enum_type, val)
538                           for val in field_value]
539          field_copy.extend(field_value)
540        self._fields[field] = field_copy
541      elif field.cpp_type == _FieldDescriptor.CPPTYPE_MESSAGE:
542        field_copy = field._default_constructor(self)
543        new_val = None
544        if isinstance(field_value, message_mod.Message):
545          new_val = field_value
546        elif isinstance(field_value, dict):
547          if field.message_type.full_name == _StructFullTypeName:
548            field_copy.Clear()
549            if len(field_value) == 1 and 'fields' in field_value:
550              try:
551                field_copy.update(field_value)
552              except:
553                # Fall back to init normal message field
554                field_copy.Clear()
555                new_val = field.message_type._concrete_class(**field_value)
556            else:
557              field_copy.update(field_value)
558          else:
559            new_val = field.message_type._concrete_class(**field_value)
560        elif hasattr(field_copy, '_internal_assign'):
561          field_copy._internal_assign(field_value)
562        else:
563          raise TypeError(
564              'Message field {0}.{1} must be initialized with a '
565              'dict or instance of same class, got {2}.'.format(
566                  message_descriptor.name,
567                  field_name,
568                  type(field_value).__name__,
569              )
570          )
571
572        if new_val != None:
573          try:
574            field_copy.MergeFrom(new_val)
575          except TypeError:
576            _ReraiseTypeErrorWithFieldName(message_descriptor.name, field_name)
577        self._fields[field] = field_copy
578      else:
579        if field.cpp_type == _FieldDescriptor.CPPTYPE_ENUM:
580          field_value = _GetIntegerEnumValue(field.enum_type, field_value)
581        try:
582          setattr(self, field_name, field_value)
583        except TypeError:
584          _ReraiseTypeErrorWithFieldName(message_descriptor.name, field_name)
DESCRIPTOR = <google.protobuf.descriptor.Descriptor object>
def MergeFrom(self, msg):
1364  def MergeFrom(self, msg):
1365    if not isinstance(msg, cls):
1366      raise TypeError(
1367          'Parameter to MergeFrom() must be instance of same class: '
1368          'expected %s got %s.' % (_FullyQualifiedClassName(cls),
1369                                   _FullyQualifiedClassName(msg.__class__)))
1370
1371    assert msg is not self
1372    self._Modified()
1373
1374    fields = self._fields
1375
1376    for field, value in msg._fields.items():
1377      if field.label == LABEL_REPEATED:
1378        field_value = fields.get(field)
1379        if field_value is None:
1380          # Construct a new object to represent this field.
1381          field_value = field._default_constructor(self)
1382          fields[field] = field_value
1383        field_value.MergeFrom(value)
1384      elif field.cpp_type == CPPTYPE_MESSAGE:
1385        if value._is_present_in_parent:
1386          field_value = fields.get(field)
1387          if field_value is None:
1388            # Construct a new object to represent this field.
1389            field_value = field._default_constructor(self)
1390            fields[field] = field_value
1391          field_value.MergeFrom(value)
1392      else:
1393        self._fields[field] = value
1394        if field.containing_oneof:
1395          self._UpdateOneofState(field)
1396
1397    if msg._unknown_fields:
1398      if not self._unknown_fields:
1399        self._unknown_fields = []
1400      self._unknown_fields.extend(msg._unknown_fields)

Merges the contents of the specified message into current message.

This method merges the contents of the specified message into the current message. Singular fields that are set in the specified message overwrite the corresponding fields in the current message. Repeated fields are appended. Singular sub-messages and groups are recursively merged.

Arguments:
  • other_msg (Message): A message to merge into the current message.
def Clear(self):
1423def _Clear(self):
1424  # Clear fields.
1425  self._fields = {}
1426  self._unknown_fields = ()
1427
1428  self._oneofs = {}
1429  self._Modified()

Clears all data that was set in the message.

def SetInParent(self):
1489  def Modified(self):
1490    """Sets the _cached_byte_size_dirty bit to true,
1491    and propagates this to our listener iff this was a state change.
1492    """
1493
1494    # Note:  Some callers check _cached_byte_size_dirty before calling
1495    #   _Modified() as an extra optimization.  So, if this method is ever
1496    #   changed such that it does stuff even when _cached_byte_size_dirty is
1497    #   already true, the callers need to be updated.
1498    if not self._cached_byte_size_dirty:
1499      self._cached_byte_size_dirty = True
1500      self._listener_for_children.dirty = True
1501      self._is_present_in_parent = True
1502      self._listener.Modified()

Sets the _cached_byte_size_dirty bit to true, and propagates this to our listener iff this was a state change.

def IsInitialized(self, errors=None):
1265  def IsInitialized(self, errors=None):
1266    """Checks if all required fields of a message are set.
1267
1268    Args:
1269      errors:  A list which, if provided, will be populated with the field
1270               paths of all missing required fields.
1271
1272    Returns:
1273      True iff the specified message has all required fields set.
1274    """
1275
1276    # Performance is critical so we avoid HasField() and ListFields().
1277
1278    for field in required_fields:
1279      if (field not in self._fields or
1280          (field.cpp_type == _FieldDescriptor.CPPTYPE_MESSAGE and
1281           not self._fields[field]._is_present_in_parent)):
1282        if errors is not None:
1283          errors.extend(self.FindInitializationErrors())
1284        return False
1285
1286    for field, value in list(self._fields.items()):  # dict can change size!
1287      if field.cpp_type == _FieldDescriptor.CPPTYPE_MESSAGE:
1288        if field.label == _FieldDescriptor.LABEL_REPEATED:
1289          if (field.message_type._is_map_entry):
1290            continue
1291          for element in value:
1292            if not element.IsInitialized():
1293              if errors is not None:
1294                errors.extend(self.FindInitializationErrors())
1295              return False
1296        elif value._is_present_in_parent and not value.IsInitialized():
1297          if errors is not None:
1298            errors.extend(self.FindInitializationErrors())
1299          return False
1300
1301    return True

Checks if all required fields of a message are set.

Arguments:
  • errors: A list which, if provided, will be populated with the field paths of all missing required fields.
Returns:

True iff the specified message has all required fields set.

def MergeFromString(self, serialized):
1180  def MergeFromString(self, serialized):
1181    serialized = memoryview(serialized)
1182    length = len(serialized)
1183    try:
1184      if self._InternalParse(serialized, 0, length) != length:
1185        # The only reason _InternalParse would return early is if it
1186        # encountered an end-group tag.
1187        raise message_mod.DecodeError('Unexpected end-group tag.')
1188    except (IndexError, TypeError):
1189      # Now ord(buf[p:p+1]) == ord('') gets TypeError.
1190      raise message_mod.DecodeError('Truncated message.')
1191    except struct.error as e:
1192      raise message_mod.DecodeError(e)
1193    return length   # Return this for legacy reasons.

Merges serialized protocol buffer data into this message.

When we find a field in serialized that is already present in this message:

  • If it's a "repeated" field, we append to the end of our list.
  • Else, if it's a scalar, we overwrite our field.
  • Else, (it's a nonrepeated composite), we recursively merge into the existing composite.
Arguments:
  • serialized (bytes): Any object that allows us to call memoryview(serialized) to access a string of bytes using the buffer interface.
Returns:

int: The number of bytes read from serialized. For non-group messages, this will always be len(serialized), but for messages which are actually groups, this will generally be less than len(serialized), since we must stop when we reach an END_GROUP tag. Note that if we do stop because of an END_GROUP tag, the number of bytes returned does not include the bytes for the END_GROUP tag information.

Raises:
  • DecodeError: if the input cannot be parsed.
def SerializeToString(self, **kwargs):
1133  def SerializeToString(self, **kwargs):
1134    # Check if the message has all of its required fields set.
1135    if not self.IsInitialized():
1136      raise message_mod.EncodeError(
1137          'Message %s is missing required fields: %s' % (
1138          self.DESCRIPTOR.full_name, ','.join(self.FindInitializationErrors())))
1139    return self.SerializePartialToString(**kwargs)

Serializes the protocol message to a binary string.

Keyword Args:

deterministic (bool): If true, requests deterministic serialization of the protobuf, with predictable ordering of map keys.

Returns:

A binary string representation of the message if all of the required fields in the message are set (i.e. the message is initialized).

Raises:
def SerializePartialToString(self, **kwargs):
1146  def SerializePartialToString(self, **kwargs):
1147    out = BytesIO()
1148    self._InternalSerialize(out.write, **kwargs)
1149    return out.getvalue()

Serializes the protocol message to a binary string.

This method is similar to SerializeToString but doesn't check if the message is initialized.

Keyword Args:

deterministic (bool): If true, requests deterministic serialization of the protobuf, with predictable ordering of map keys.

Returns:

bytes: A serialized representation of the partial message.

def ListFields(self):
848  def ListFields(self):
849    all_fields = [item for item in self._fields.items() if _IsPresent(item)]
850    all_fields.sort(key = lambda item: item[0].number)
851    return all_fields

Returns a list of (FieldDescriptor, value) tuples for present fields.

A message field is non-empty if HasField() would return true. A singular primitive field is non-empty if HasField() would return true in proto2 or it is non zero in proto3. A repeated field is non-empty if it contains at least one element. The fields are ordered by field number.

Returns:

list[tuple(FieldDescriptor, value)]: field descriptors and values for all fields in the message which are not empty. The values vary by field type.

def HasField(self, field_name):
872  def HasField(self, field_name):
873    try:
874      field = hassable_fields[field_name]
875    except KeyError as exc:
876      raise ValueError('Protocol message %s has no non-repeated field "%s" '
877                       'nor has presence is not available for this field.' % (
878                           message_descriptor.full_name, field_name)) from exc
879
880    if isinstance(field, descriptor_mod.OneofDescriptor):
881      try:
882        return HasField(self, self._oneofs[field].name)
883      except KeyError:
884        return False
885    else:
886      if field.cpp_type == _FieldDescriptor.CPPTYPE_MESSAGE:
887        value = self._fields.get(field)
888        return value is not None and value._is_present_in_parent
889      else:
890        return field in self._fields

Checks if a certain field is set for the message.

For a oneof group, checks if any field inside is set. Note that if the field_name is not defined in the message descriptor, ValueError will be raised.

Arguments:
  • field_name (str): The name of the field to check for presence.
Returns:

bool: Whether a value has been set for the named field.

Raises:
  • ValueError: if the field_name is not a member of this message.
def ClearField(self, field_name):
897  def ClearField(self, field_name):
898    try:
899      field = message_descriptor.fields_by_name[field_name]
900    except KeyError:
901      try:
902        field = message_descriptor.oneofs_by_name[field_name]
903        if field in self._oneofs:
904          field = self._oneofs[field]
905        else:
906          return
907      except KeyError:
908        raise ValueError('Protocol message %s has no "%s" field.' %
909                         (message_descriptor.name, field_name))
910
911    if field in self._fields:
912      # To match the C++ implementation, we need to invalidate iterators
913      # for map fields when ClearField() happens.
914      if hasattr(self._fields[field], 'InvalidateIterators'):
915        self._fields[field].InvalidateIterators()
916
917      # Note:  If the field is a sub-message, its listener will still point
918      #   at us.  That's fine, because the worst than can happen is that it
919      #   will call _Modified() and invalidate our byte size.  Big deal.
920      del self._fields[field]
921
922      if self._oneofs.get(field.containing_oneof, None) is field:
923        del self._oneofs[field.containing_oneof]
924
925    # Always call _Modified() -- even if nothing was changed, this is
926    # a mutating method, and thus calling it should cause the field to become
927    # present in the parent message.
928    self._Modified()

Clears the contents of a given field.

Inside a oneof group, clears the field set. If the name neither refers to a defined field or oneof group, ValueError is raised.

Arguments:
  • field_name (str): The name of the field to check for presence.
Raises:
  • ValueError: if the field_name is not a member of this message.
def WhichOneof(self, oneof_name):
1406  def WhichOneof(self, oneof_name):
1407    """Returns the name of the currently set field inside a oneof, or None."""
1408    try:
1409      field = message_descriptor.oneofs_by_name[oneof_name]
1410    except KeyError:
1411      raise ValueError(
1412          'Protocol message has no oneof "%s" field.' % oneof_name)
1413
1414    nested_field = self._oneofs.get(field, None)
1415    if nested_field is not None and self.HasField(nested_field.name):
1416      return nested_field.name
1417    else:
1418      return None

Returns the name of the currently set field inside a oneof, or None.

def DiscardUnknownFields(self):
1438def _DiscardUnknownFields(self):
1439  self._unknown_fields = []
1440  for field, value in self.ListFields():
1441    if field.cpp_type == _FieldDescriptor.CPPTYPE_MESSAGE:
1442      if _IsMapField(field):
1443        if _IsMessageMapField(field):
1444          for key in value:
1445            value[key].DiscardUnknownFields()
1446      elif field.label == _FieldDescriptor.LABEL_REPEATED:
1447        for sub_message in value:
1448          sub_message.DiscardUnknownFields()
1449      else:
1450        value.DiscardUnknownFields()

Clears all fields in the UnknownFieldSet.

This operation is recursive for nested message.

def ByteSize(self):
1101  def ByteSize(self):
1102    if not self._cached_byte_size_dirty:
1103      return self._cached_byte_size
1104
1105    size = 0
1106    descriptor = self.DESCRIPTOR
1107    if descriptor._is_map_entry:
1108      # Fields of map entry should always be serialized.
1109      key_field = descriptor.fields_by_name['key']
1110      _MaybeAddEncoder(cls, key_field)
1111      size = key_field._sizer(self.key)
1112      value_field = descriptor.fields_by_name['value']
1113      _MaybeAddEncoder(cls, value_field)
1114      size += value_field._sizer(self.value)
1115    else:
1116      for field_descriptor, field_value in self.ListFields():
1117        _MaybeAddEncoder(cls, field_descriptor)
1118        size += field_descriptor._sizer(field_value)
1119      for tag_bytes, value_bytes in self._unknown_fields:
1120        size += len(tag_bytes) + len(value_bytes)
1121
1122    self._cached_byte_size = size
1123    self._cached_byte_size_dirty = False
1124    self._listener_for_children.dirty = False
1125    return size

Returns the serialized size of this message.

Recursively calls ByteSize() on all contained messages.

Returns:

int: The number of bytes required to serialize this message.

def FromString(s):
826  def FromString(s):
827    message = cls()
828    message.MergeFromString(s)
829    return message
VariableSelectionStrategy = <google.protobuf.internal.enum_type_wrapper.EnumTypeWrapper object>
CHOOSE_FIRST = 0
CHOOSE_LOWEST_MIN = 1
CHOOSE_HIGHEST_MAX = 2
CHOOSE_MIN_DOMAIN_SIZE = 3
CHOOSE_MAX_DOMAIN_SIZE = 4
DomainReductionStrategy = <google.protobuf.internal.enum_type_wrapper.EnumTypeWrapper object>
SELECT_MIN_VALUE = 0
SELECT_MAX_VALUE = 1
SELECT_LOWER_HALF = 2
SELECT_UPPER_HALF = 3
SELECT_MEDIAN_VALUE = 4
SELECT_RANDOM_HALF = 5
VARIABLES_FIELD_NUMBER = 1
variables
668  def getter(self):
669    field_value = self._fields.get(field)
670    if field_value is None:
671      # Construct a new object to represent this field.
672      field_value = field._default_constructor(self)
673
674      # Atomically check if another thread has preempted us and, if not, swap
675      # in the new object we just created.  If someone has preempted us, we
676      # take that object and discard ours.
677      # WARNING:  We are relying on setdefault() being atomic.  This is true
678      #   in CPython but we haven't investigated others.  This warning appears
679      #   in several other locations in this file.
680      field_value = self._fields.setdefault(field, field_value)
681    return field_value

Getter for variables.

EXPRS_FIELD_NUMBER = 5
exprs
668  def getter(self):
669    field_value = self._fields.get(field)
670    if field_value is None:
671      # Construct a new object to represent this field.
672      field_value = field._default_constructor(self)
673
674      # Atomically check if another thread has preempted us and, if not, swap
675      # in the new object we just created.  If someone has preempted us, we
676      # take that object and discard ours.
677      # WARNING:  We are relying on setdefault() being atomic.  This is true
678      #   in CPython but we haven't investigated others.  This warning appears
679      #   in several other locations in this file.
680      field_value = self._fields.setdefault(field, field_value)
681    return field_value

Getter for exprs.

VARIABLE_SELECTION_STRATEGY_FIELD_NUMBER = 2
variable_selection_strategy
711  def getter(self):
712    # TODO: This may be broken since there may not be
713    # default_value.  Combine with has_default_value somehow.
714    return self._fields.get(field, default_value)

Getter for variable_selection_strategy.

DOMAIN_REDUCTION_STRATEGY_FIELD_NUMBER = 3
domain_reduction_strategy
711  def getter(self):
712    # TODO: This may be broken since there may not be
713    # default_value.  Combine with has_default_value somehow.
714    return self._fields.get(field, default_value)

Getter for domain_reduction_strategy.

def FindInitializationErrors(self):
1305  def FindInitializationErrors(self):
1306    """Finds required fields which are not initialized.
1307
1308    Returns:
1309      A list of strings.  Each string is a path to an uninitialized field from
1310      the top-level message, e.g. "foo.bar[5].baz".
1311    """
1312
1313    errors = []  # simplify things
1314
1315    for field in required_fields:
1316      if not self.HasField(field.name):
1317        errors.append(field.name)
1318
1319    for field, value in self.ListFields():
1320      if field.cpp_type == _FieldDescriptor.CPPTYPE_MESSAGE:
1321        if field.is_extension:
1322          name = '(%s)' % field.full_name
1323        else:
1324          name = field.name
1325
1326        if _IsMapField(field):
1327          if _IsMessageMapField(field):
1328            for key in value:
1329              element = value[key]
1330              prefix = '%s[%s].' % (name, key)
1331              sub_errors = element.FindInitializationErrors()
1332              errors += [prefix + error for error in sub_errors]
1333          else:
1334            # ScalarMaps can't have any initialization errors.
1335            pass
1336        elif field.label == _FieldDescriptor.LABEL_REPEATED:
1337          for i in range(len(value)):
1338            element = value[i]
1339            prefix = '%s[%d].' % (name, i)
1340            sub_errors = element.FindInitializationErrors()
1341            errors += [prefix + error for error in sub_errors]
1342        else:
1343          prefix = name + '.'
1344          sub_errors = value.FindInitializationErrors()
1345          errors += [prefix + error for error in sub_errors]
1346
1347    return errors

Finds required fields which are not initialized.

Returns:

A list of strings. Each string is a path to an uninitialized field from the top-level message, e.g. "foo.bar[5].baz".

class PartialVariableAssignment(google.protobuf.message.Message):

Abstract base class for protocol messages.

Protocol message classes are almost always generated by the protocol compiler. These generated types subclass Message and implement the methods shown below.

PartialVariableAssignment(**kwargs)
498  def init(self, **kwargs):
499    self._cached_byte_size = 0
500    self._cached_byte_size_dirty = len(kwargs) > 0
501    self._fields = {}
502    # Contains a mapping from oneof field descriptors to the descriptor
503    # of the currently set field in that oneof field.
504    self._oneofs = {}
505
506    # _unknown_fields is () when empty for efficiency, and will be turned into
507    # a list if fields are added.
508    self._unknown_fields = ()
509    self._is_present_in_parent = False
510    self._listener = message_listener_mod.NullMessageListener()
511    self._listener_for_children = _Listener(self)
512    for field_name, field_value in kwargs.items():
513      field = _GetFieldByName(message_descriptor, field_name)
514      if field is None:
515        raise TypeError('%s() got an unexpected keyword argument "%s"' %
516                        (message_descriptor.name, field_name))
517      if field_value is None:
518        # field=None is the same as no field at all.
519        continue
520      if field.label == _FieldDescriptor.LABEL_REPEATED:
521        field_copy = field._default_constructor(self)
522        if field.cpp_type == _FieldDescriptor.CPPTYPE_MESSAGE:  # Composite
523          if _IsMapField(field):
524            if _IsMessageMapField(field):
525              for key in field_value:
526                field_copy[key].MergeFrom(field_value[key])
527            else:
528              field_copy.update(field_value)
529          else:
530            for val in field_value:
531              if isinstance(val, dict):
532                field_copy.add(**val)
533              else:
534                field_copy.add().MergeFrom(val)
535        else:  # Scalar
536          if field.cpp_type == _FieldDescriptor.CPPTYPE_ENUM:
537            field_value = [_GetIntegerEnumValue(field.enum_type, val)
538                           for val in field_value]
539          field_copy.extend(field_value)
540        self._fields[field] = field_copy
541      elif field.cpp_type == _FieldDescriptor.CPPTYPE_MESSAGE:
542        field_copy = field._default_constructor(self)
543        new_val = None
544        if isinstance(field_value, message_mod.Message):
545          new_val = field_value
546        elif isinstance(field_value, dict):
547          if field.message_type.full_name == _StructFullTypeName:
548            field_copy.Clear()
549            if len(field_value) == 1 and 'fields' in field_value:
550              try:
551                field_copy.update(field_value)
552              except:
553                # Fall back to init normal message field
554                field_copy.Clear()
555                new_val = field.message_type._concrete_class(**field_value)
556            else:
557              field_copy.update(field_value)
558          else:
559            new_val = field.message_type._concrete_class(**field_value)
560        elif hasattr(field_copy, '_internal_assign'):
561          field_copy._internal_assign(field_value)
562        else:
563          raise TypeError(
564              'Message field {0}.{1} must be initialized with a '
565              'dict or instance of same class, got {2}.'.format(
566                  message_descriptor.name,
567                  field_name,
568                  type(field_value).__name__,
569              )
570          )
571
572        if new_val != None:
573          try:
574            field_copy.MergeFrom(new_val)
575          except TypeError:
576            _ReraiseTypeErrorWithFieldName(message_descriptor.name, field_name)
577        self._fields[field] = field_copy
578      else:
579        if field.cpp_type == _FieldDescriptor.CPPTYPE_ENUM:
580          field_value = _GetIntegerEnumValue(field.enum_type, field_value)
581        try:
582          setattr(self, field_name, field_value)
583        except TypeError:
584          _ReraiseTypeErrorWithFieldName(message_descriptor.name, field_name)
DESCRIPTOR = <google.protobuf.descriptor.Descriptor object>
def MergeFrom(self, msg):
1364  def MergeFrom(self, msg):
1365    if not isinstance(msg, cls):
1366      raise TypeError(
1367          'Parameter to MergeFrom() must be instance of same class: '
1368          'expected %s got %s.' % (_FullyQualifiedClassName(cls),
1369                                   _FullyQualifiedClassName(msg.__class__)))
1370
1371    assert msg is not self
1372    self._Modified()
1373
1374    fields = self._fields
1375
1376    for field, value in msg._fields.items():
1377      if field.label == LABEL_REPEATED:
1378        field_value = fields.get(field)
1379        if field_value is None:
1380          # Construct a new object to represent this field.
1381          field_value = field._default_constructor(self)
1382          fields[field] = field_value
1383        field_value.MergeFrom(value)
1384      elif field.cpp_type == CPPTYPE_MESSAGE:
1385        if value._is_present_in_parent:
1386          field_value = fields.get(field)
1387          if field_value is None:
1388            # Construct a new object to represent this field.
1389            field_value = field._default_constructor(self)
1390            fields[field] = field_value
1391          field_value.MergeFrom(value)
1392      else:
1393        self._fields[field] = value
1394        if field.containing_oneof:
1395          self._UpdateOneofState(field)
1396
1397    if msg._unknown_fields:
1398      if not self._unknown_fields:
1399        self._unknown_fields = []
1400      self._unknown_fields.extend(msg._unknown_fields)

Merges the contents of the specified message into current message.

This method merges the contents of the specified message into the current message. Singular fields that are set in the specified message overwrite the corresponding fields in the current message. Repeated fields are appended. Singular sub-messages and groups are recursively merged.

Arguments:
  • other_msg (Message): A message to merge into the current message.
def Clear(self):
1423def _Clear(self):
1424  # Clear fields.
1425  self._fields = {}
1426  self._unknown_fields = ()
1427
1428  self._oneofs = {}
1429  self._Modified()

Clears all data that was set in the message.

def SetInParent(self):
1489  def Modified(self):
1490    """Sets the _cached_byte_size_dirty bit to true,
1491    and propagates this to our listener iff this was a state change.
1492    """
1493
1494    # Note:  Some callers check _cached_byte_size_dirty before calling
1495    #   _Modified() as an extra optimization.  So, if this method is ever
1496    #   changed such that it does stuff even when _cached_byte_size_dirty is
1497    #   already true, the callers need to be updated.
1498    if not self._cached_byte_size_dirty:
1499      self._cached_byte_size_dirty = True
1500      self._listener_for_children.dirty = True
1501      self._is_present_in_parent = True
1502      self._listener.Modified()

Sets the _cached_byte_size_dirty bit to true, and propagates this to our listener iff this was a state change.

def IsInitialized(self, errors=None):
1265  def IsInitialized(self, errors=None):
1266    """Checks if all required fields of a message are set.
1267
1268    Args:
1269      errors:  A list which, if provided, will be populated with the field
1270               paths of all missing required fields.
1271
1272    Returns:
1273      True iff the specified message has all required fields set.
1274    """
1275
1276    # Performance is critical so we avoid HasField() and ListFields().
1277
1278    for field in required_fields:
1279      if (field not in self._fields or
1280          (field.cpp_type == _FieldDescriptor.CPPTYPE_MESSAGE and
1281           not self._fields[field]._is_present_in_parent)):
1282        if errors is not None:
1283          errors.extend(self.FindInitializationErrors())
1284        return False
1285
1286    for field, value in list(self._fields.items()):  # dict can change size!
1287      if field.cpp_type == _FieldDescriptor.CPPTYPE_MESSAGE:
1288        if field.label == _FieldDescriptor.LABEL_REPEATED:
1289          if (field.message_type._is_map_entry):
1290            continue
1291          for element in value:
1292            if not element.IsInitialized():
1293              if errors is not None:
1294                errors.extend(self.FindInitializationErrors())
1295              return False
1296        elif value._is_present_in_parent and not value.IsInitialized():
1297          if errors is not None:
1298            errors.extend(self.FindInitializationErrors())
1299          return False
1300
1301    return True

Checks if all required fields of a message are set.

Arguments:
  • errors: A list which, if provided, will be populated with the field paths of all missing required fields.
Returns:

True iff the specified message has all required fields set.

def MergeFromString(self, serialized):
1180  def MergeFromString(self, serialized):
1181    serialized = memoryview(serialized)
1182    length = len(serialized)
1183    try:
1184      if self._InternalParse(serialized, 0, length) != length:
1185        # The only reason _InternalParse would return early is if it
1186        # encountered an end-group tag.
1187        raise message_mod.DecodeError('Unexpected end-group tag.')
1188    except (IndexError, TypeError):
1189      # Now ord(buf[p:p+1]) == ord('') gets TypeError.
1190      raise message_mod.DecodeError('Truncated message.')
1191    except struct.error as e:
1192      raise message_mod.DecodeError(e)
1193    return length   # Return this for legacy reasons.

Merges serialized protocol buffer data into this message.

When we find a field in serialized that is already present in this message:

  • If it's a "repeated" field, we append to the end of our list.
  • Else, if it's a scalar, we overwrite our field.
  • Else, (it's a nonrepeated composite), we recursively merge into the existing composite.
Arguments:
  • serialized (bytes): Any object that allows us to call memoryview(serialized) to access a string of bytes using the buffer interface.
Returns:

int: The number of bytes read from serialized. For non-group messages, this will always be len(serialized), but for messages which are actually groups, this will generally be less than len(serialized), since we must stop when we reach an END_GROUP tag. Note that if we do stop because of an END_GROUP tag, the number of bytes returned does not include the bytes for the END_GROUP tag information.

Raises:
  • DecodeError: if the input cannot be parsed.
def SerializeToString(self, **kwargs):
1133  def SerializeToString(self, **kwargs):
1134    # Check if the message has all of its required fields set.
1135    if not self.IsInitialized():
1136      raise message_mod.EncodeError(
1137          'Message %s is missing required fields: %s' % (
1138          self.DESCRIPTOR.full_name, ','.join(self.FindInitializationErrors())))
1139    return self.SerializePartialToString(**kwargs)

Serializes the protocol message to a binary string.

Keyword Args:

deterministic (bool): If true, requests deterministic serialization of the protobuf, with predictable ordering of map keys.

Returns:

A binary string representation of the message if all of the required fields in the message are set (i.e. the message is initialized).

Raises:
def SerializePartialToString(self, **kwargs):
1146  def SerializePartialToString(self, **kwargs):
1147    out = BytesIO()
1148    self._InternalSerialize(out.write, **kwargs)
1149    return out.getvalue()

Serializes the protocol message to a binary string.

This method is similar to SerializeToString but doesn't check if the message is initialized.

Keyword Args:

deterministic (bool): If true, requests deterministic serialization of the protobuf, with predictable ordering of map keys.

Returns:

bytes: A serialized representation of the partial message.

def ListFields(self):
848  def ListFields(self):
849    all_fields = [item for item in self._fields.items() if _IsPresent(item)]
850    all_fields.sort(key = lambda item: item[0].number)
851    return all_fields

Returns a list of (FieldDescriptor, value) tuples for present fields.

A message field is non-empty if HasField() would return true. A singular primitive field is non-empty if HasField() would return true in proto2 or it is non zero in proto3. A repeated field is non-empty if it contains at least one element. The fields are ordered by field number.

Returns:

list[tuple(FieldDescriptor, value)]: field descriptors and values for all fields in the message which are not empty. The values vary by field type.

def HasField(self, field_name):
872  def HasField(self, field_name):
873    try:
874      field = hassable_fields[field_name]
875    except KeyError as exc:
876      raise ValueError('Protocol message %s has no non-repeated field "%s" '
877                       'nor has presence is not available for this field.' % (
878                           message_descriptor.full_name, field_name)) from exc
879
880    if isinstance(field, descriptor_mod.OneofDescriptor):
881      try:
882        return HasField(self, self._oneofs[field].name)
883      except KeyError:
884        return False
885    else:
886      if field.cpp_type == _FieldDescriptor.CPPTYPE_MESSAGE:
887        value = self._fields.get(field)
888        return value is not None and value._is_present_in_parent
889      else:
890        return field in self._fields

Checks if a certain field is set for the message.

For a oneof group, checks if any field inside is set. Note that if the field_name is not defined in the message descriptor, ValueError will be raised.

Arguments:
  • field_name (str): The name of the field to check for presence.
Returns:

bool: Whether a value has been set for the named field.

Raises:
  • ValueError: if the field_name is not a member of this message.
def ClearField(self, field_name):
897  def ClearField(self, field_name):
898    try:
899      field = message_descriptor.fields_by_name[field_name]
900    except KeyError:
901      try:
902        field = message_descriptor.oneofs_by_name[field_name]
903        if field in self._oneofs:
904          field = self._oneofs[field]
905        else:
906          return
907      except KeyError:
908        raise ValueError('Protocol message %s has no "%s" field.' %
909                         (message_descriptor.name, field_name))
910
911    if field in self._fields:
912      # To match the C++ implementation, we need to invalidate iterators
913      # for map fields when ClearField() happens.
914      if hasattr(self._fields[field], 'InvalidateIterators'):
915        self._fields[field].InvalidateIterators()
916
917      # Note:  If the field is a sub-message, its listener will still point
918      #   at us.  That's fine, because the worst than can happen is that it
919      #   will call _Modified() and invalidate our byte size.  Big deal.
920      del self._fields[field]
921
922      if self._oneofs.get(field.containing_oneof, None) is field:
923        del self._oneofs[field.containing_oneof]
924
925    # Always call _Modified() -- even if nothing was changed, this is
926    # a mutating method, and thus calling it should cause the field to become
927    # present in the parent message.
928    self._Modified()

Clears the contents of a given field.

Inside a oneof group, clears the field set. If the name neither refers to a defined field or oneof group, ValueError is raised.

Arguments:
  • field_name (str): The name of the field to check for presence.
Raises:
  • ValueError: if the field_name is not a member of this message.
def WhichOneof(self, oneof_name):
1406  def WhichOneof(self, oneof_name):
1407    """Returns the name of the currently set field inside a oneof, or None."""
1408    try:
1409      field = message_descriptor.oneofs_by_name[oneof_name]
1410    except KeyError:
1411      raise ValueError(
1412          'Protocol message has no oneof "%s" field.' % oneof_name)
1413
1414    nested_field = self._oneofs.get(field, None)
1415    if nested_field is not None and self.HasField(nested_field.name):
1416      return nested_field.name
1417    else:
1418      return None

Returns the name of the currently set field inside a oneof, or None.

def DiscardUnknownFields(self):
1438def _DiscardUnknownFields(self):
1439  self._unknown_fields = []
1440  for field, value in self.ListFields():
1441    if field.cpp_type == _FieldDescriptor.CPPTYPE_MESSAGE:
1442      if _IsMapField(field):
1443        if _IsMessageMapField(field):
1444          for key in value:
1445            value[key].DiscardUnknownFields()
1446      elif field.label == _FieldDescriptor.LABEL_REPEATED:
1447        for sub_message in value:
1448          sub_message.DiscardUnknownFields()
1449      else:
1450        value.DiscardUnknownFields()

Clears all fields in the UnknownFieldSet.

This operation is recursive for nested message.

def ByteSize(self):
1101  def ByteSize(self):
1102    if not self._cached_byte_size_dirty:
1103      return self._cached_byte_size
1104
1105    size = 0
1106    descriptor = self.DESCRIPTOR
1107    if descriptor._is_map_entry:
1108      # Fields of map entry should always be serialized.
1109      key_field = descriptor.fields_by_name['key']
1110      _MaybeAddEncoder(cls, key_field)
1111      size = key_field._sizer(self.key)
1112      value_field = descriptor.fields_by_name['value']
1113      _MaybeAddEncoder(cls, value_field)
1114      size += value_field._sizer(self.value)
1115    else:
1116      for field_descriptor, field_value in self.ListFields():
1117        _MaybeAddEncoder(cls, field_descriptor)
1118        size += field_descriptor._sizer(field_value)
1119      for tag_bytes, value_bytes in self._unknown_fields:
1120        size += len(tag_bytes) + len(value_bytes)
1121
1122    self._cached_byte_size = size
1123    self._cached_byte_size_dirty = False
1124    self._listener_for_children.dirty = False
1125    return size

Returns the serialized size of this message.

Recursively calls ByteSize() on all contained messages.

Returns:

int: The number of bytes required to serialize this message.

def FromString(s):
826  def FromString(s):
827    message = cls()
828    message.MergeFromString(s)
829    return message
VARS_FIELD_NUMBER = 1
vars
668  def getter(self):
669    field_value = self._fields.get(field)
670    if field_value is None:
671      # Construct a new object to represent this field.
672      field_value = field._default_constructor(self)
673
674      # Atomically check if another thread has preempted us and, if not, swap
675      # in the new object we just created.  If someone has preempted us, we
676      # take that object and discard ours.
677      # WARNING:  We are relying on setdefault() being atomic.  This is true
678      #   in CPython but we haven't investigated others.  This warning appears
679      #   in several other locations in this file.
680      field_value = self._fields.setdefault(field, field_value)
681    return field_value

Getter for vars.

VALUES_FIELD_NUMBER = 2
values
668  def getter(self):
669    field_value = self._fields.get(field)
670    if field_value is None:
671      # Construct a new object to represent this field.
672      field_value = field._default_constructor(self)
673
674      # Atomically check if another thread has preempted us and, if not, swap
675      # in the new object we just created.  If someone has preempted us, we
676      # take that object and discard ours.
677      # WARNING:  We are relying on setdefault() being atomic.  This is true
678      #   in CPython but we haven't investigated others.  This warning appears
679      #   in several other locations in this file.
680      field_value = self._fields.setdefault(field, field_value)
681    return field_value

Getter for values.

def FindInitializationErrors(self):
1305  def FindInitializationErrors(self):
1306    """Finds required fields which are not initialized.
1307
1308    Returns:
1309      A list of strings.  Each string is a path to an uninitialized field from
1310      the top-level message, e.g. "foo.bar[5].baz".
1311    """
1312
1313    errors = []  # simplify things
1314
1315    for field in required_fields:
1316      if not self.HasField(field.name):
1317        errors.append(field.name)
1318
1319    for field, value in self.ListFields():
1320      if field.cpp_type == _FieldDescriptor.CPPTYPE_MESSAGE:
1321        if field.is_extension:
1322          name = '(%s)' % field.full_name
1323        else:
1324          name = field.name
1325
1326        if _IsMapField(field):
1327          if _IsMessageMapField(field):
1328            for key in value:
1329              element = value[key]
1330              prefix = '%s[%s].' % (name, key)
1331              sub_errors = element.FindInitializationErrors()
1332              errors += [prefix + error for error in sub_errors]
1333          else:
1334            # ScalarMaps can't have any initialization errors.
1335            pass
1336        elif field.label == _FieldDescriptor.LABEL_REPEATED:
1337          for i in range(len(value)):
1338            element = value[i]
1339            prefix = '%s[%d].' % (name, i)
1340            sub_errors = element.FindInitializationErrors()
1341            errors += [prefix + error for error in sub_errors]
1342        else:
1343          prefix = name + '.'
1344          sub_errors = value.FindInitializationErrors()
1345          errors += [prefix + error for error in sub_errors]
1346
1347    return errors

Finds required fields which are not initialized.

Returns:

A list of strings. Each string is a path to an uninitialized field from the top-level message, e.g. "foo.bar[5].baz".

class SparsePermutationProto(google.protobuf.message.Message):

Abstract base class for protocol messages.

Protocol message classes are almost always generated by the protocol compiler. These generated types subclass Message and implement the methods shown below.

SparsePermutationProto(**kwargs)
498  def init(self, **kwargs):
499    self._cached_byte_size = 0
500    self._cached_byte_size_dirty = len(kwargs) > 0
501    self._fields = {}
502    # Contains a mapping from oneof field descriptors to the descriptor
503    # of the currently set field in that oneof field.
504    self._oneofs = {}
505
506    # _unknown_fields is () when empty for efficiency, and will be turned into
507    # a list if fields are added.
508    self._unknown_fields = ()
509    self._is_present_in_parent = False
510    self._listener = message_listener_mod.NullMessageListener()
511    self._listener_for_children = _Listener(self)
512    for field_name, field_value in kwargs.items():
513      field = _GetFieldByName(message_descriptor, field_name)
514      if field is None:
515        raise TypeError('%s() got an unexpected keyword argument "%s"' %
516                        (message_descriptor.name, field_name))
517      if field_value is None:
518        # field=None is the same as no field at all.
519        continue
520      if field.label == _FieldDescriptor.LABEL_REPEATED:
521        field_copy = field._default_constructor(self)
522        if field.cpp_type == _FieldDescriptor.CPPTYPE_MESSAGE:  # Composite
523          if _IsMapField(field):
524            if _IsMessageMapField(field):
525              for key in field_value:
526                field_copy[key].MergeFrom(field_value[key])
527            else:
528              field_copy.update(field_value)
529          else:
530            for val in field_value:
531              if isinstance(val, dict):
532                field_copy.add(**val)
533              else:
534                field_copy.add().MergeFrom(val)
535        else:  # Scalar
536          if field.cpp_type == _FieldDescriptor.CPPTYPE_ENUM:
537            field_value = [_GetIntegerEnumValue(field.enum_type, val)
538                           for val in field_value]
539          field_copy.extend(field_value)
540        self._fields[field] = field_copy
541      elif field.cpp_type == _FieldDescriptor.CPPTYPE_MESSAGE:
542        field_copy = field._default_constructor(self)
543        new_val = None
544        if isinstance(field_value, message_mod.Message):
545          new_val = field_value
546        elif isinstance(field_value, dict):
547          if field.message_type.full_name == _StructFullTypeName:
548            field_copy.Clear()
549            if len(field_value) == 1 and 'fields' in field_value:
550              try:
551                field_copy.update(field_value)
552              except:
553                # Fall back to init normal message field
554                field_copy.Clear()
555                new_val = field.message_type._concrete_class(**field_value)
556            else:
557              field_copy.update(field_value)
558          else:
559            new_val = field.message_type._concrete_class(**field_value)
560        elif hasattr(field_copy, '_internal_assign'):
561          field_copy._internal_assign(field_value)
562        else:
563          raise TypeError(
564              'Message field {0}.{1} must be initialized with a '
565              'dict or instance of same class, got {2}.'.format(
566                  message_descriptor.name,
567                  field_name,
568                  type(field_value).__name__,
569              )
570          )
571
572        if new_val != None:
573          try:
574            field_copy.MergeFrom(new_val)
575          except TypeError:
576            _ReraiseTypeErrorWithFieldName(message_descriptor.name, field_name)
577        self._fields[field] = field_copy
578      else:
579        if field.cpp_type == _FieldDescriptor.CPPTYPE_ENUM:
580          field_value = _GetIntegerEnumValue(field.enum_type, field_value)
581        try:
582          setattr(self, field_name, field_value)
583        except TypeError:
584          _ReraiseTypeErrorWithFieldName(message_descriptor.name, field_name)
DESCRIPTOR = <google.protobuf.descriptor.Descriptor object>
def MergeFrom(self, msg):
1364  def MergeFrom(self, msg):
1365    if not isinstance(msg, cls):
1366      raise TypeError(
1367          'Parameter to MergeFrom() must be instance of same class: '
1368          'expected %s got %s.' % (_FullyQualifiedClassName(cls),
1369                                   _FullyQualifiedClassName(msg.__class__)))
1370
1371    assert msg is not self
1372    self._Modified()
1373
1374    fields = self._fields
1375
1376    for field, value in msg._fields.items():
1377      if field.label == LABEL_REPEATED:
1378        field_value = fields.get(field)
1379        if field_value is None:
1380          # Construct a new object to represent this field.
1381          field_value = field._default_constructor(self)
1382          fields[field] = field_value
1383        field_value.MergeFrom(value)
1384      elif field.cpp_type == CPPTYPE_MESSAGE:
1385        if value._is_present_in_parent:
1386          field_value = fields.get(field)
1387          if field_value is None:
1388            # Construct a new object to represent this field.
1389            field_value = field._default_constructor(self)
1390            fields[field] = field_value
1391          field_value.MergeFrom(value)
1392      else:
1393        self._fields[field] = value
1394        if field.containing_oneof:
1395          self._UpdateOneofState(field)
1396
1397    if msg._unknown_fields:
1398      if not self._unknown_fields:
1399        self._unknown_fields = []
1400      self._unknown_fields.extend(msg._unknown_fields)

Merges the contents of the specified message into current message.

This method merges the contents of the specified message into the current message. Singular fields that are set in the specified message overwrite the corresponding fields in the current message. Repeated fields are appended. Singular sub-messages and groups are recursively merged.

Arguments:
  • other_msg (Message): A message to merge into the current message.
def Clear(self):
1423def _Clear(self):
1424  # Clear fields.
1425  self._fields = {}
1426  self._unknown_fields = ()
1427
1428  self._oneofs = {}
1429  self._Modified()

Clears all data that was set in the message.

def SetInParent(self):
1489  def Modified(self):
1490    """Sets the _cached_byte_size_dirty bit to true,
1491    and propagates this to our listener iff this was a state change.
1492    """
1493
1494    # Note:  Some callers check _cached_byte_size_dirty before calling
1495    #   _Modified() as an extra optimization.  So, if this method is ever
1496    #   changed such that it does stuff even when _cached_byte_size_dirty is
1497    #   already true, the callers need to be updated.
1498    if not self._cached_byte_size_dirty:
1499      self._cached_byte_size_dirty = True
1500      self._listener_for_children.dirty = True
1501      self._is_present_in_parent = True
1502      self._listener.Modified()

Sets the _cached_byte_size_dirty bit to true, and propagates this to our listener iff this was a state change.

def IsInitialized(self, errors=None):
1265  def IsInitialized(self, errors=None):
1266    """Checks if all required fields of a message are set.
1267
1268    Args:
1269      errors:  A list which, if provided, will be populated with the field
1270               paths of all missing required fields.
1271
1272    Returns:
1273      True iff the specified message has all required fields set.
1274    """
1275
1276    # Performance is critical so we avoid HasField() and ListFields().
1277
1278    for field in required_fields:
1279      if (field not in self._fields or
1280          (field.cpp_type == _FieldDescriptor.CPPTYPE_MESSAGE and
1281           not self._fields[field]._is_present_in_parent)):
1282        if errors is not None:
1283          errors.extend(self.FindInitializationErrors())
1284        return False
1285
1286    for field, value in list(self._fields.items()):  # dict can change size!
1287      if field.cpp_type == _FieldDescriptor.CPPTYPE_MESSAGE:
1288        if field.label == _FieldDescriptor.LABEL_REPEATED:
1289          if (field.message_type._is_map_entry):
1290            continue
1291          for element in value:
1292            if not element.IsInitialized():
1293              if errors is not None:
1294                errors.extend(self.FindInitializationErrors())
1295              return False
1296        elif value._is_present_in_parent and not value.IsInitialized():
1297          if errors is not None:
1298            errors.extend(self.FindInitializationErrors())
1299          return False
1300
1301    return True

Checks if all required fields of a message are set.

Arguments:
  • errors: A list which, if provided, will be populated with the field paths of all missing required fields.
Returns:

True iff the specified message has all required fields set.

def MergeFromString(self, serialized):
1180  def MergeFromString(self, serialized):
1181    serialized = memoryview(serialized)
1182    length = len(serialized)
1183    try:
1184      if self._InternalParse(serialized, 0, length) != length:
1185        # The only reason _InternalParse would return early is if it
1186        # encountered an end-group tag.
1187        raise message_mod.DecodeError('Unexpected end-group tag.')
1188    except (IndexError, TypeError):
1189      # Now ord(buf[p:p+1]) == ord('') gets TypeError.
1190      raise message_mod.DecodeError('Truncated message.')
1191    except struct.error as e:
1192      raise message_mod.DecodeError(e)
1193    return length   # Return this for legacy reasons.

Merges serialized protocol buffer data into this message.

When we find a field in serialized that is already present in this message:

  • If it's a "repeated" field, we append to the end of our list.
  • Else, if it's a scalar, we overwrite our field.
  • Else, (it's a nonrepeated composite), we recursively merge into the existing composite.
Arguments:
  • serialized (bytes): Any object that allows us to call memoryview(serialized) to access a string of bytes using the buffer interface.
Returns:

int: The number of bytes read from serialized. For non-group messages, this will always be len(serialized), but for messages which are actually groups, this will generally be less than len(serialized), since we must stop when we reach an END_GROUP tag. Note that if we do stop because of an END_GROUP tag, the number of bytes returned does not include the bytes for the END_GROUP tag information.

Raises:
  • DecodeError: if the input cannot be parsed.
def SerializeToString(self, **kwargs):
1133  def SerializeToString(self, **kwargs):
1134    # Check if the message has all of its required fields set.
1135    if not self.IsInitialized():
1136      raise message_mod.EncodeError(
1137          'Message %s is missing required fields: %s' % (
1138          self.DESCRIPTOR.full_name, ','.join(self.FindInitializationErrors())))
1139    return self.SerializePartialToString(**kwargs)

Serializes the protocol message to a binary string.

Keyword Args:

deterministic (bool): If true, requests deterministic serialization of the protobuf, with predictable ordering of map keys.

Returns:

A binary string representation of the message if all of the required fields in the message are set (i.e. the message is initialized).

Raises:
def SerializePartialToString(self, **kwargs):
1146  def SerializePartialToString(self, **kwargs):
1147    out = BytesIO()
1148    self._InternalSerialize(out.write, **kwargs)
1149    return out.getvalue()

Serializes the protocol message to a binary string.

This method is similar to SerializeToString but doesn't check if the message is initialized.

Keyword Args:

deterministic (bool): If true, requests deterministic serialization of the protobuf, with predictable ordering of map keys.

Returns:

bytes: A serialized representation of the partial message.

def ListFields(self):
848  def ListFields(self):
849    all_fields = [item for item in self._fields.items() if _IsPresent(item)]
850    all_fields.sort(key = lambda item: item[0].number)
851    return all_fields

Returns a list of (FieldDescriptor, value) tuples for present fields.

A message field is non-empty if HasField() would return true. A singular primitive field is non-empty if HasField() would return true in proto2 or it is non zero in proto3. A repeated field is non-empty if it contains at least one element. The fields are ordered by field number.

Returns:

list[tuple(FieldDescriptor, value)]: field descriptors and values for all fields in the message which are not empty. The values vary by field type.

def HasField(self, field_name):
872  def HasField(self, field_name):
873    try:
874      field = hassable_fields[field_name]
875    except KeyError as exc:
876      raise ValueError('Protocol message %s has no non-repeated field "%s" '
877                       'nor has presence is not available for this field.' % (
878                           message_descriptor.full_name, field_name)) from exc
879
880    if isinstance(field, descriptor_mod.OneofDescriptor):
881      try:
882        return HasField(self, self._oneofs[field].name)
883      except KeyError:
884        return False
885    else:
886      if field.cpp_type == _FieldDescriptor.CPPTYPE_MESSAGE:
887        value = self._fields.get(field)
888        return value is not None and value._is_present_in_parent
889      else:
890        return field in self._fields

Checks if a certain field is set for the message.

For a oneof group, checks if any field inside is set. Note that if the field_name is not defined in the message descriptor, ValueError will be raised.

Arguments:
  • field_name (str): The name of the field to check for presence.
Returns:

bool: Whether a value has been set for the named field.

Raises:
  • ValueError: if the field_name is not a member of this message.
def ClearField(self, field_name):
897  def ClearField(self, field_name):
898    try:
899      field = message_descriptor.fields_by_name[field_name]
900    except KeyError:
901      try:
902        field = message_descriptor.oneofs_by_name[field_name]
903        if field in self._oneofs:
904          field = self._oneofs[field]
905        else:
906          return
907      except KeyError:
908        raise ValueError('Protocol message %s has no "%s" field.' %
909                         (message_descriptor.name, field_name))
910
911    if field in self._fields:
912      # To match the C++ implementation, we need to invalidate iterators
913      # for map fields when ClearField() happens.
914      if hasattr(self._fields[field], 'InvalidateIterators'):
915        self._fields[field].InvalidateIterators()
916
917      # Note:  If the field is a sub-message, its listener will still point
918      #   at us.  That's fine, because the worst than can happen is that it
919      #   will call _Modified() and invalidate our byte size.  Big deal.
920      del self._fields[field]
921
922      if self._oneofs.get(field.containing_oneof, None) is field:
923        del self._oneofs[field.containing_oneof]
924
925    # Always call _Modified() -- even if nothing was changed, this is
926    # a mutating method, and thus calling it should cause the field to become
927    # present in the parent message.
928    self._Modified()

Clears the contents of a given field.

Inside a oneof group, clears the field set. If the name neither refers to a defined field or oneof group, ValueError is raised.

Arguments:
  • field_name (str): The name of the field to check for presence.
Raises:
  • ValueError: if the field_name is not a member of this message.
def WhichOneof(self, oneof_name):
1406  def WhichOneof(self, oneof_name):
1407    """Returns the name of the currently set field inside a oneof, or None."""
1408    try:
1409      field = message_descriptor.oneofs_by_name[oneof_name]
1410    except KeyError:
1411      raise ValueError(
1412          'Protocol message has no oneof "%s" field.' % oneof_name)
1413
1414    nested_field = self._oneofs.get(field, None)
1415    if nested_field is not None and self.HasField(nested_field.name):
1416      return nested_field.name
1417    else:
1418      return None

Returns the name of the currently set field inside a oneof, or None.

def DiscardUnknownFields(self):
1438def _DiscardUnknownFields(self):
1439  self._unknown_fields = []
1440  for field, value in self.ListFields():
1441    if field.cpp_type == _FieldDescriptor.CPPTYPE_MESSAGE:
1442      if _IsMapField(field):
1443        if _IsMessageMapField(field):
1444          for key in value:
1445            value[key].DiscardUnknownFields()
1446      elif field.label == _FieldDescriptor.LABEL_REPEATED:
1447        for sub_message in value:
1448          sub_message.DiscardUnknownFields()
1449      else:
1450        value.DiscardUnknownFields()

Clears all fields in the UnknownFieldSet.

This operation is recursive for nested message.

def ByteSize(self):
1101  def ByteSize(self):
1102    if not self._cached_byte_size_dirty:
1103      return self._cached_byte_size
1104
1105    size = 0
1106    descriptor = self.DESCRIPTOR
1107    if descriptor._is_map_entry:
1108      # Fields of map entry should always be serialized.
1109      key_field = descriptor.fields_by_name['key']
1110      _MaybeAddEncoder(cls, key_field)
1111      size = key_field._sizer(self.key)
1112      value_field = descriptor.fields_by_name['value']
1113      _MaybeAddEncoder(cls, value_field)
1114      size += value_field._sizer(self.value)
1115    else:
1116      for field_descriptor, field_value in self.ListFields():
1117        _MaybeAddEncoder(cls, field_descriptor)
1118        size += field_descriptor._sizer(field_value)
1119      for tag_bytes, value_bytes in self._unknown_fields:
1120        size += len(tag_bytes) + len(value_bytes)
1121
1122    self._cached_byte_size = size
1123    self._cached_byte_size_dirty = False
1124    self._listener_for_children.dirty = False
1125    return size

Returns the serialized size of this message.

Recursively calls ByteSize() on all contained messages.

Returns:

int: The number of bytes required to serialize this message.

def FromString(s):
826  def FromString(s):
827    message = cls()
828    message.MergeFromString(s)
829    return message
SUPPORT_FIELD_NUMBER = 1
support
668  def getter(self):
669    field_value = self._fields.get(field)
670    if field_value is None:
671      # Construct a new object to represent this field.
672      field_value = field._default_constructor(self)
673
674      # Atomically check if another thread has preempted us and, if not, swap
675      # in the new object we just created.  If someone has preempted us, we
676      # take that object and discard ours.
677      # WARNING:  We are relying on setdefault() being atomic.  This is true
678      #   in CPython but we haven't investigated others.  This warning appears
679      #   in several other locations in this file.
680      field_value = self._fields.setdefault(field, field_value)
681    return field_value

Getter for support.

CYCLE_SIZES_FIELD_NUMBER = 2
cycle_sizes
668  def getter(self):
669    field_value = self._fields.get(field)
670    if field_value is None:
671      # Construct a new object to represent this field.
672      field_value = field._default_constructor(self)
673
674      # Atomically check if another thread has preempted us and, if not, swap
675      # in the new object we just created.  If someone has preempted us, we
676      # take that object and discard ours.
677      # WARNING:  We are relying on setdefault() being atomic.  This is true
678      #   in CPython but we haven't investigated others.  This warning appears
679      #   in several other locations in this file.
680      field_value = self._fields.setdefault(field, field_value)
681    return field_value

Getter for cycle_sizes.

def FindInitializationErrors(self):
1305  def FindInitializationErrors(self):
1306    """Finds required fields which are not initialized.
1307
1308    Returns:
1309      A list of strings.  Each string is a path to an uninitialized field from
1310      the top-level message, e.g. "foo.bar[5].baz".
1311    """
1312
1313    errors = []  # simplify things
1314
1315    for field in required_fields:
1316      if not self.HasField(field.name):
1317        errors.append(field.name)
1318
1319    for field, value in self.ListFields():
1320      if field.cpp_type == _FieldDescriptor.CPPTYPE_MESSAGE:
1321        if field.is_extension:
1322          name = '(%s)' % field.full_name
1323        else:
1324          name = field.name
1325
1326        if _IsMapField(field):
1327          if _IsMessageMapField(field):
1328            for key in value:
1329              element = value[key]
1330              prefix = '%s[%s].' % (name, key)
1331              sub_errors = element.FindInitializationErrors()
1332              errors += [prefix + error for error in sub_errors]
1333          else:
1334            # ScalarMaps can't have any initialization errors.
1335            pass
1336        elif field.label == _FieldDescriptor.LABEL_REPEATED:
1337          for i in range(len(value)):
1338            element = value[i]
1339            prefix = '%s[%d].' % (name, i)
1340            sub_errors = element.FindInitializationErrors()
1341            errors += [prefix + error for error in sub_errors]
1342        else:
1343          prefix = name + '.'
1344          sub_errors = value.FindInitializationErrors()
1345          errors += [prefix + error for error in sub_errors]
1346
1347    return errors

Finds required fields which are not initialized.

Returns:

A list of strings. Each string is a path to an uninitialized field from the top-level message, e.g. "foo.bar[5].baz".

class DenseMatrixProto(google.protobuf.message.Message):

Abstract base class for protocol messages.

Protocol message classes are almost always generated by the protocol compiler. These generated types subclass Message and implement the methods shown below.

DenseMatrixProto(**kwargs)
498  def init(self, **kwargs):
499    self._cached_byte_size = 0
500    self._cached_byte_size_dirty = len(kwargs) > 0
501    self._fields = {}
502    # Contains a mapping from oneof field descriptors to the descriptor
503    # of the currently set field in that oneof field.
504    self._oneofs = {}
505
506    # _unknown_fields is () when empty for efficiency, and will be turned into
507    # a list if fields are added.
508    self._unknown_fields = ()
509    self._is_present_in_parent = False
510    self._listener = message_listener_mod.NullMessageListener()
511    self._listener_for_children = _Listener(self)
512    for field_name, field_value in kwargs.items():
513      field = _GetFieldByName(message_descriptor, field_name)
514      if field is None:
515        raise TypeError('%s() got an unexpected keyword argument "%s"' %
516                        (message_descriptor.name, field_name))
517      if field_value is None:
518        # field=None is the same as no field at all.
519        continue
520      if field.label == _FieldDescriptor.LABEL_REPEATED:
521        field_copy = field._default_constructor(self)
522        if field.cpp_type == _FieldDescriptor.CPPTYPE_MESSAGE:  # Composite
523          if _IsMapField(field):
524            if _IsMessageMapField(field):
525              for key in field_value:
526                field_copy[key].MergeFrom(field_value[key])
527            else:
528              field_copy.update(field_value)
529          else:
530            for val in field_value:
531              if isinstance(val, dict):
532                field_copy.add(**val)
533              else:
534                field_copy.add().MergeFrom(val)
535        else:  # Scalar
536          if field.cpp_type == _FieldDescriptor.CPPTYPE_ENUM:
537            field_value = [_GetIntegerEnumValue(field.enum_type, val)
538                           for val in field_value]
539          field_copy.extend(field_value)
540        self._fields[field] = field_copy
541      elif field.cpp_type == _FieldDescriptor.CPPTYPE_MESSAGE:
542        field_copy = field._default_constructor(self)
543        new_val = None
544        if isinstance(field_value, message_mod.Message):
545          new_val = field_value
546        elif isinstance(field_value, dict):
547          if field.message_type.full_name == _StructFullTypeName:
548            field_copy.Clear()
549            if len(field_value) == 1 and 'fields' in field_value:
550              try:
551                field_copy.update(field_value)
552              except:
553                # Fall back to init normal message field
554                field_copy.Clear()
555                new_val = field.message_type._concrete_class(**field_value)
556            else:
557              field_copy.update(field_value)
558          else:
559            new_val = field.message_type._concrete_class(**field_value)
560        elif hasattr(field_copy, '_internal_assign'):
561          field_copy._internal_assign(field_value)
562        else:
563          raise TypeError(
564              'Message field {0}.{1} must be initialized with a '
565              'dict or instance of same class, got {2}.'.format(
566                  message_descriptor.name,
567                  field_name,
568                  type(field_value).__name__,
569              )
570          )
571
572        if new_val != None:
573          try:
574            field_copy.MergeFrom(new_val)
575          except TypeError:
576            _ReraiseTypeErrorWithFieldName(message_descriptor.name, field_name)
577        self._fields[field] = field_copy
578      else:
579        if field.cpp_type == _FieldDescriptor.CPPTYPE_ENUM:
580          field_value = _GetIntegerEnumValue(field.enum_type, field_value)
581        try:
582          setattr(self, field_name, field_value)
583        except TypeError:
584          _ReraiseTypeErrorWithFieldName(message_descriptor.name, field_name)
DESCRIPTOR = <google.protobuf.descriptor.Descriptor object>
def MergeFrom(self, msg):
1364  def MergeFrom(self, msg):
1365    if not isinstance(msg, cls):
1366      raise TypeError(
1367          'Parameter to MergeFrom() must be instance of same class: '
1368          'expected %s got %s.' % (_FullyQualifiedClassName(cls),
1369                                   _FullyQualifiedClassName(msg.__class__)))
1370
1371    assert msg is not self
1372    self._Modified()
1373
1374    fields = self._fields
1375
1376    for field, value in msg._fields.items():
1377      if field.label == LABEL_REPEATED:
1378        field_value = fields.get(field)
1379        if field_value is None:
1380          # Construct a new object to represent this field.
1381          field_value = field._default_constructor(self)
1382          fields[field] = field_value
1383        field_value.MergeFrom(value)
1384      elif field.cpp_type == CPPTYPE_MESSAGE:
1385        if value._is_present_in_parent:
1386          field_value = fields.get(field)
1387          if field_value is None:
1388            # Construct a new object to represent this field.
1389            field_value = field._default_constructor(self)
1390            fields[field] = field_value
1391          field_value.MergeFrom(value)
1392      else:
1393        self._fields[field] = value
1394        if field.containing_oneof:
1395          self._UpdateOneofState(field)
1396
1397    if msg._unknown_fields:
1398      if not self._unknown_fields:
1399        self._unknown_fields = []
1400      self._unknown_fields.extend(msg._unknown_fields)

Merges the contents of the specified message into current message.

This method merges the contents of the specified message into the current message. Singular fields that are set in the specified message overwrite the corresponding fields in the current message. Repeated fields are appended. Singular sub-messages and groups are recursively merged.

Arguments:
  • other_msg (Message): A message to merge into the current message.
def Clear(self):
1423def _Clear(self):
1424  # Clear fields.
1425  self._fields = {}
1426  self._unknown_fields = ()
1427
1428  self._oneofs = {}
1429  self._Modified()

Clears all data that was set in the message.

def SetInParent(self):
1489  def Modified(self):
1490    """Sets the _cached_byte_size_dirty bit to true,
1491    and propagates this to our listener iff this was a state change.
1492    """
1493
1494    # Note:  Some callers check _cached_byte_size_dirty before calling
1495    #   _Modified() as an extra optimization.  So, if this method is ever
1496    #   changed such that it does stuff even when _cached_byte_size_dirty is
1497    #   already true, the callers need to be updated.
1498    if not self._cached_byte_size_dirty:
1499      self._cached_byte_size_dirty = True
1500      self._listener_for_children.dirty = True
1501      self._is_present_in_parent = True
1502      self._listener.Modified()

Sets the _cached_byte_size_dirty bit to true, and propagates this to our listener iff this was a state change.

def IsInitialized(self, errors=None):
1265  def IsInitialized(self, errors=None):
1266    """Checks if all required fields of a message are set.
1267
1268    Args:
1269      errors:  A list which, if provided, will be populated with the field
1270               paths of all missing required fields.
1271
1272    Returns:
1273      True iff the specified message has all required fields set.
1274    """
1275
1276    # Performance is critical so we avoid HasField() and ListFields().
1277
1278    for field in required_fields:
1279      if (field not in self._fields or
1280          (field.cpp_type == _FieldDescriptor.CPPTYPE_MESSAGE and
1281           not self._fields[field]._is_present_in_parent)):
1282        if errors is not None:
1283          errors.extend(self.FindInitializationErrors())
1284        return False
1285
1286    for field, value in list(self._fields.items()):  # dict can change size!
1287      if field.cpp_type == _FieldDescriptor.CPPTYPE_MESSAGE:
1288        if field.label == _FieldDescriptor.LABEL_REPEATED:
1289          if (field.message_type._is_map_entry):
1290            continue
1291          for element in value:
1292            if not element.IsInitialized():
1293              if errors is not None:
1294                errors.extend(self.FindInitializationErrors())
1295              return False
1296        elif value._is_present_in_parent and not value.IsInitialized():
1297          if errors is not None:
1298            errors.extend(self.FindInitializationErrors())
1299          return False
1300
1301    return True

Checks if all required fields of a message are set.

Arguments:
  • errors: A list which, if provided, will be populated with the field paths of all missing required fields.
Returns:

True iff the specified message has all required fields set.

def MergeFromString(self, serialized):
1180  def MergeFromString(self, serialized):
1181    serialized = memoryview(serialized)
1182    length = len(serialized)
1183    try:
1184      if self._InternalParse(serialized, 0, length) != length:
1185        # The only reason _InternalParse would return early is if it
1186        # encountered an end-group tag.
1187        raise message_mod.DecodeError('Unexpected end-group tag.')
1188    except (IndexError, TypeError):
1189      # Now ord(buf[p:p+1]) == ord('') gets TypeError.
1190      raise message_mod.DecodeError('Truncated message.')
1191    except struct.error as e:
1192      raise message_mod.DecodeError(e)
1193    return length   # Return this for legacy reasons.

Merges serialized protocol buffer data into this message.

When we find a field in serialized that is already present in this message:

  • If it's a "repeated" field, we append to the end of our list.
  • Else, if it's a scalar, we overwrite our field.
  • Else, (it's a nonrepeated composite), we recursively merge into the existing composite.
Arguments:
  • serialized (bytes): Any object that allows us to call memoryview(serialized) to access a string of bytes using the buffer interface.
Returns:

int: The number of bytes read from serialized. For non-group messages, this will always be len(serialized), but for messages which are actually groups, this will generally be less than len(serialized), since we must stop when we reach an END_GROUP tag. Note that if we do stop because of an END_GROUP tag, the number of bytes returned does not include the bytes for the END_GROUP tag information.

Raises:
  • DecodeError: if the input cannot be parsed.
def SerializeToString(self, **kwargs):
1133  def SerializeToString(self, **kwargs):
1134    # Check if the message has all of its required fields set.
1135    if not self.IsInitialized():
1136      raise message_mod.EncodeError(
1137          'Message %s is missing required fields: %s' % (
1138          self.DESCRIPTOR.full_name, ','.join(self.FindInitializationErrors())))
1139    return self.SerializePartialToString(**kwargs)

Serializes the protocol message to a binary string.

Keyword Args:

deterministic (bool): If true, requests deterministic serialization of the protobuf, with predictable ordering of map keys.

Returns:

A binary string representation of the message if all of the required fields in the message are set (i.e. the message is initialized).

Raises:
def SerializePartialToString(self, **kwargs):
1146  def SerializePartialToString(self, **kwargs):
1147    out = BytesIO()
1148    self._InternalSerialize(out.write, **kwargs)
1149    return out.getvalue()

Serializes the protocol message to a binary string.

This method is similar to SerializeToString but doesn't check if the message is initialized.

Keyword Args:

deterministic (bool): If true, requests deterministic serialization of the protobuf, with predictable ordering of map keys.

Returns:

bytes: A serialized representation of the partial message.

def ListFields(self):
848  def ListFields(self):
849    all_fields = [item for item in self._fields.items() if _IsPresent(item)]
850    all_fields.sort(key = lambda item: item[0].number)
851    return all_fields

Returns a list of (FieldDescriptor, value) tuples for present fields.

A message field is non-empty if HasField() would return true. A singular primitive field is non-empty if HasField() would return true in proto2 or it is non zero in proto3. A repeated field is non-empty if it contains at least one element. The fields are ordered by field number.

Returns:

list[tuple(FieldDescriptor, value)]: field descriptors and values for all fields in the message which are not empty. The values vary by field type.

def HasField(self, field_name):
872  def HasField(self, field_name):
873    try:
874      field = hassable_fields[field_name]
875    except KeyError as exc:
876      raise ValueError('Protocol message %s has no non-repeated field "%s" '
877                       'nor has presence is not available for this field.' % (
878                           message_descriptor.full_name, field_name)) from exc
879
880    if isinstance(field, descriptor_mod.OneofDescriptor):
881      try:
882        return HasField(self, self._oneofs[field].name)
883      except KeyError:
884        return False
885    else:
886      if field.cpp_type == _FieldDescriptor.CPPTYPE_MESSAGE:
887        value = self._fields.get(field)
888        return value is not None and value._is_present_in_parent
889      else:
890        return field in self._fields

Checks if a certain field is set for the message.

For a oneof group, checks if any field inside is set. Note that if the field_name is not defined in the message descriptor, ValueError will be raised.

Arguments:
  • field_name (str): The name of the field to check for presence.
Returns:

bool: Whether a value has been set for the named field.

Raises:
  • ValueError: if the field_name is not a member of this message.
def ClearField(self, field_name):
897  def ClearField(self, field_name):
898    try:
899      field = message_descriptor.fields_by_name[field_name]
900    except KeyError:
901      try:
902        field = message_descriptor.oneofs_by_name[field_name]
903        if field in self._oneofs:
904          field = self._oneofs[field]
905        else:
906          return
907      except KeyError:
908        raise ValueError('Protocol message %s has no "%s" field.' %
909                         (message_descriptor.name, field_name))
910
911    if field in self._fields:
912      # To match the C++ implementation, we need to invalidate iterators
913      # for map fields when ClearField() happens.
914      if hasattr(self._fields[field], 'InvalidateIterators'):
915        self._fields[field].InvalidateIterators()
916
917      # Note:  If the field is a sub-message, its listener will still point
918      #   at us.  That's fine, because the worst than can happen is that it
919      #   will call _Modified() and invalidate our byte size.  Big deal.
920      del self._fields[field]
921
922      if self._oneofs.get(field.containing_oneof, None) is field:
923        del self._oneofs[field.containing_oneof]
924
925    # Always call _Modified() -- even if nothing was changed, this is
926    # a mutating method, and thus calling it should cause the field to become
927    # present in the parent message.
928    self._Modified()

Clears the contents of a given field.

Inside a oneof group, clears the field set. If the name neither refers to a defined field or oneof group, ValueError is raised.

Arguments:
  • field_name (str): The name of the field to check for presence.
Raises:
  • ValueError: if the field_name is not a member of this message.
def WhichOneof(self, oneof_name):
1406  def WhichOneof(self, oneof_name):
1407    """Returns the name of the currently set field inside a oneof, or None."""
1408    try:
1409      field = message_descriptor.oneofs_by_name[oneof_name]
1410    except KeyError:
1411      raise ValueError(
1412          'Protocol message has no oneof "%s" field.' % oneof_name)
1413
1414    nested_field = self._oneofs.get(field, None)
1415    if nested_field is not None and self.HasField(nested_field.name):
1416      return nested_field.name
1417    else:
1418      return None

Returns the name of the currently set field inside a oneof, or None.

def DiscardUnknownFields(self):
1438def _DiscardUnknownFields(self):
1439  self._unknown_fields = []
1440  for field, value in self.ListFields():
1441    if field.cpp_type == _FieldDescriptor.CPPTYPE_MESSAGE:
1442      if _IsMapField(field):
1443        if _IsMessageMapField(field):
1444          for key in value:
1445            value[key].DiscardUnknownFields()
1446      elif field.label == _FieldDescriptor.LABEL_REPEATED:
1447        for sub_message in value:
1448          sub_message.DiscardUnknownFields()
1449      else:
1450        value.DiscardUnknownFields()

Clears all fields in the UnknownFieldSet.

This operation is recursive for nested message.

def ByteSize(self):
1101  def ByteSize(self):
1102    if not self._cached_byte_size_dirty:
1103      return self._cached_byte_size
1104
1105    size = 0
1106    descriptor = self.DESCRIPTOR
1107    if descriptor._is_map_entry:
1108      # Fields of map entry should always be serialized.
1109      key_field = descriptor.fields_by_name['key']
1110      _MaybeAddEncoder(cls, key_field)
1111      size = key_field._sizer(self.key)
1112      value_field = descriptor.fields_by_name['value']
1113      _MaybeAddEncoder(cls, value_field)
1114      size += value_field._sizer(self.value)
1115    else:
1116      for field_descriptor, field_value in self.ListFields():
1117        _MaybeAddEncoder(cls, field_descriptor)
1118        size += field_descriptor._sizer(field_value)
1119      for tag_bytes, value_bytes in self._unknown_fields:
1120        size += len(tag_bytes) + len(value_bytes)
1121
1122    self._cached_byte_size = size
1123    self._cached_byte_size_dirty = False
1124    self._listener_for_children.dirty = False
1125    return size

Returns the serialized size of this message.

Recursively calls ByteSize() on all contained messages.

Returns:

int: The number of bytes required to serialize this message.

def FromString(s):
826  def FromString(s):
827    message = cls()
828    message.MergeFromString(s)
829    return message
NUM_ROWS_FIELD_NUMBER = 1
num_rows
711  def getter(self):
712    # TODO: This may be broken since there may not be
713    # default_value.  Combine with has_default_value somehow.
714    return self._fields.get(field, default_value)

Getter for num_rows.

NUM_COLS_FIELD_NUMBER = 2
num_cols
711  def getter(self):
712    # TODO: This may be broken since there may not be
713    # default_value.  Combine with has_default_value somehow.
714    return self._fields.get(field, default_value)

Getter for num_cols.

ENTRIES_FIELD_NUMBER = 3
entries
668  def getter(self):
669    field_value = self._fields.get(field)
670    if field_value is None:
671      # Construct a new object to represent this field.
672      field_value = field._default_constructor(self)
673
674      # Atomically check if another thread has preempted us and, if not, swap
675      # in the new object we just created.  If someone has preempted us, we
676      # take that object and discard ours.
677      # WARNING:  We are relying on setdefault() being atomic.  This is true
678      #   in CPython but we haven't investigated others.  This warning appears
679      #   in several other locations in this file.
680      field_value = self._fields.setdefault(field, field_value)
681    return field_value

Getter for entries.

def FindInitializationErrors(self):
1305  def FindInitializationErrors(self):
1306    """Finds required fields which are not initialized.
1307
1308    Returns:
1309      A list of strings.  Each string is a path to an uninitialized field from
1310      the top-level message, e.g. "foo.bar[5].baz".
1311    """
1312
1313    errors = []  # simplify things
1314
1315    for field in required_fields:
1316      if not self.HasField(field.name):
1317        errors.append(field.name)
1318
1319    for field, value in self.ListFields():
1320      if field.cpp_type == _FieldDescriptor.CPPTYPE_MESSAGE:
1321        if field.is_extension:
1322          name = '(%s)' % field.full_name
1323        else:
1324          name = field.name
1325
1326        if _IsMapField(field):
1327          if _IsMessageMapField(field):
1328            for key in value:
1329              element = value[key]
1330              prefix = '%s[%s].' % (name, key)
1331              sub_errors = element.FindInitializationErrors()
1332              errors += [prefix + error for error in sub_errors]
1333          else:
1334            # ScalarMaps can't have any initialization errors.
1335            pass
1336        elif field.label == _FieldDescriptor.LABEL_REPEATED:
1337          for i in range(len(value)):
1338            element = value[i]
1339            prefix = '%s[%d].' % (name, i)
1340            sub_errors = element.FindInitializationErrors()
1341            errors += [prefix + error for error in sub_errors]
1342        else:
1343          prefix = name + '.'
1344          sub_errors = value.FindInitializationErrors()
1345          errors += [prefix + error for error in sub_errors]
1346
1347    return errors

Finds required fields which are not initialized.

Returns:

A list of strings. Each string is a path to an uninitialized field from the top-level message, e.g. "foo.bar[5].baz".

class SymmetryProto(google.protobuf.message.Message):

Abstract base class for protocol messages.

Protocol message classes are almost always generated by the protocol compiler. These generated types subclass Message and implement the methods shown below.

SymmetryProto(**kwargs)
498  def init(self, **kwargs):
499    self._cached_byte_size = 0
500    self._cached_byte_size_dirty = len(kwargs) > 0
501    self._fields = {}
502    # Contains a mapping from oneof field descriptors to the descriptor
503    # of the currently set field in that oneof field.
504    self._oneofs = {}
505
506    # _unknown_fields is () when empty for efficiency, and will be turned into
507    # a list if fields are added.
508    self._unknown_fields = ()
509    self._is_present_in_parent = False
510    self._listener = message_listener_mod.NullMessageListener()
511    self._listener_for_children = _Listener(self)
512    for field_name, field_value in kwargs.items():
513      field = _GetFieldByName(message_descriptor, field_name)
514      if field is None:
515        raise TypeError('%s() got an unexpected keyword argument "%s"' %
516                        (message_descriptor.name, field_name))
517      if field_value is None:
518        # field=None is the same as no field at all.
519        continue
520      if field.label == _FieldDescriptor.LABEL_REPEATED:
521        field_copy = field._default_constructor(self)
522        if field.cpp_type == _FieldDescriptor.CPPTYPE_MESSAGE:  # Composite
523          if _IsMapField(field):
524            if _IsMessageMapField(field):
525              for key in field_value:
526                field_copy[key].MergeFrom(field_value[key])
527            else:
528              field_copy.update(field_value)
529          else:
530            for val in field_value:
531              if isinstance(val, dict):
532                field_copy.add(**val)
533              else:
534                field_copy.add().MergeFrom(val)
535        else:  # Scalar
536          if field.cpp_type == _FieldDescriptor.CPPTYPE_ENUM:
537            field_value = [_GetIntegerEnumValue(field.enum_type, val)
538                           for val in field_value]
539          field_copy.extend(field_value)
540        self._fields[field] = field_copy
541      elif field.cpp_type == _FieldDescriptor.CPPTYPE_MESSAGE:
542        field_copy = field._default_constructor(self)
543        new_val = None
544        if isinstance(field_value, message_mod.Message):
545          new_val = field_value
546        elif isinstance(field_value, dict):
547          if field.message_type.full_name == _StructFullTypeName:
548            field_copy.Clear()
549            if len(field_value) == 1 and 'fields' in field_value:
550              try:
551                field_copy.update(field_value)
552              except:
553                # Fall back to init normal message field
554                field_copy.Clear()
555                new_val = field.message_type._concrete_class(**field_value)
556            else:
557              field_copy.update(field_value)
558          else:
559            new_val = field.message_type._concrete_class(**field_value)
560        elif hasattr(field_copy, '_internal_assign'):
561          field_copy._internal_assign(field_value)
562        else:
563          raise TypeError(
564              'Message field {0}.{1} must be initialized with a '
565              'dict or instance of same class, got {2}.'.format(
566                  message_descriptor.name,
567                  field_name,
568                  type(field_value).__name__,
569              )
570          )
571
572        if new_val != None:
573          try:
574            field_copy.MergeFrom(new_val)
575          except TypeError:
576            _ReraiseTypeErrorWithFieldName(message_descriptor.name, field_name)
577        self._fields[field] = field_copy
578      else:
579        if field.cpp_type == _FieldDescriptor.CPPTYPE_ENUM:
580          field_value = _GetIntegerEnumValue(field.enum_type, field_value)
581        try:
582          setattr(self, field_name, field_value)
583        except TypeError:
584          _ReraiseTypeErrorWithFieldName(message_descriptor.name, field_name)
DESCRIPTOR = <google.protobuf.descriptor.Descriptor object>
def MergeFrom(self, msg):
1364  def MergeFrom(self, msg):
1365    if not isinstance(msg, cls):
1366      raise TypeError(
1367          'Parameter to MergeFrom() must be instance of same class: '
1368          'expected %s got %s.' % (_FullyQualifiedClassName(cls),
1369                                   _FullyQualifiedClassName(msg.__class__)))
1370
1371    assert msg is not self
1372    self._Modified()
1373
1374    fields = self._fields
1375
1376    for field, value in msg._fields.items():
1377      if field.label == LABEL_REPEATED:
1378        field_value = fields.get(field)
1379        if field_value is None:
1380          # Construct a new object to represent this field.
1381          field_value = field._default_constructor(self)
1382          fields[field] = field_value
1383        field_value.MergeFrom(value)
1384      elif field.cpp_type == CPPTYPE_MESSAGE:
1385        if value._is_present_in_parent:
1386          field_value = fields.get(field)
1387          if field_value is None:
1388            # Construct a new object to represent this field.
1389            field_value = field._default_constructor(self)
1390            fields[field] = field_value
1391          field_value.MergeFrom(value)
1392      else:
1393        self._fields[field] = value
1394        if field.containing_oneof:
1395          self._UpdateOneofState(field)
1396
1397    if msg._unknown_fields:
1398      if not self._unknown_fields:
1399        self._unknown_fields = []
1400      self._unknown_fields.extend(msg._unknown_fields)

Merges the contents of the specified message into current message.

This method merges the contents of the specified message into the current message. Singular fields that are set in the specified message overwrite the corresponding fields in the current message. Repeated fields are appended. Singular sub-messages and groups are recursively merged.

Arguments:
  • other_msg (Message): A message to merge into the current message.
def Clear(self):
1423def _Clear(self):
1424  # Clear fields.
1425  self._fields = {}
1426  self._unknown_fields = ()
1427
1428  self._oneofs = {}
1429  self._Modified()

Clears all data that was set in the message.

def SetInParent(self):
1489  def Modified(self):
1490    """Sets the _cached_byte_size_dirty bit to true,
1491    and propagates this to our listener iff this was a state change.
1492    """
1493
1494    # Note:  Some callers check _cached_byte_size_dirty before calling
1495    #   _Modified() as an extra optimization.  So, if this method is ever
1496    #   changed such that it does stuff even when _cached_byte_size_dirty is
1497    #   already true, the callers need to be updated.
1498    if not self._cached_byte_size_dirty:
1499      self._cached_byte_size_dirty = True
1500      self._listener_for_children.dirty = True
1501      self._is_present_in_parent = True
1502      self._listener.Modified()

Sets the _cached_byte_size_dirty bit to true, and propagates this to our listener iff this was a state change.

def IsInitialized(self, errors=None):
1265  def IsInitialized(self, errors=None):
1266    """Checks if all required fields of a message are set.
1267
1268    Args:
1269      errors:  A list which, if provided, will be populated with the field
1270               paths of all missing required fields.
1271
1272    Returns:
1273      True iff the specified message has all required fields set.
1274    """
1275
1276    # Performance is critical so we avoid HasField() and ListFields().
1277
1278    for field in required_fields:
1279      if (field not in self._fields or
1280          (field.cpp_type == _FieldDescriptor.CPPTYPE_MESSAGE and
1281           not self._fields[field]._is_present_in_parent)):
1282        if errors is not None:
1283          errors.extend(self.FindInitializationErrors())
1284        return False
1285
1286    for field, value in list(self._fields.items()):  # dict can change size!
1287      if field.cpp_type == _FieldDescriptor.CPPTYPE_MESSAGE:
1288        if field.label == _FieldDescriptor.LABEL_REPEATED:
1289          if (field.message_type._is_map_entry):
1290            continue
1291          for element in value:
1292            if not element.IsInitialized():
1293              if errors is not None:
1294                errors.extend(self.FindInitializationErrors())
1295              return False
1296        elif value._is_present_in_parent and not value.IsInitialized():
1297          if errors is not None:
1298            errors.extend(self.FindInitializationErrors())
1299          return False
1300
1301    return True

Checks if all required fields of a message are set.

Arguments:
  • errors: A list which, if provided, will be populated with the field paths of all missing required fields.
Returns:

True iff the specified message has all required fields set.

def MergeFromString(self, serialized):
1180  def MergeFromString(self, serialized):
1181    serialized = memoryview(serialized)
1182    length = len(serialized)
1183    try:
1184      if self._InternalParse(serialized, 0, length) != length:
1185        # The only reason _InternalParse would return early is if it
1186        # encountered an end-group tag.
1187        raise message_mod.DecodeError('Unexpected end-group tag.')
1188    except (IndexError, TypeError):
1189      # Now ord(buf[p:p+1]) == ord('') gets TypeError.
1190      raise message_mod.DecodeError('Truncated message.')
1191    except struct.error as e:
1192      raise message_mod.DecodeError(e)
1193    return length   # Return this for legacy reasons.

Merges serialized protocol buffer data into this message.

When we find a field in serialized that is already present in this message:

  • If it's a "repeated" field, we append to the end of our list.
  • Else, if it's a scalar, we overwrite our field.
  • Else, (it's a nonrepeated composite), we recursively merge into the existing composite.
Arguments:
  • serialized (bytes): Any object that allows us to call memoryview(serialized) to access a string of bytes using the buffer interface.
Returns:

int: The number of bytes read from serialized. For non-group messages, this will always be len(serialized), but for messages which are actually groups, this will generally be less than len(serialized), since we must stop when we reach an END_GROUP tag. Note that if we do stop because of an END_GROUP tag, the number of bytes returned does not include the bytes for the END_GROUP tag information.

Raises:
  • DecodeError: if the input cannot be parsed.
def SerializeToString(self, **kwargs):
1133  def SerializeToString(self, **kwargs):
1134    # Check if the message has all of its required fields set.
1135    if not self.IsInitialized():
1136      raise message_mod.EncodeError(
1137          'Message %s is missing required fields: %s' % (
1138          self.DESCRIPTOR.full_name, ','.join(self.FindInitializationErrors())))
1139    return self.SerializePartialToString(**kwargs)

Serializes the protocol message to a binary string.

Keyword Args:

deterministic (bool): If true, requests deterministic serialization of the protobuf, with predictable ordering of map keys.

Returns:

A binary string representation of the message if all of the required fields in the message are set (i.e. the message is initialized).

Raises:
def SerializePartialToString(self, **kwargs):
1146  def SerializePartialToString(self, **kwargs):
1147    out = BytesIO()
1148    self._InternalSerialize(out.write, **kwargs)
1149    return out.getvalue()

Serializes the protocol message to a binary string.

This method is similar to SerializeToString but doesn't check if the message is initialized.

Keyword Args:

deterministic (bool): If true, requests deterministic serialization of the protobuf, with predictable ordering of map keys.

Returns:

bytes: A serialized representation of the partial message.

def ListFields(self):
848  def ListFields(self):
849    all_fields = [item for item in self._fields.items() if _IsPresent(item)]
850    all_fields.sort(key = lambda item: item[0].number)
851    return all_fields

Returns a list of (FieldDescriptor, value) tuples for present fields.

A message field is non-empty if HasField() would return true. A singular primitive field is non-empty if HasField() would return true in proto2 or it is non zero in proto3. A repeated field is non-empty if it contains at least one element. The fields are ordered by field number.

Returns:

list[tuple(FieldDescriptor, value)]: field descriptors and values for all fields in the message which are not empty. The values vary by field type.

def HasField(self, field_name):
872  def HasField(self, field_name):
873    try:
874      field = hassable_fields[field_name]
875    except KeyError as exc:
876      raise ValueError('Protocol message %s has no non-repeated field "%s" '
877                       'nor has presence is not available for this field.' % (
878                           message_descriptor.full_name, field_name)) from exc
879
880    if isinstance(field, descriptor_mod.OneofDescriptor):
881      try:
882        return HasField(self, self._oneofs[field].name)
883      except KeyError:
884        return False
885    else:
886      if field.cpp_type == _FieldDescriptor.CPPTYPE_MESSAGE:
887        value = self._fields.get(field)
888        return value is not None and value._is_present_in_parent
889      else:
890        return field in self._fields

Checks if a certain field is set for the message.

For a oneof group, checks if any field inside is set. Note that if the field_name is not defined in the message descriptor, ValueError will be raised.

Arguments:
  • field_name (str): The name of the field to check for presence.
Returns:

bool: Whether a value has been set for the named field.

Raises:
  • ValueError: if the field_name is not a member of this message.
def ClearField(self, field_name):
897  def ClearField(self, field_name):
898    try:
899      field = message_descriptor.fields_by_name[field_name]
900    except KeyError:
901      try:
902        field = message_descriptor.oneofs_by_name[field_name]
903        if field in self._oneofs:
904          field = self._oneofs[field]
905        else:
906          return
907      except KeyError:
908        raise ValueError('Protocol message %s has no "%s" field.' %
909                         (message_descriptor.name, field_name))
910
911    if field in self._fields:
912      # To match the C++ implementation, we need to invalidate iterators
913      # for map fields when ClearField() happens.
914      if hasattr(self._fields[field], 'InvalidateIterators'):
915        self._fields[field].InvalidateIterators()
916
917      # Note:  If the field is a sub-message, its listener will still point
918      #   at us.  That's fine, because the worst than can happen is that it
919      #   will call _Modified() and invalidate our byte size.  Big deal.
920      del self._fields[field]
921
922      if self._oneofs.get(field.containing_oneof, None) is field:
923        del self._oneofs[field.containing_oneof]
924
925    # Always call _Modified() -- even if nothing was changed, this is
926    # a mutating method, and thus calling it should cause the field to become
927    # present in the parent message.
928    self._Modified()

Clears the contents of a given field.

Inside a oneof group, clears the field set. If the name neither refers to a defined field or oneof group, ValueError is raised.

Arguments:
  • field_name (str): The name of the field to check for presence.
Raises:
  • ValueError: if the field_name is not a member of this message.
def WhichOneof(self, oneof_name):
1406  def WhichOneof(self, oneof_name):
1407    """Returns the name of the currently set field inside a oneof, or None."""
1408    try:
1409      field = message_descriptor.oneofs_by_name[oneof_name]
1410    except KeyError:
1411      raise ValueError(
1412          'Protocol message has no oneof "%s" field.' % oneof_name)
1413
1414    nested_field = self._oneofs.get(field, None)
1415    if nested_field is not None and self.HasField(nested_field.name):
1416      return nested_field.name
1417    else:
1418      return None

Returns the name of the currently set field inside a oneof, or None.

def DiscardUnknownFields(self):
1438def _DiscardUnknownFields(self):
1439  self._unknown_fields = []
1440  for field, value in self.ListFields():
1441    if field.cpp_type == _FieldDescriptor.CPPTYPE_MESSAGE:
1442      if _IsMapField(field):
1443        if _IsMessageMapField(field):
1444          for key in value:
1445            value[key].DiscardUnknownFields()
1446      elif field.label == _FieldDescriptor.LABEL_REPEATED:
1447        for sub_message in value:
1448          sub_message.DiscardUnknownFields()
1449      else:
1450        value.DiscardUnknownFields()

Clears all fields in the UnknownFieldSet.

This operation is recursive for nested message.

def ByteSize(self):
1101  def ByteSize(self):
1102    if not self._cached_byte_size_dirty:
1103      return self._cached_byte_size
1104
1105    size = 0
1106    descriptor = self.DESCRIPTOR
1107    if descriptor._is_map_entry:
1108      # Fields of map entry should always be serialized.
1109      key_field = descriptor.fields_by_name['key']
1110      _MaybeAddEncoder(cls, key_field)
1111      size = key_field._sizer(self.key)
1112      value_field = descriptor.fields_by_name['value']
1113      _MaybeAddEncoder(cls, value_field)
1114      size += value_field._sizer(self.value)
1115    else:
1116      for field_descriptor, field_value in self.ListFields():
1117        _MaybeAddEncoder(cls, field_descriptor)
1118        size += field_descriptor._sizer(field_value)
1119      for tag_bytes, value_bytes in self._unknown_fields:
1120        size += len(tag_bytes) + len(value_bytes)
1121
1122    self._cached_byte_size = size
1123    self._cached_byte_size_dirty = False
1124    self._listener_for_children.dirty = False
1125    return size

Returns the serialized size of this message.

Recursively calls ByteSize() on all contained messages.

Returns:

int: The number of bytes required to serialize this message.

def FromString(s):
826  def FromString(s):
827    message = cls()
828    message.MergeFromString(s)
829    return message
PERMUTATIONS_FIELD_NUMBER = 1
permutations
668  def getter(self):
669    field_value = self._fields.get(field)
670    if field_value is None:
671      # Construct a new object to represent this field.
672      field_value = field._default_constructor(self)
673
674      # Atomically check if another thread has preempted us and, if not, swap
675      # in the new object we just created.  If someone has preempted us, we
676      # take that object and discard ours.
677      # WARNING:  We are relying on setdefault() being atomic.  This is true
678      #   in CPython but we haven't investigated others.  This warning appears
679      #   in several other locations in this file.
680      field_value = self._fields.setdefault(field, field_value)
681    return field_value

Getter for permutations.

ORBITOPES_FIELD_NUMBER = 2
orbitopes
668  def getter(self):
669    field_value = self._fields.get(field)
670    if field_value is None:
671      # Construct a new object to represent this field.
672      field_value = field._default_constructor(self)
673
674      # Atomically check if another thread has preempted us and, if not, swap
675      # in the new object we just created.  If someone has preempted us, we
676      # take that object and discard ours.
677      # WARNING:  We are relying on setdefault() being atomic.  This is true
678      #   in CPython but we haven't investigated others.  This warning appears
679      #   in several other locations in this file.
680      field_value = self._fields.setdefault(field, field_value)
681    return field_value

Getter for orbitopes.

def FindInitializationErrors(self):
1305  def FindInitializationErrors(self):
1306    """Finds required fields which are not initialized.
1307
1308    Returns:
1309      A list of strings.  Each string is a path to an uninitialized field from
1310      the top-level message, e.g. "foo.bar[5].baz".
1311    """
1312
1313    errors = []  # simplify things
1314
1315    for field in required_fields:
1316      if not self.HasField(field.name):
1317        errors.append(field.name)
1318
1319    for field, value in self.ListFields():
1320      if field.cpp_type == _FieldDescriptor.CPPTYPE_MESSAGE:
1321        if field.is_extension:
1322          name = '(%s)' % field.full_name
1323        else:
1324          name = field.name
1325
1326        if _IsMapField(field):
1327          if _IsMessageMapField(field):
1328            for key in value:
1329              element = value[key]
1330              prefix = '%s[%s].' % (name, key)
1331              sub_errors = element.FindInitializationErrors()
1332              errors += [prefix + error for error in sub_errors]
1333          else:
1334            # ScalarMaps can't have any initialization errors.
1335            pass
1336        elif field.label == _FieldDescriptor.LABEL_REPEATED:
1337          for i in range(len(value)):
1338            element = value[i]
1339            prefix = '%s[%d].' % (name, i)
1340            sub_errors = element.FindInitializationErrors()
1341            errors += [prefix + error for error in sub_errors]
1342        else:
1343          prefix = name + '.'
1344          sub_errors = value.FindInitializationErrors()
1345          errors += [prefix + error for error in sub_errors]
1346
1347    return errors

Finds required fields which are not initialized.

Returns:

A list of strings. Each string is a path to an uninitialized field from the top-level message, e.g. "foo.bar[5].baz".

class CpModelProto(google.protobuf.message.Message):

Abstract base class for protocol messages.

Protocol message classes are almost always generated by the protocol compiler. These generated types subclass Message and implement the methods shown below.

CpModelProto(**kwargs)
498  def init(self, **kwargs):
499    self._cached_byte_size = 0
500    self._cached_byte_size_dirty = len(kwargs) > 0
501    self._fields = {}
502    # Contains a mapping from oneof field descriptors to the descriptor
503    # of the currently set field in that oneof field.
504    self._oneofs = {}
505
506    # _unknown_fields is () when empty for efficiency, and will be turned into
507    # a list if fields are added.
508    self._unknown_fields = ()
509    self._is_present_in_parent = False
510    self._listener = message_listener_mod.NullMessageListener()
511    self._listener_for_children = _Listener(self)
512    for field_name, field_value in kwargs.items():
513      field = _GetFieldByName(message_descriptor, field_name)
514      if field is None:
515        raise TypeError('%s() got an unexpected keyword argument "%s"' %
516                        (message_descriptor.name, field_name))
517      if field_value is None:
518        # field=None is the same as no field at all.
519        continue
520      if field.label == _FieldDescriptor.LABEL_REPEATED:
521        field_copy = field._default_constructor(self)
522        if field.cpp_type == _FieldDescriptor.CPPTYPE_MESSAGE:  # Composite
523          if _IsMapField(field):
524            if _IsMessageMapField(field):
525              for key in field_value:
526                field_copy[key].MergeFrom(field_value[key])
527            else:
528              field_copy.update(field_value)
529          else:
530            for val in field_value:
531              if isinstance(val, dict):
532                field_copy.add(**val)
533              else:
534                field_copy.add().MergeFrom(val)
535        else:  # Scalar
536          if field.cpp_type == _FieldDescriptor.CPPTYPE_ENUM:
537            field_value = [_GetIntegerEnumValue(field.enum_type, val)
538                           for val in field_value]
539          field_copy.extend(field_value)
540        self._fields[field] = field_copy
541      elif field.cpp_type == _FieldDescriptor.CPPTYPE_MESSAGE:
542        field_copy = field._default_constructor(self)
543        new_val = None
544        if isinstance(field_value, message_mod.Message):
545          new_val = field_value
546        elif isinstance(field_value, dict):
547          if field.message_type.full_name == _StructFullTypeName:
548            field_copy.Clear()
549            if len(field_value) == 1 and 'fields' in field_value:
550              try:
551                field_copy.update(field_value)
552              except:
553                # Fall back to init normal message field
554                field_copy.Clear()
555                new_val = field.message_type._concrete_class(**field_value)
556            else:
557              field_copy.update(field_value)
558          else:
559            new_val = field.message_type._concrete_class(**field_value)
560        elif hasattr(field_copy, '_internal_assign'):
561          field_copy._internal_assign(field_value)
562        else:
563          raise TypeError(
564              'Message field {0}.{1} must be initialized with a '
565              'dict or instance of same class, got {2}.'.format(
566                  message_descriptor.name,
567                  field_name,
568                  type(field_value).__name__,
569              )
570          )
571
572        if new_val != None:
573          try:
574            field_copy.MergeFrom(new_val)
575          except TypeError:
576            _ReraiseTypeErrorWithFieldName(message_descriptor.name, field_name)
577        self._fields[field] = field_copy
578      else:
579        if field.cpp_type == _FieldDescriptor.CPPTYPE_ENUM:
580          field_value = _GetIntegerEnumValue(field.enum_type, field_value)
581        try:
582          setattr(self, field_name, field_value)
583        except TypeError:
584          _ReraiseTypeErrorWithFieldName(message_descriptor.name, field_name)
DESCRIPTOR = <google.protobuf.descriptor.Descriptor object>
def MergeFrom(self, msg):
1364  def MergeFrom(self, msg):
1365    if not isinstance(msg, cls):
1366      raise TypeError(
1367          'Parameter to MergeFrom() must be instance of same class: '
1368          'expected %s got %s.' % (_FullyQualifiedClassName(cls),
1369                                   _FullyQualifiedClassName(msg.__class__)))
1370
1371    assert msg is not self
1372    self._Modified()
1373
1374    fields = self._fields
1375
1376    for field, value in msg._fields.items():
1377      if field.label == LABEL_REPEATED:
1378        field_value = fields.get(field)
1379        if field_value is None:
1380          # Construct a new object to represent this field.
1381          field_value = field._default_constructor(self)
1382          fields[field] = field_value
1383        field_value.MergeFrom(value)
1384      elif field.cpp_type == CPPTYPE_MESSAGE:
1385        if value._is_present_in_parent:
1386          field_value = fields.get(field)
1387          if field_value is None:
1388            # Construct a new object to represent this field.
1389            field_value = field._default_constructor(self)
1390            fields[field] = field_value
1391          field_value.MergeFrom(value)
1392      else:
1393        self._fields[field] = value
1394        if field.containing_oneof:
1395          self._UpdateOneofState(field)
1396
1397    if msg._unknown_fields:
1398      if not self._unknown_fields:
1399        self._unknown_fields = []
1400      self._unknown_fields.extend(msg._unknown_fields)

Merges the contents of the specified message into current message.

This method merges the contents of the specified message into the current message. Singular fields that are set in the specified message overwrite the corresponding fields in the current message. Repeated fields are appended. Singular sub-messages and groups are recursively merged.

Arguments:
  • other_msg (Message): A message to merge into the current message.
def Clear(self):
1423def _Clear(self):
1424  # Clear fields.
1425  self._fields = {}
1426  self._unknown_fields = ()
1427
1428  self._oneofs = {}
1429  self._Modified()

Clears all data that was set in the message.

def SetInParent(self):
1489  def Modified(self):
1490    """Sets the _cached_byte_size_dirty bit to true,
1491    and propagates this to our listener iff this was a state change.
1492    """
1493
1494    # Note:  Some callers check _cached_byte_size_dirty before calling
1495    #   _Modified() as an extra optimization.  So, if this method is ever
1496    #   changed such that it does stuff even when _cached_byte_size_dirty is
1497    #   already true, the callers need to be updated.
1498    if not self._cached_byte_size_dirty:
1499      self._cached_byte_size_dirty = True
1500      self._listener_for_children.dirty = True
1501      self._is_present_in_parent = True
1502      self._listener.Modified()

Sets the _cached_byte_size_dirty bit to true, and propagates this to our listener iff this was a state change.

def IsInitialized(self, errors=None):
1265  def IsInitialized(self, errors=None):
1266    """Checks if all required fields of a message are set.
1267
1268    Args:
1269      errors:  A list which, if provided, will be populated with the field
1270               paths of all missing required fields.
1271
1272    Returns:
1273      True iff the specified message has all required fields set.
1274    """
1275
1276    # Performance is critical so we avoid HasField() and ListFields().
1277
1278    for field in required_fields:
1279      if (field not in self._fields or
1280          (field.cpp_type == _FieldDescriptor.CPPTYPE_MESSAGE and
1281           not self._fields[field]._is_present_in_parent)):
1282        if errors is not None:
1283          errors.extend(self.FindInitializationErrors())
1284        return False
1285
1286    for field, value in list(self._fields.items()):  # dict can change size!
1287      if field.cpp_type == _FieldDescriptor.CPPTYPE_MESSAGE:
1288        if field.label == _FieldDescriptor.LABEL_REPEATED:
1289          if (field.message_type._is_map_entry):
1290            continue
1291          for element in value:
1292            if not element.IsInitialized():
1293              if errors is not None:
1294                errors.extend(self.FindInitializationErrors())
1295              return False
1296        elif value._is_present_in_parent and not value.IsInitialized():
1297          if errors is not None:
1298            errors.extend(self.FindInitializationErrors())
1299          return False
1300
1301    return True

Checks if all required fields of a message are set.

Arguments:
  • errors: A list which, if provided, will be populated with the field paths of all missing required fields.
Returns:

True iff the specified message has all required fields set.

def MergeFromString(self, serialized):
1180  def MergeFromString(self, serialized):
1181    serialized = memoryview(serialized)
1182    length = len(serialized)
1183    try:
1184      if self._InternalParse(serialized, 0, length) != length:
1185        # The only reason _InternalParse would return early is if it
1186        # encountered an end-group tag.
1187        raise message_mod.DecodeError('Unexpected end-group tag.')
1188    except (IndexError, TypeError):
1189      # Now ord(buf[p:p+1]) == ord('') gets TypeError.
1190      raise message_mod.DecodeError('Truncated message.')
1191    except struct.error as e:
1192      raise message_mod.DecodeError(e)
1193    return length   # Return this for legacy reasons.

Merges serialized protocol buffer data into this message.

When we find a field in serialized that is already present in this message:

  • If it's a "repeated" field, we append to the end of our list.
  • Else, if it's a scalar, we overwrite our field.
  • Else, (it's a nonrepeated composite), we recursively merge into the existing composite.
Arguments:
  • serialized (bytes): Any object that allows us to call memoryview(serialized) to access a string of bytes using the buffer interface.
Returns:

int: The number of bytes read from serialized. For non-group messages, this will always be len(serialized), but for messages which are actually groups, this will generally be less than len(serialized), since we must stop when we reach an END_GROUP tag. Note that if we do stop because of an END_GROUP tag, the number of bytes returned does not include the bytes for the END_GROUP tag information.

Raises:
  • DecodeError: if the input cannot be parsed.
def SerializeToString(self, **kwargs):
1133  def SerializeToString(self, **kwargs):
1134    # Check if the message has all of its required fields set.
1135    if not self.IsInitialized():
1136      raise message_mod.EncodeError(
1137          'Message %s is missing required fields: %s' % (
1138          self.DESCRIPTOR.full_name, ','.join(self.FindInitializationErrors())))
1139    return self.SerializePartialToString(**kwargs)

Serializes the protocol message to a binary string.

Keyword Args:

deterministic (bool): If true, requests deterministic serialization of the protobuf, with predictable ordering of map keys.

Returns:

A binary string representation of the message if all of the required fields in the message are set (i.e. the message is initialized).

Raises:
def SerializePartialToString(self, **kwargs):
1146  def SerializePartialToString(self, **kwargs):
1147    out = BytesIO()
1148    self._InternalSerialize(out.write, **kwargs)
1149    return out.getvalue()

Serializes the protocol message to a binary string.

This method is similar to SerializeToString but doesn't check if the message is initialized.

Keyword Args:

deterministic (bool): If true, requests deterministic serialization of the protobuf, with predictable ordering of map keys.

Returns:

bytes: A serialized representation of the partial message.

def ListFields(self):
848  def ListFields(self):
849    all_fields = [item for item in self._fields.items() if _IsPresent(item)]
850    all_fields.sort(key = lambda item: item[0].number)
851    return all_fields

Returns a list of (FieldDescriptor, value) tuples for present fields.

A message field is non-empty if HasField() would return true. A singular primitive field is non-empty if HasField() would return true in proto2 or it is non zero in proto3. A repeated field is non-empty if it contains at least one element. The fields are ordered by field number.

Returns:

list[tuple(FieldDescriptor, value)]: field descriptors and values for all fields in the message which are not empty. The values vary by field type.

def HasField(self, field_name):
872  def HasField(self, field_name):
873    try:
874      field = hassable_fields[field_name]
875    except KeyError as exc:
876      raise ValueError('Protocol message %s has no non-repeated field "%s" '
877                       'nor has presence is not available for this field.' % (
878                           message_descriptor.full_name, field_name)) from exc
879
880    if isinstance(field, descriptor_mod.OneofDescriptor):
881      try:
882        return HasField(self, self._oneofs[field].name)
883      except KeyError:
884        return False
885    else:
886      if field.cpp_type == _FieldDescriptor.CPPTYPE_MESSAGE:
887        value = self._fields.get(field)
888        return value is not None and value._is_present_in_parent
889      else:
890        return field in self._fields

Checks if a certain field is set for the message.

For a oneof group, checks if any field inside is set. Note that if the field_name is not defined in the message descriptor, ValueError will be raised.

Arguments:
  • field_name (str): The name of the field to check for presence.
Returns:

bool: Whether a value has been set for the named field.

Raises:
  • ValueError: if the field_name is not a member of this message.
def ClearField(self, field_name):
897  def ClearField(self, field_name):
898    try:
899      field = message_descriptor.fields_by_name[field_name]
900    except KeyError:
901      try:
902        field = message_descriptor.oneofs_by_name[field_name]
903        if field in self._oneofs:
904          field = self._oneofs[field]
905        else:
906          return
907      except KeyError:
908        raise ValueError('Protocol message %s has no "%s" field.' %
909                         (message_descriptor.name, field_name))
910
911    if field in self._fields:
912      # To match the C++ implementation, we need to invalidate iterators
913      # for map fields when ClearField() happens.
914      if hasattr(self._fields[field], 'InvalidateIterators'):
915        self._fields[field].InvalidateIterators()
916
917      # Note:  If the field is a sub-message, its listener will still point
918      #   at us.  That's fine, because the worst than can happen is that it
919      #   will call _Modified() and invalidate our byte size.  Big deal.
920      del self._fields[field]
921
922      if self._oneofs.get(field.containing_oneof, None) is field:
923        del self._oneofs[field.containing_oneof]
924
925    # Always call _Modified() -- even if nothing was changed, this is
926    # a mutating method, and thus calling it should cause the field to become
927    # present in the parent message.
928    self._Modified()

Clears the contents of a given field.

Inside a oneof group, clears the field set. If the name neither refers to a defined field or oneof group, ValueError is raised.

Arguments:
  • field_name (str): The name of the field to check for presence.
Raises:
  • ValueError: if the field_name is not a member of this message.
def WhichOneof(self, oneof_name):
1406  def WhichOneof(self, oneof_name):
1407    """Returns the name of the currently set field inside a oneof, or None."""
1408    try:
1409      field = message_descriptor.oneofs_by_name[oneof_name]
1410    except KeyError:
1411      raise ValueError(
1412          'Protocol message has no oneof "%s" field.' % oneof_name)
1413
1414    nested_field = self._oneofs.get(field, None)
1415    if nested_field is not None and self.HasField(nested_field.name):
1416      return nested_field.name
1417    else:
1418      return None

Returns the name of the currently set field inside a oneof, or None.

def DiscardUnknownFields(self):
1438def _DiscardUnknownFields(self):
1439  self._unknown_fields = []
1440  for field, value in self.ListFields():
1441    if field.cpp_type == _FieldDescriptor.CPPTYPE_MESSAGE:
1442      if _IsMapField(field):
1443        if _IsMessageMapField(field):
1444          for key in value:
1445            value[key].DiscardUnknownFields()
1446      elif field.label == _FieldDescriptor.LABEL_REPEATED:
1447        for sub_message in value:
1448          sub_message.DiscardUnknownFields()
1449      else:
1450        value.DiscardUnknownFields()

Clears all fields in the UnknownFieldSet.

This operation is recursive for nested message.

def ByteSize(self):
1101  def ByteSize(self):
1102    if not self._cached_byte_size_dirty:
1103      return self._cached_byte_size
1104
1105    size = 0
1106    descriptor = self.DESCRIPTOR
1107    if descriptor._is_map_entry:
1108      # Fields of map entry should always be serialized.
1109      key_field = descriptor.fields_by_name['key']
1110      _MaybeAddEncoder(cls, key_field)
1111      size = key_field._sizer(self.key)
1112      value_field = descriptor.fields_by_name['value']
1113      _MaybeAddEncoder(cls, value_field)
1114      size += value_field._sizer(self.value)
1115    else:
1116      for field_descriptor, field_value in self.ListFields():
1117        _MaybeAddEncoder(cls, field_descriptor)
1118        size += field_descriptor._sizer(field_value)
1119      for tag_bytes, value_bytes in self._unknown_fields:
1120        size += len(tag_bytes) + len(value_bytes)
1121
1122    self._cached_byte_size = size
1123    self._cached_byte_size_dirty = False
1124    self._listener_for_children.dirty = False
1125    return size

Returns the serialized size of this message.

Recursively calls ByteSize() on all contained messages.

Returns:

int: The number of bytes required to serialize this message.

def FromString(s):
826  def FromString(s):
827    message = cls()
828    message.MergeFromString(s)
829    return message
NAME_FIELD_NUMBER = 1
name
711  def getter(self):
712    # TODO: This may be broken since there may not be
713    # default_value.  Combine with has_default_value somehow.
714    return self._fields.get(field, default_value)

Getter for name.

VARIABLES_FIELD_NUMBER = 2
variables
668  def getter(self):
669    field_value = self._fields.get(field)
670    if field_value is None:
671      # Construct a new object to represent this field.
672      field_value = field._default_constructor(self)
673
674      # Atomically check if another thread has preempted us and, if not, swap
675      # in the new object we just created.  If someone has preempted us, we
676      # take that object and discard ours.
677      # WARNING:  We are relying on setdefault() being atomic.  This is true
678      #   in CPython but we haven't investigated others.  This warning appears
679      #   in several other locations in this file.
680      field_value = self._fields.setdefault(field, field_value)
681    return field_value

Getter for variables.

CONSTRAINTS_FIELD_NUMBER = 3
constraints
668  def getter(self):
669    field_value = self._fields.get(field)
670    if field_value is None:
671      # Construct a new object to represent this field.
672      field_value = field._default_constructor(self)
673
674      # Atomically check if another thread has preempted us and, if not, swap
675      # in the new object we just created.  If someone has preempted us, we
676      # take that object and discard ours.
677      # WARNING:  We are relying on setdefault() being atomic.  This is true
678      #   in CPython but we haven't investigated others.  This warning appears
679      #   in several other locations in this file.
680      field_value = self._fields.setdefault(field, field_value)
681    return field_value

Getter for constraints.

OBJECTIVE_FIELD_NUMBER = 4
objective
767  def getter(self):
768    field_value = self._fields.get(field)
769    if field_value is None:
770      # Construct a new object to represent this field.
771      field_value = field._default_constructor(self)
772
773      # Atomically check if another thread has preempted us and, if not, swap
774      # in the new object we just created.  If someone has preempted us, we
775      # take that object and discard ours.
776      # WARNING:  We are relying on setdefault() being atomic.  This is true
777      #   in CPython but we haven't investigated others.  This warning appears
778      #   in several other locations in this file.
779      field_value = self._fields.setdefault(field, field_value)
780    return field_value

Getter for objective.

FLOATING_POINT_OBJECTIVE_FIELD_NUMBER = 9
floating_point_objective
767  def getter(self):
768    field_value = self._fields.get(field)
769    if field_value is None:
770      # Construct a new object to represent this field.
771      field_value = field._default_constructor(self)
772
773      # Atomically check if another thread has preempted us and, if not, swap
774      # in the new object we just created.  If someone has preempted us, we
775      # take that object and discard ours.
776      # WARNING:  We are relying on setdefault() being atomic.  This is true
777      #   in CPython but we haven't investigated others.  This warning appears
778      #   in several other locations in this file.
779      field_value = self._fields.setdefault(field, field_value)
780    return field_value

Getter for floating_point_objective.

SEARCH_STRATEGY_FIELD_NUMBER = 5
search_strategy
668  def getter(self):
669    field_value = self._fields.get(field)
670    if field_value is None:
671      # Construct a new object to represent this field.
672      field_value = field._default_constructor(self)
673
674      # Atomically check if another thread has preempted us and, if not, swap
675      # in the new object we just created.  If someone has preempted us, we
676      # take that object and discard ours.
677      # WARNING:  We are relying on setdefault() being atomic.  This is true
678      #   in CPython but we haven't investigated others.  This warning appears
679      #   in several other locations in this file.
680      field_value = self._fields.setdefault(field, field_value)
681    return field_value

Getter for search_strategy.

SOLUTION_HINT_FIELD_NUMBER = 6
solution_hint
767  def getter(self):
768    field_value = self._fields.get(field)
769    if field_value is None:
770      # Construct a new object to represent this field.
771      field_value = field._default_constructor(self)
772
773      # Atomically check if another thread has preempted us and, if not, swap
774      # in the new object we just created.  If someone has preempted us, we
775      # take that object and discard ours.
776      # WARNING:  We are relying on setdefault() being atomic.  This is true
777      #   in CPython but we haven't investigated others.  This warning appears
778      #   in several other locations in this file.
779      field_value = self._fields.setdefault(field, field_value)
780    return field_value

Getter for solution_hint.

ASSUMPTIONS_FIELD_NUMBER = 7
assumptions
668  def getter(self):
669    field_value = self._fields.get(field)
670    if field_value is None:
671      # Construct a new object to represent this field.
672      field_value = field._default_constructor(self)
673
674      # Atomically check if another thread has preempted us and, if not, swap
675      # in the new object we just created.  If someone has preempted us, we
676      # take that object and discard ours.
677      # WARNING:  We are relying on setdefault() being atomic.  This is true
678      #   in CPython but we haven't investigated others.  This warning appears
679      #   in several other locations in this file.
680      field_value = self._fields.setdefault(field, field_value)
681    return field_value

Getter for assumptions.

SYMMETRY_FIELD_NUMBER = 8
symmetry
767  def getter(self):
768    field_value = self._fields.get(field)
769    if field_value is None:
770      # Construct a new object to represent this field.
771      field_value = field._default_constructor(self)
772
773      # Atomically check if another thread has preempted us and, if not, swap
774      # in the new object we just created.  If someone has preempted us, we
775      # take that object and discard ours.
776      # WARNING:  We are relying on setdefault() being atomic.  This is true
777      #   in CPython but we haven't investigated others.  This warning appears
778      #   in several other locations in this file.
779      field_value = self._fields.setdefault(field, field_value)
780    return field_value

Getter for symmetry.

def FindInitializationErrors(self):
1305  def FindInitializationErrors(self):
1306    """Finds required fields which are not initialized.
1307
1308    Returns:
1309      A list of strings.  Each string is a path to an uninitialized field from
1310      the top-level message, e.g. "foo.bar[5].baz".
1311    """
1312
1313    errors = []  # simplify things
1314
1315    for field in required_fields:
1316      if not self.HasField(field.name):
1317        errors.append(field.name)
1318
1319    for field, value in self.ListFields():
1320      if field.cpp_type == _FieldDescriptor.CPPTYPE_MESSAGE:
1321        if field.is_extension:
1322          name = '(%s)' % field.full_name
1323        else:
1324          name = field.name
1325
1326        if _IsMapField(field):
1327          if _IsMessageMapField(field):
1328            for key in value:
1329              element = value[key]
1330              prefix = '%s[%s].' % (name, key)
1331              sub_errors = element.FindInitializationErrors()
1332              errors += [prefix + error for error in sub_errors]
1333          else:
1334            # ScalarMaps can't have any initialization errors.
1335            pass
1336        elif field.label == _FieldDescriptor.LABEL_REPEATED:
1337          for i in range(len(value)):
1338            element = value[i]
1339            prefix = '%s[%d].' % (name, i)
1340            sub_errors = element.FindInitializationErrors()
1341            errors += [prefix + error for error in sub_errors]
1342        else:
1343          prefix = name + '.'
1344          sub_errors = value.FindInitializationErrors()
1345          errors += [prefix + error for error in sub_errors]
1346
1347    return errors

Finds required fields which are not initialized.

Returns:

A list of strings. Each string is a path to an uninitialized field from the top-level message, e.g. "foo.bar[5].baz".

class CpSolverSolution(google.protobuf.message.Message):

Abstract base class for protocol messages.

Protocol message classes are almost always generated by the protocol compiler. These generated types subclass Message and implement the methods shown below.

CpSolverSolution(**kwargs)
498  def init(self, **kwargs):
499    self._cached_byte_size = 0
500    self._cached_byte_size_dirty = len(kwargs) > 0
501    self._fields = {}
502    # Contains a mapping from oneof field descriptors to the descriptor
503    # of the currently set field in that oneof field.
504    self._oneofs = {}
505
506    # _unknown_fields is () when empty for efficiency, and will be turned into
507    # a list if fields are added.
508    self._unknown_fields = ()
509    self._is_present_in_parent = False
510    self._listener = message_listener_mod.NullMessageListener()
511    self._listener_for_children = _Listener(self)
512    for field_name, field_value in kwargs.items():
513      field = _GetFieldByName(message_descriptor, field_name)
514      if field is None:
515        raise TypeError('%s() got an unexpected keyword argument "%s"' %
516                        (message_descriptor.name, field_name))
517      if field_value is None:
518        # field=None is the same as no field at all.
519        continue
520      if field.label == _FieldDescriptor.LABEL_REPEATED:
521        field_copy = field._default_constructor(self)
522        if field.cpp_type == _FieldDescriptor.CPPTYPE_MESSAGE:  # Composite
523          if _IsMapField(field):
524            if _IsMessageMapField(field):
525              for key in field_value:
526                field_copy[key].MergeFrom(field_value[key])
527            else:
528              field_copy.update(field_value)
529          else:
530            for val in field_value:
531              if isinstance(val, dict):
532                field_copy.add(**val)
533              else:
534                field_copy.add().MergeFrom(val)
535        else:  # Scalar
536          if field.cpp_type == _FieldDescriptor.CPPTYPE_ENUM:
537            field_value = [_GetIntegerEnumValue(field.enum_type, val)
538                           for val in field_value]
539          field_copy.extend(field_value)
540        self._fields[field] = field_copy
541      elif field.cpp_type == _FieldDescriptor.CPPTYPE_MESSAGE:
542        field_copy = field._default_constructor(self)
543        new_val = None
544        if isinstance(field_value, message_mod.Message):
545          new_val = field_value
546        elif isinstance(field_value, dict):
547          if field.message_type.full_name == _StructFullTypeName:
548            field_copy.Clear()
549            if len(field_value) == 1 and 'fields' in field_value:
550              try:
551                field_copy.update(field_value)
552              except:
553                # Fall back to init normal message field
554                field_copy.Clear()
555                new_val = field.message_type._concrete_class(**field_value)
556            else:
557              field_copy.update(field_value)
558          else:
559            new_val = field.message_type._concrete_class(**field_value)
560        elif hasattr(field_copy, '_internal_assign'):
561          field_copy._internal_assign(field_value)
562        else:
563          raise TypeError(
564              'Message field {0}.{1} must be initialized with a '
565              'dict or instance of same class, got {2}.'.format(
566                  message_descriptor.name,
567                  field_name,
568                  type(field_value).__name__,
569              )
570          )
571
572        if new_val != None:
573          try:
574            field_copy.MergeFrom(new_val)
575          except TypeError:
576            _ReraiseTypeErrorWithFieldName(message_descriptor.name, field_name)
577        self._fields[field] = field_copy
578      else:
579        if field.cpp_type == _FieldDescriptor.CPPTYPE_ENUM:
580          field_value = _GetIntegerEnumValue(field.enum_type, field_value)
581        try:
582          setattr(self, field_name, field_value)
583        except TypeError:
584          _ReraiseTypeErrorWithFieldName(message_descriptor.name, field_name)
DESCRIPTOR = <google.protobuf.descriptor.Descriptor object>
def MergeFrom(self, msg):
1364  def MergeFrom(self, msg):
1365    if not isinstance(msg, cls):
1366      raise TypeError(
1367          'Parameter to MergeFrom() must be instance of same class: '
1368          'expected %s got %s.' % (_FullyQualifiedClassName(cls),
1369                                   _FullyQualifiedClassName(msg.__class__)))
1370
1371    assert msg is not self
1372    self._Modified()
1373
1374    fields = self._fields
1375
1376    for field, value in msg._fields.items():
1377      if field.label == LABEL_REPEATED:
1378        field_value = fields.get(field)
1379        if field_value is None:
1380          # Construct a new object to represent this field.
1381          field_value = field._default_constructor(self)
1382          fields[field] = field_value
1383        field_value.MergeFrom(value)
1384      elif field.cpp_type == CPPTYPE_MESSAGE:
1385        if value._is_present_in_parent:
1386          field_value = fields.get(field)
1387          if field_value is None:
1388            # Construct a new object to represent this field.
1389            field_value = field._default_constructor(self)
1390            fields[field] = field_value
1391          field_value.MergeFrom(value)
1392      else:
1393        self._fields[field] = value
1394        if field.containing_oneof:
1395          self._UpdateOneofState(field)
1396
1397    if msg._unknown_fields:
1398      if not self._unknown_fields:
1399        self._unknown_fields = []
1400      self._unknown_fields.extend(msg._unknown_fields)

Merges the contents of the specified message into current message.

This method merges the contents of the specified message into the current message. Singular fields that are set in the specified message overwrite the corresponding fields in the current message. Repeated fields are appended. Singular sub-messages and groups are recursively merged.

Arguments:
  • other_msg (Message): A message to merge into the current message.
def Clear(self):
1423def _Clear(self):
1424  # Clear fields.
1425  self._fields = {}
1426  self._unknown_fields = ()
1427
1428  self._oneofs = {}
1429  self._Modified()

Clears all data that was set in the message.

def SetInParent(self):
1489  def Modified(self):
1490    """Sets the _cached_byte_size_dirty bit to true,
1491    and propagates this to our listener iff this was a state change.
1492    """
1493
1494    # Note:  Some callers check _cached_byte_size_dirty before calling
1495    #   _Modified() as an extra optimization.  So, if this method is ever
1496    #   changed such that it does stuff even when _cached_byte_size_dirty is
1497    #   already true, the callers need to be updated.
1498    if not self._cached_byte_size_dirty:
1499      self._cached_byte_size_dirty = True
1500      self._listener_for_children.dirty = True
1501      self._is_present_in_parent = True
1502      self._listener.Modified()

Sets the _cached_byte_size_dirty bit to true, and propagates this to our listener iff this was a state change.

def IsInitialized(self, errors=None):
1265  def IsInitialized(self, errors=None):
1266    """Checks if all required fields of a message are set.
1267
1268    Args:
1269      errors:  A list which, if provided, will be populated with the field
1270               paths of all missing required fields.
1271
1272    Returns:
1273      True iff the specified message has all required fields set.
1274    """
1275
1276    # Performance is critical so we avoid HasField() and ListFields().
1277
1278    for field in required_fields:
1279      if (field not in self._fields or
1280          (field.cpp_type == _FieldDescriptor.CPPTYPE_MESSAGE and
1281           not self._fields[field]._is_present_in_parent)):
1282        if errors is not None:
1283          errors.extend(self.FindInitializationErrors())
1284        return False
1285
1286    for field, value in list(self._fields.items()):  # dict can change size!
1287      if field.cpp_type == _FieldDescriptor.CPPTYPE_MESSAGE:
1288        if field.label == _FieldDescriptor.LABEL_REPEATED:
1289          if (field.message_type._is_map_entry):
1290            continue
1291          for element in value:
1292            if not element.IsInitialized():
1293              if errors is not None:
1294                errors.extend(self.FindInitializationErrors())
1295              return False
1296        elif value._is_present_in_parent and not value.IsInitialized():
1297          if errors is not None:
1298            errors.extend(self.FindInitializationErrors())
1299          return False
1300
1301    return True

Checks if all required fields of a message are set.

Arguments:
  • errors: A list which, if provided, will be populated with the field paths of all missing required fields.
Returns:

True iff the specified message has all required fields set.

def MergeFromString(self, serialized):
1180  def MergeFromString(self, serialized):
1181    serialized = memoryview(serialized)
1182    length = len(serialized)
1183    try:
1184      if self._InternalParse(serialized, 0, length) != length:
1185        # The only reason _InternalParse would return early is if it
1186        # encountered an end-group tag.
1187        raise message_mod.DecodeError('Unexpected end-group tag.')
1188    except (IndexError, TypeError):
1189      # Now ord(buf[p:p+1]) == ord('') gets TypeError.
1190      raise message_mod.DecodeError('Truncated message.')
1191    except struct.error as e:
1192      raise message_mod.DecodeError(e)
1193    return length   # Return this for legacy reasons.

Merges serialized protocol buffer data into this message.

When we find a field in serialized that is already present in this message:

  • If it's a "repeated" field, we append to the end of our list.
  • Else, if it's a scalar, we overwrite our field.
  • Else, (it's a nonrepeated composite), we recursively merge into the existing composite.
Arguments:
  • serialized (bytes): Any object that allows us to call memoryview(serialized) to access a string of bytes using the buffer interface.
Returns:

int: The number of bytes read from serialized. For non-group messages, this will always be len(serialized), but for messages which are actually groups, this will generally be less than len(serialized), since we must stop when we reach an END_GROUP tag. Note that if we do stop because of an END_GROUP tag, the number of bytes returned does not include the bytes for the END_GROUP tag information.

Raises:
  • DecodeError: if the input cannot be parsed.
def SerializeToString(self, **kwargs):
1133  def SerializeToString(self, **kwargs):
1134    # Check if the message has all of its required fields set.
1135    if not self.IsInitialized():
1136      raise message_mod.EncodeError(
1137          'Message %s is missing required fields: %s' % (
1138          self.DESCRIPTOR.full_name, ','.join(self.FindInitializationErrors())))
1139    return self.SerializePartialToString(**kwargs)

Serializes the protocol message to a binary string.

Keyword Args:

deterministic (bool): If true, requests deterministic serialization of the protobuf, with predictable ordering of map keys.

Returns:

A binary string representation of the message if all of the required fields in the message are set (i.e. the message is initialized).

Raises:
def SerializePartialToString(self, **kwargs):
1146  def SerializePartialToString(self, **kwargs):
1147    out = BytesIO()
1148    self._InternalSerialize(out.write, **kwargs)
1149    return out.getvalue()

Serializes the protocol message to a binary string.

This method is similar to SerializeToString but doesn't check if the message is initialized.

Keyword Args:

deterministic (bool): If true, requests deterministic serialization of the protobuf, with predictable ordering of map keys.

Returns:

bytes: A serialized representation of the partial message.

def ListFields(self):
848  def ListFields(self):
849    all_fields = [item for item in self._fields.items() if _IsPresent(item)]
850    all_fields.sort(key = lambda item: item[0].number)
851    return all_fields

Returns a list of (FieldDescriptor, value) tuples for present fields.

A message field is non-empty if HasField() would return true. A singular primitive field is non-empty if HasField() would return true in proto2 or it is non zero in proto3. A repeated field is non-empty if it contains at least one element. The fields are ordered by field number.

Returns:

list[tuple(FieldDescriptor, value)]: field descriptors and values for all fields in the message which are not empty. The values vary by field type.

def HasField(self, field_name):
872  def HasField(self, field_name):
873    try:
874      field = hassable_fields[field_name]
875    except KeyError as exc:
876      raise ValueError('Protocol message %s has no non-repeated field "%s" '
877                       'nor has presence is not available for this field.' % (
878                           message_descriptor.full_name, field_name)) from exc
879
880    if isinstance(field, descriptor_mod.OneofDescriptor):
881      try:
882        return HasField(self, self._oneofs[field].name)
883      except KeyError:
884        return False
885    else:
886      if field.cpp_type == _FieldDescriptor.CPPTYPE_MESSAGE:
887        value = self._fields.get(field)
888        return value is not None and value._is_present_in_parent
889      else:
890        return field in self._fields

Checks if a certain field is set for the message.

For a oneof group, checks if any field inside is set. Note that if the field_name is not defined in the message descriptor, ValueError will be raised.

Arguments:
  • field_name (str): The name of the field to check for presence.
Returns:

bool: Whether a value has been set for the named field.

Raises:
  • ValueError: if the field_name is not a member of this message.
def ClearField(self, field_name):
897  def ClearField(self, field_name):
898    try:
899      field = message_descriptor.fields_by_name[field_name]
900    except KeyError:
901      try:
902        field = message_descriptor.oneofs_by_name[field_name]
903        if field in self._oneofs:
904          field = self._oneofs[field]
905        else:
906          return
907      except KeyError:
908        raise ValueError('Protocol message %s has no "%s" field.' %
909                         (message_descriptor.name, field_name))
910
911    if field in self._fields:
912      # To match the C++ implementation, we need to invalidate iterators
913      # for map fields when ClearField() happens.
914      if hasattr(self._fields[field], 'InvalidateIterators'):
915        self._fields[field].InvalidateIterators()
916
917      # Note:  If the field is a sub-message, its listener will still point
918      #   at us.  That's fine, because the worst than can happen is that it
919      #   will call _Modified() and invalidate our byte size.  Big deal.
920      del self._fields[field]
921
922      if self._oneofs.get(field.containing_oneof, None) is field:
923        del self._oneofs[field.containing_oneof]
924
925    # Always call _Modified() -- even if nothing was changed, this is
926    # a mutating method, and thus calling it should cause the field to become
927    # present in the parent message.
928    self._Modified()

Clears the contents of a given field.

Inside a oneof group, clears the field set. If the name neither refers to a defined field or oneof group, ValueError is raised.

Arguments:
  • field_name (str): The name of the field to check for presence.
Raises:
  • ValueError: if the field_name is not a member of this message.
def WhichOneof(self, oneof_name):
1406  def WhichOneof(self, oneof_name):
1407    """Returns the name of the currently set field inside a oneof, or None."""
1408    try:
1409      field = message_descriptor.oneofs_by_name[oneof_name]
1410    except KeyError:
1411      raise ValueError(
1412          'Protocol message has no oneof "%s" field.' % oneof_name)
1413
1414    nested_field = self._oneofs.get(field, None)
1415    if nested_field is not None and self.HasField(nested_field.name):
1416      return nested_field.name
1417    else:
1418      return None

Returns the name of the currently set field inside a oneof, or None.

def DiscardUnknownFields(self):
1438def _DiscardUnknownFields(self):
1439  self._unknown_fields = []
1440  for field, value in self.ListFields():
1441    if field.cpp_type == _FieldDescriptor.CPPTYPE_MESSAGE:
1442      if _IsMapField(field):
1443        if _IsMessageMapField(field):
1444          for key in value:
1445            value[key].DiscardUnknownFields()
1446      elif field.label == _FieldDescriptor.LABEL_REPEATED:
1447        for sub_message in value:
1448          sub_message.DiscardUnknownFields()
1449      else:
1450        value.DiscardUnknownFields()

Clears all fields in the UnknownFieldSet.

This operation is recursive for nested message.

def ByteSize(self):
1101  def ByteSize(self):
1102    if not self._cached_byte_size_dirty:
1103      return self._cached_byte_size
1104
1105    size = 0
1106    descriptor = self.DESCRIPTOR
1107    if descriptor._is_map_entry:
1108      # Fields of map entry should always be serialized.
1109      key_field = descriptor.fields_by_name['key']
1110      _MaybeAddEncoder(cls, key_field)
1111      size = key_field._sizer(self.key)
1112      value_field = descriptor.fields_by_name['value']
1113      _MaybeAddEncoder(cls, value_field)
1114      size += value_field._sizer(self.value)
1115    else:
1116      for field_descriptor, field_value in self.ListFields():
1117        _MaybeAddEncoder(cls, field_descriptor)
1118        size += field_descriptor._sizer(field_value)
1119      for tag_bytes, value_bytes in self._unknown_fields:
1120        size += len(tag_bytes) + len(value_bytes)
1121
1122    self._cached_byte_size = size
1123    self._cached_byte_size_dirty = False
1124    self._listener_for_children.dirty = False
1125    return size

Returns the serialized size of this message.

Recursively calls ByteSize() on all contained messages.

Returns:

int: The number of bytes required to serialize this message.

def FromString(s):
826  def FromString(s):
827    message = cls()
828    message.MergeFromString(s)
829    return message
VALUES_FIELD_NUMBER = 1
values
668  def getter(self):
669    field_value = self._fields.get(field)
670    if field_value is None:
671      # Construct a new object to represent this field.
672      field_value = field._default_constructor(self)
673
674      # Atomically check if another thread has preempted us and, if not, swap
675      # in the new object we just created.  If someone has preempted us, we
676      # take that object and discard ours.
677      # WARNING:  We are relying on setdefault() being atomic.  This is true
678      #   in CPython but we haven't investigated others.  This warning appears
679      #   in several other locations in this file.
680      field_value = self._fields.setdefault(field, field_value)
681    return field_value

Getter for values.

def FindInitializationErrors(self):
1305  def FindInitializationErrors(self):
1306    """Finds required fields which are not initialized.
1307
1308    Returns:
1309      A list of strings.  Each string is a path to an uninitialized field from
1310      the top-level message, e.g. "foo.bar[5].baz".
1311    """
1312
1313    errors = []  # simplify things
1314
1315    for field in required_fields:
1316      if not self.HasField(field.name):
1317        errors.append(field.name)
1318
1319    for field, value in self.ListFields():
1320      if field.cpp_type == _FieldDescriptor.CPPTYPE_MESSAGE:
1321        if field.is_extension:
1322          name = '(%s)' % field.full_name
1323        else:
1324          name = field.name
1325
1326        if _IsMapField(field):
1327          if _IsMessageMapField(field):
1328            for key in value:
1329              element = value[key]
1330              prefix = '%s[%s].' % (name, key)
1331              sub_errors = element.FindInitializationErrors()
1332              errors += [prefix + error for error in sub_errors]
1333          else:
1334            # ScalarMaps can't have any initialization errors.
1335            pass
1336        elif field.label == _FieldDescriptor.LABEL_REPEATED:
1337          for i in range(len(value)):
1338            element = value[i]
1339            prefix = '%s[%d].' % (name, i)
1340            sub_errors = element.FindInitializationErrors()
1341            errors += [prefix + error for error in sub_errors]
1342        else:
1343          prefix = name + '.'
1344          sub_errors = value.FindInitializationErrors()
1345          errors += [prefix + error for error in sub_errors]
1346
1347    return errors

Finds required fields which are not initialized.

Returns:

A list of strings. Each string is a path to an uninitialized field from the top-level message, e.g. "foo.bar[5].baz".

class CpSolverResponse(google.protobuf.message.Message):

Abstract base class for protocol messages.

Protocol message classes are almost always generated by the protocol compiler. These generated types subclass Message and implement the methods shown below.

CpSolverResponse(**kwargs)
498  def init(self, **kwargs):
499    self._cached_byte_size = 0
500    self._cached_byte_size_dirty = len(kwargs) > 0
501    self._fields = {}
502    # Contains a mapping from oneof field descriptors to the descriptor
503    # of the currently set field in that oneof field.
504    self._oneofs = {}
505
506    # _unknown_fields is () when empty for efficiency, and will be turned into
507    # a list if fields are added.
508    self._unknown_fields = ()
509    self._is_present_in_parent = False
510    self._listener = message_listener_mod.NullMessageListener()
511    self._listener_for_children = _Listener(self)
512    for field_name, field_value in kwargs.items():
513      field = _GetFieldByName(message_descriptor, field_name)
514      if field is None:
515        raise TypeError('%s() got an unexpected keyword argument "%s"' %
516                        (message_descriptor.name, field_name))
517      if field_value is None:
518        # field=None is the same as no field at all.
519        continue
520      if field.label == _FieldDescriptor.LABEL_REPEATED:
521        field_copy = field._default_constructor(self)
522        if field.cpp_type == _FieldDescriptor.CPPTYPE_MESSAGE:  # Composite
523          if _IsMapField(field):
524            if _IsMessageMapField(field):
525              for key in field_value:
526                field_copy[key].MergeFrom(field_value[key])
527            else:
528              field_copy.update(field_value)
529          else:
530            for val in field_value:
531              if isinstance(val, dict):
532                field_copy.add(**val)
533              else:
534                field_copy.add().MergeFrom(val)
535        else:  # Scalar
536          if field.cpp_type == _FieldDescriptor.CPPTYPE_ENUM:
537            field_value = [_GetIntegerEnumValue(field.enum_type, val)
538                           for val in field_value]
539          field_copy.extend(field_value)
540        self._fields[field] = field_copy
541      elif field.cpp_type == _FieldDescriptor.CPPTYPE_MESSAGE:
542        field_copy = field._default_constructor(self)
543        new_val = None
544        if isinstance(field_value, message_mod.Message):
545          new_val = field_value
546        elif isinstance(field_value, dict):
547          if field.message_type.full_name == _StructFullTypeName:
548            field_copy.Clear()
549            if len(field_value) == 1 and 'fields' in field_value:
550              try:
551                field_copy.update(field_value)
552              except:
553                # Fall back to init normal message field
554                field_copy.Clear()
555                new_val = field.message_type._concrete_class(**field_value)
556            else:
557              field_copy.update(field_value)
558          else:
559            new_val = field.message_type._concrete_class(**field_value)
560        elif hasattr(field_copy, '_internal_assign'):
561          field_copy._internal_assign(field_value)
562        else:
563          raise TypeError(
564              'Message field {0}.{1} must be initialized with a '
565              'dict or instance of same class, got {2}.'.format(
566                  message_descriptor.name,
567                  field_name,
568                  type(field_value).__name__,
569              )
570          )
571
572        if new_val != None:
573          try:
574            field_copy.MergeFrom(new_val)
575          except TypeError:
576            _ReraiseTypeErrorWithFieldName(message_descriptor.name, field_name)
577        self._fields[field] = field_copy
578      else:
579        if field.cpp_type == _FieldDescriptor.CPPTYPE_ENUM:
580          field_value = _GetIntegerEnumValue(field.enum_type, field_value)
581        try:
582          setattr(self, field_name, field_value)
583        except TypeError:
584          _ReraiseTypeErrorWithFieldName(message_descriptor.name, field_name)
DESCRIPTOR = <google.protobuf.descriptor.Descriptor object>
def MergeFrom(self, msg):
1364  def MergeFrom(self, msg):
1365    if not isinstance(msg, cls):
1366      raise TypeError(
1367          'Parameter to MergeFrom() must be instance of same class: '
1368          'expected %s got %s.' % (_FullyQualifiedClassName(cls),
1369                                   _FullyQualifiedClassName(msg.__class__)))
1370
1371    assert msg is not self
1372    self._Modified()
1373
1374    fields = self._fields
1375
1376    for field, value in msg._fields.items():
1377      if field.label == LABEL_REPEATED:
1378        field_value = fields.get(field)
1379        if field_value is None:
1380          # Construct a new object to represent this field.
1381          field_value = field._default_constructor(self)
1382          fields[field] = field_value
1383        field_value.MergeFrom(value)
1384      elif field.cpp_type == CPPTYPE_MESSAGE:
1385        if value._is_present_in_parent:
1386          field_value = fields.get(field)
1387          if field_value is None:
1388            # Construct a new object to represent this field.
1389            field_value = field._default_constructor(self)
1390            fields[field] = field_value
1391          field_value.MergeFrom(value)
1392      else:
1393        self._fields[field] = value
1394        if field.containing_oneof:
1395          self._UpdateOneofState(field)
1396
1397    if msg._unknown_fields:
1398      if not self._unknown_fields:
1399        self._unknown_fields = []
1400      self._unknown_fields.extend(msg._unknown_fields)

Merges the contents of the specified message into current message.

This method merges the contents of the specified message into the current message. Singular fields that are set in the specified message overwrite the corresponding fields in the current message. Repeated fields are appended. Singular sub-messages and groups are recursively merged.

Arguments:
  • other_msg (Message): A message to merge into the current message.
def Clear(self):
1423def _Clear(self):
1424  # Clear fields.
1425  self._fields = {}
1426  self._unknown_fields = ()
1427
1428  self._oneofs = {}
1429  self._Modified()

Clears all data that was set in the message.

def SetInParent(self):
1489  def Modified(self):
1490    """Sets the _cached_byte_size_dirty bit to true,
1491    and propagates this to our listener iff this was a state change.
1492    """
1493
1494    # Note:  Some callers check _cached_byte_size_dirty before calling
1495    #   _Modified() as an extra optimization.  So, if this method is ever
1496    #   changed such that it does stuff even when _cached_byte_size_dirty is
1497    #   already true, the callers need to be updated.
1498    if not self._cached_byte_size_dirty:
1499      self._cached_byte_size_dirty = True
1500      self._listener_for_children.dirty = True
1501      self._is_present_in_parent = True
1502      self._listener.Modified()

Sets the _cached_byte_size_dirty bit to true, and propagates this to our listener iff this was a state change.

def IsInitialized(self, errors=None):
1265  def IsInitialized(self, errors=None):
1266    """Checks if all required fields of a message are set.
1267
1268    Args:
1269      errors:  A list which, if provided, will be populated with the field
1270               paths of all missing required fields.
1271
1272    Returns:
1273      True iff the specified message has all required fields set.
1274    """
1275
1276    # Performance is critical so we avoid HasField() and ListFields().
1277
1278    for field in required_fields:
1279      if (field not in self._fields or
1280          (field.cpp_type == _FieldDescriptor.CPPTYPE_MESSAGE and
1281           not self._fields[field]._is_present_in_parent)):
1282        if errors is not None:
1283          errors.extend(self.FindInitializationErrors())
1284        return False
1285
1286    for field, value in list(self._fields.items()):  # dict can change size!
1287      if field.cpp_type == _FieldDescriptor.CPPTYPE_MESSAGE:
1288        if field.label == _FieldDescriptor.LABEL_REPEATED:
1289          if (field.message_type._is_map_entry):
1290            continue
1291          for element in value:
1292            if not element.IsInitialized():
1293              if errors is not None:
1294                errors.extend(self.FindInitializationErrors())
1295              return False
1296        elif value._is_present_in_parent and not value.IsInitialized():
1297          if errors is not None:
1298            errors.extend(self.FindInitializationErrors())
1299          return False
1300
1301    return True

Checks if all required fields of a message are set.

Arguments:
  • errors: A list which, if provided, will be populated with the field paths of all missing required fields.
Returns:

True iff the specified message has all required fields set.

def MergeFromString(self, serialized):
1180  def MergeFromString(self, serialized):
1181    serialized = memoryview(serialized)
1182    length = len(serialized)
1183    try:
1184      if self._InternalParse(serialized, 0, length) != length:
1185        # The only reason _InternalParse would return early is if it
1186        # encountered an end-group tag.
1187        raise message_mod.DecodeError('Unexpected end-group tag.')
1188    except (IndexError, TypeError):
1189      # Now ord(buf[p:p+1]) == ord('') gets TypeError.
1190      raise message_mod.DecodeError('Truncated message.')
1191    except struct.error as e:
1192      raise message_mod.DecodeError(e)
1193    return length   # Return this for legacy reasons.

Merges serialized protocol buffer data into this message.

When we find a field in serialized that is already present in this message:

  • If it's a "repeated" field, we append to the end of our list.
  • Else, if it's a scalar, we overwrite our field.
  • Else, (it's a nonrepeated composite), we recursively merge into the existing composite.
Arguments:
  • serialized (bytes): Any object that allows us to call memoryview(serialized) to access a string of bytes using the buffer interface.
Returns:

int: The number of bytes read from serialized. For non-group messages, this will always be len(serialized), but for messages which are actually groups, this will generally be less than len(serialized), since we must stop when we reach an END_GROUP tag. Note that if we do stop because of an END_GROUP tag, the number of bytes returned does not include the bytes for the END_GROUP tag information.

Raises:
  • DecodeError: if the input cannot be parsed.
def SerializeToString(self, **kwargs):
1133  def SerializeToString(self, **kwargs):
1134    # Check if the message has all of its required fields set.
1135    if not self.IsInitialized():
1136      raise message_mod.EncodeError(
1137          'Message %s is missing required fields: %s' % (
1138          self.DESCRIPTOR.full_name, ','.join(self.FindInitializationErrors())))
1139    return self.SerializePartialToString(**kwargs)

Serializes the protocol message to a binary string.

Keyword Args:

deterministic (bool): If true, requests deterministic serialization of the protobuf, with predictable ordering of map keys.

Returns:

A binary string representation of the message if all of the required fields in the message are set (i.e. the message is initialized).

Raises:
def SerializePartialToString(self, **kwargs):
1146  def SerializePartialToString(self, **kwargs):
1147    out = BytesIO()
1148    self._InternalSerialize(out.write, **kwargs)
1149    return out.getvalue()

Serializes the protocol message to a binary string.

This method is similar to SerializeToString but doesn't check if the message is initialized.

Keyword Args:

deterministic (bool): If true, requests deterministic serialization of the protobuf, with predictable ordering of map keys.

Returns:

bytes: A serialized representation of the partial message.

def ListFields(self):
848  def ListFields(self):
849    all_fields = [item for item in self._fields.items() if _IsPresent(item)]
850    all_fields.sort(key = lambda item: item[0].number)
851    return all_fields

Returns a list of (FieldDescriptor, value) tuples for present fields.

A message field is non-empty if HasField() would return true. A singular primitive field is non-empty if HasField() would return true in proto2 or it is non zero in proto3. A repeated field is non-empty if it contains at least one element. The fields are ordered by field number.

Returns:

list[tuple(FieldDescriptor, value)]: field descriptors and values for all fields in the message which are not empty. The values vary by field type.

def HasField(self, field_name):
872  def HasField(self, field_name):
873    try:
874      field = hassable_fields[field_name]
875    except KeyError as exc:
876      raise ValueError('Protocol message %s has no non-repeated field "%s" '
877                       'nor has presence is not available for this field.' % (
878                           message_descriptor.full_name, field_name)) from exc
879
880    if isinstance(field, descriptor_mod.OneofDescriptor):
881      try:
882        return HasField(self, self._oneofs[field].name)
883      except KeyError:
884        return False
885    else:
886      if field.cpp_type == _FieldDescriptor.CPPTYPE_MESSAGE:
887        value = self._fields.get(field)
888        return value is not None and value._is_present_in_parent
889      else:
890        return field in self._fields

Checks if a certain field is set for the message.

For a oneof group, checks if any field inside is set. Note that if the field_name is not defined in the message descriptor, ValueError will be raised.

Arguments:
  • field_name (str): The name of the field to check for presence.
Returns:

bool: Whether a value has been set for the named field.

Raises:
  • ValueError: if the field_name is not a member of this message.
def ClearField(self, field_name):
897  def ClearField(self, field_name):
898    try:
899      field = message_descriptor.fields_by_name[field_name]
900    except KeyError:
901      try:
902        field = message_descriptor.oneofs_by_name[field_name]
903        if field in self._oneofs:
904          field = self._oneofs[field]
905        else:
906          return
907      except KeyError:
908        raise ValueError('Protocol message %s has no "%s" field.' %
909                         (message_descriptor.name, field_name))
910
911    if field in self._fields:
912      # To match the C++ implementation, we need to invalidate iterators
913      # for map fields when ClearField() happens.
914      if hasattr(self._fields[field], 'InvalidateIterators'):
915        self._fields[field].InvalidateIterators()
916
917      # Note:  If the field is a sub-message, its listener will still point
918      #   at us.  That's fine, because the worst than can happen is that it
919      #   will call _Modified() and invalidate our byte size.  Big deal.
920      del self._fields[field]
921
922      if self._oneofs.get(field.containing_oneof, None) is field:
923        del self._oneofs[field.containing_oneof]
924
925    # Always call _Modified() -- even if nothing was changed, this is
926    # a mutating method, and thus calling it should cause the field to become
927    # present in the parent message.
928    self._Modified()

Clears the contents of a given field.

Inside a oneof group, clears the field set. If the name neither refers to a defined field or oneof group, ValueError is raised.

Arguments:
  • field_name (str): The name of the field to check for presence.
Raises:
  • ValueError: if the field_name is not a member of this message.
def WhichOneof(self, oneof_name):
1406  def WhichOneof(self, oneof_name):
1407    """Returns the name of the currently set field inside a oneof, or None."""
1408    try:
1409      field = message_descriptor.oneofs_by_name[oneof_name]
1410    except KeyError:
1411      raise ValueError(
1412          'Protocol message has no oneof "%s" field.' % oneof_name)
1413
1414    nested_field = self._oneofs.get(field, None)
1415    if nested_field is not None and self.HasField(nested_field.name):
1416      return nested_field.name
1417    else:
1418      return None

Returns the name of the currently set field inside a oneof, or None.

def DiscardUnknownFields(self):
1438def _DiscardUnknownFields(self):
1439  self._unknown_fields = []
1440  for field, value in self.ListFields():
1441    if field.cpp_type == _FieldDescriptor.CPPTYPE_MESSAGE:
1442      if _IsMapField(field):
1443        if _IsMessageMapField(field):
1444          for key in value:
1445            value[key].DiscardUnknownFields()
1446      elif field.label == _FieldDescriptor.LABEL_REPEATED:
1447        for sub_message in value:
1448          sub_message.DiscardUnknownFields()
1449      else:
1450        value.DiscardUnknownFields()

Clears all fields in the UnknownFieldSet.

This operation is recursive for nested message.

def ByteSize(self):
1101  def ByteSize(self):
1102    if not self._cached_byte_size_dirty:
1103      return self._cached_byte_size
1104
1105    size = 0
1106    descriptor = self.DESCRIPTOR
1107    if descriptor._is_map_entry:
1108      # Fields of map entry should always be serialized.
1109      key_field = descriptor.fields_by_name['key']
1110      _MaybeAddEncoder(cls, key_field)
1111      size = key_field._sizer(self.key)
1112      value_field = descriptor.fields_by_name['value']
1113      _MaybeAddEncoder(cls, value_field)
1114      size += value_field._sizer(self.value)
1115    else:
1116      for field_descriptor, field_value in self.ListFields():
1117        _MaybeAddEncoder(cls, field_descriptor)
1118        size += field_descriptor._sizer(field_value)
1119      for tag_bytes, value_bytes in self._unknown_fields:
1120        size += len(tag_bytes) + len(value_bytes)
1121
1122    self._cached_byte_size = size
1123    self._cached_byte_size_dirty = False
1124    self._listener_for_children.dirty = False
1125    return size

Returns the serialized size of this message.

Recursively calls ByteSize() on all contained messages.

Returns:

int: The number of bytes required to serialize this message.

def FromString(s):
826  def FromString(s):
827    message = cls()
828    message.MergeFromString(s)
829    return message
STATUS_FIELD_NUMBER = 1
status
711  def getter(self):
712    # TODO: This may be broken since there may not be
713    # default_value.  Combine with has_default_value somehow.
714    return self._fields.get(field, default_value)

Getter for status.

SOLUTION_FIELD_NUMBER = 2
solution
668  def getter(self):
669    field_value = self._fields.get(field)
670    if field_value is None:
671      # Construct a new object to represent this field.
672      field_value = field._default_constructor(self)
673
674      # Atomically check if another thread has preempted us and, if not, swap
675      # in the new object we just created.  If someone has preempted us, we
676      # take that object and discard ours.
677      # WARNING:  We are relying on setdefault() being atomic.  This is true
678      #   in CPython but we haven't investigated others.  This warning appears
679      #   in several other locations in this file.
680      field_value = self._fields.setdefault(field, field_value)
681    return field_value

Getter for solution.

OBJECTIVE_VALUE_FIELD_NUMBER = 3
objective_value
711  def getter(self):
712    # TODO: This may be broken since there may not be
713    # default_value.  Combine with has_default_value somehow.
714    return self._fields.get(field, default_value)

Getter for objective_value.

BEST_OBJECTIVE_BOUND_FIELD_NUMBER = 4
best_objective_bound
711  def getter(self):
712    # TODO: This may be broken since there may not be
713    # default_value.  Combine with has_default_value somehow.
714    return self._fields.get(field, default_value)

Getter for best_objective_bound.

ADDITIONAL_SOLUTIONS_FIELD_NUMBER = 27
additional_solutions
668  def getter(self):
669    field_value = self._fields.get(field)
670    if field_value is None:
671      # Construct a new object to represent this field.
672      field_value = field._default_constructor(self)
673
674      # Atomically check if another thread has preempted us and, if not, swap
675      # in the new object we just created.  If someone has preempted us, we
676      # take that object and discard ours.
677      # WARNING:  We are relying on setdefault() being atomic.  This is true
678      #   in CPython but we haven't investigated others.  This warning appears
679      #   in several other locations in this file.
680      field_value = self._fields.setdefault(field, field_value)
681    return field_value

Getter for additional_solutions.

TIGHTENED_VARIABLES_FIELD_NUMBER = 21
tightened_variables
668  def getter(self):
669    field_value = self._fields.get(field)
670    if field_value is None:
671      # Construct a new object to represent this field.
672      field_value = field._default_constructor(self)
673
674      # Atomically check if another thread has preempted us and, if not, swap
675      # in the new object we just created.  If someone has preempted us, we
676      # take that object and discard ours.
677      # WARNING:  We are relying on setdefault() being atomic.  This is true
678      #   in CPython but we haven't investigated others.  This warning appears
679      #   in several other locations in this file.
680      field_value = self._fields.setdefault(field, field_value)
681    return field_value

Getter for tightened_variables.

SUFFICIENT_ASSUMPTIONS_FOR_INFEASIBILITY_FIELD_NUMBER = 23
sufficient_assumptions_for_infeasibility
668  def getter(self):
669    field_value = self._fields.get(field)
670    if field_value is None:
671      # Construct a new object to represent this field.
672      field_value = field._default_constructor(self)
673
674      # Atomically check if another thread has preempted us and, if not, swap
675      # in the new object we just created.  If someone has preempted us, we
676      # take that object and discard ours.
677      # WARNING:  We are relying on setdefault() being atomic.  This is true
678      #   in CPython but we haven't investigated others.  This warning appears
679      #   in several other locations in this file.
680      field_value = self._fields.setdefault(field, field_value)
681    return field_value

Getter for sufficient_assumptions_for_infeasibility.

INTEGER_OBJECTIVE_FIELD_NUMBER = 28
integer_objective
767  def getter(self):
768    field_value = self._fields.get(field)
769    if field_value is None:
770      # Construct a new object to represent this field.
771      field_value = field._default_constructor(self)
772
773      # Atomically check if another thread has preempted us and, if not, swap
774      # in the new object we just created.  If someone has preempted us, we
775      # take that object and discard ours.
776      # WARNING:  We are relying on setdefault() being atomic.  This is true
777      #   in CPython but we haven't investigated others.  This warning appears
778      #   in several other locations in this file.
779      field_value = self._fields.setdefault(field, field_value)
780    return field_value

Getter for integer_objective.

INNER_OBJECTIVE_LOWER_BOUND_FIELD_NUMBER = 29
inner_objective_lower_bound
711  def getter(self):
712    # TODO: This may be broken since there may not be
713    # default_value.  Combine with has_default_value somehow.
714    return self._fields.get(field, default_value)

Getter for inner_objective_lower_bound.

NUM_INTEGERS_FIELD_NUMBER = 30
num_integers
711  def getter(self):
712    # TODO: This may be broken since there may not be
713    # default_value.  Combine with has_default_value somehow.
714    return self._fields.get(field, default_value)

Getter for num_integers.

NUM_BOOLEANS_FIELD_NUMBER = 10
num_booleans
711  def getter(self):
712    # TODO: This may be broken since there may not be
713    # default_value.  Combine with has_default_value somehow.
714    return self._fields.get(field, default_value)

Getter for num_booleans.

NUM_FIXED_BOOLEANS_FIELD_NUMBER = 31
num_fixed_booleans
711  def getter(self):
712    # TODO: This may be broken since there may not be
713    # default_value.  Combine with has_default_value somehow.
714    return self._fields.get(field, default_value)

Getter for num_fixed_booleans.

NUM_CONFLICTS_FIELD_NUMBER = 11
num_conflicts
711  def getter(self):
712    # TODO: This may be broken since there may not be
713    # default_value.  Combine with has_default_value somehow.
714    return self._fields.get(field, default_value)

Getter for num_conflicts.

NUM_BRANCHES_FIELD_NUMBER = 12
num_branches
711  def getter(self):
712    # TODO: This may be broken since there may not be
713    # default_value.  Combine with has_default_value somehow.
714    return self._fields.get(field, default_value)

Getter for num_branches.

NUM_BINARY_PROPAGATIONS_FIELD_NUMBER = 13
num_binary_propagations
711  def getter(self):
712    # TODO: This may be broken since there may not be
713    # default_value.  Combine with has_default_value somehow.
714    return self._fields.get(field, default_value)

Getter for num_binary_propagations.

NUM_INTEGER_PROPAGATIONS_FIELD_NUMBER = 14
num_integer_propagations
711  def getter(self):
712    # TODO: This may be broken since there may not be
713    # default_value.  Combine with has_default_value somehow.
714    return self._fields.get(field, default_value)

Getter for num_integer_propagations.

NUM_RESTARTS_FIELD_NUMBER = 24
num_restarts
711  def getter(self):
712    # TODO: This may be broken since there may not be
713    # default_value.  Combine with has_default_value somehow.
714    return self._fields.get(field, default_value)

Getter for num_restarts.

NUM_LP_ITERATIONS_FIELD_NUMBER = 25
num_lp_iterations
711  def getter(self):
712    # TODO: This may be broken since there may not be
713    # default_value.  Combine with has_default_value somehow.
714    return self._fields.get(field, default_value)

Getter for num_lp_iterations.

WALL_TIME_FIELD_NUMBER = 15
wall_time
711  def getter(self):
712    # TODO: This may be broken since there may not be
713    # default_value.  Combine with has_default_value somehow.
714    return self._fields.get(field, default_value)

Getter for wall_time.

USER_TIME_FIELD_NUMBER = 16
user_time
711  def getter(self):
712    # TODO: This may be broken since there may not be
713    # default_value.  Combine with has_default_value somehow.
714    return self._fields.get(field, default_value)

Getter for user_time.

DETERMINISTIC_TIME_FIELD_NUMBER = 17
deterministic_time
711  def getter(self):
712    # TODO: This may be broken since there may not be
713    # default_value.  Combine with has_default_value somehow.
714    return self._fields.get(field, default_value)

Getter for deterministic_time.

GAP_INTEGRAL_FIELD_NUMBER = 22
gap_integral
711  def getter(self):
712    # TODO: This may be broken since there may not be
713    # default_value.  Combine with has_default_value somehow.
714    return self._fields.get(field, default_value)

Getter for gap_integral.

SOLUTION_INFO_FIELD_NUMBER = 20
solution_info
711  def getter(self):
712    # TODO: This may be broken since there may not be
713    # default_value.  Combine with has_default_value somehow.
714    return self._fields.get(field, default_value)

Getter for solution_info.

SOLVE_LOG_FIELD_NUMBER = 26
solve_log
711  def getter(self):
712    # TODO: This may be broken since there may not be
713    # default_value.  Combine with has_default_value somehow.
714    return self._fields.get(field, default_value)

Getter for solve_log.

def FindInitializationErrors(self):
1305  def FindInitializationErrors(self):
1306    """Finds required fields which are not initialized.
1307
1308    Returns:
1309      A list of strings.  Each string is a path to an uninitialized field from
1310      the top-level message, e.g. "foo.bar[5].baz".
1311    """
1312
1313    errors = []  # simplify things
1314
1315    for field in required_fields:
1316      if not self.HasField(field.name):
1317        errors.append(field.name)
1318
1319    for field, value in self.ListFields():
1320      if field.cpp_type == _FieldDescriptor.CPPTYPE_MESSAGE:
1321        if field.is_extension:
1322          name = '(%s)' % field.full_name
1323        else:
1324          name = field.name
1325
1326        if _IsMapField(field):
1327          if _IsMessageMapField(field):
1328            for key in value:
1329              element = value[key]
1330              prefix = '%s[%s].' % (name, key)
1331              sub_errors = element.FindInitializationErrors()
1332              errors += [prefix + error for error in sub_errors]
1333          else:
1334            # ScalarMaps can't have any initialization errors.
1335            pass
1336        elif field.label == _FieldDescriptor.LABEL_REPEATED:
1337          for i in range(len(value)):
1338            element = value[i]
1339            prefix = '%s[%d].' % (name, i)
1340            sub_errors = element.FindInitializationErrors()
1341            errors += [prefix + error for error in sub_errors]
1342        else:
1343          prefix = name + '.'
1344          sub_errors = value.FindInitializationErrors()
1345          errors += [prefix + error for error in sub_errors]
1346
1347    return errors

Finds required fields which are not initialized.

Returns:

A list of strings. Each string is a path to an uninitialized field from the top-level message, e.g. "foo.bar[5].baz".