--- url: "https://grpc.io/docs/languages/python/generated-code/" titulek: "Generated-code reference | Python | gRPC" h1: "Generated-code reference" popis: "gRPC Python relies on the protocol buffers compiler (protoc) to generate code. It uses a plugin to supplement the generated code by plain protoc with …" jazyk: "en" kanonicka: "https://grpc.io/docs/languages/python/generated-code/" drobecky: ["Docs", "Languages", "Python", "Generated code"] zdroj: "live" wayback_snapshot: "" stazeno: "2026-09-13 21:00:15" znaku: 6602 slov: 609 kodovani: "utf-8" sha256: "13f337999d473fdb889fdfe717d506ed2daa379ee9a9b24ee8053c8781fe3ed4" --- # Generated-code reference Contents # Generated-code reference gRPC Python relies on the protocol buffers compiler (`protoc`) to generate code. It uses a plugin to supplement the generated code by plain `protoc` with gRPC-specific code. For a `.proto` service description containing gRPC services, the plain `protoc` generated code is synthesized in a `_pb2.py` file, and the gRPC-specific code lands in a `_pb2_grpc.py` file. The latter python module imports the former. The focus of this page is on the gRPC-specific subset of the generated code. ## Example Consider the following `FortuneTeller` proto service: ``` service FortuneTeller { // Returns the horoscope and zodiac sign for the given month and day. rpc TellFortune(HoroscopeRequest) returns (HoroscopeResponse) { // errors: invalid month or day, fortune unavailable } // Replaces the fortune for the given zodiac sign with the provided one. rpc SuggestFortune(SuggestionRequest) returns (SuggestionResponse) { // errors: invalid zodiac sign } } ``` When the service is compiled, the gRPC `protoc` plugin generates code similar to the following `_pb2_grpc.py` file: ``` import grpc import fortune_pb2 class FortuneTellerStub(object): def __init__(self, channel): """Constructor. Args: channel: A grpc.Channel. """ self.TellFortune = channel.unary_unary( '/example.FortuneTeller/TellFortune', request_serializer=fortune_pb2.HoroscopeRequest.SerializeToString, response_deserializer=fortune_pb2.HoroscopeResponse.FromString, ) self.SuggestFortune = channel.unary_unary( '/example.FortuneTeller/SuggestFortune', request_serializer=fortune_pb2.SuggestionRequest.SerializeToString, response_deserializer=fortune_pb2.SuggestionResponse.FromString, ) class FortuneTellerServicer(object): def TellFortune(self, request, context): """Returns the horoscope and zodiac sign for the given month and day. errors: invalid month or day, fortune unavailable """ context.set_code(grpc.StatusCode.UNIMPLEMENTED) context.set_details('Method not implemented!') raise NotImplementedError('Method not implemented!') def SuggestFortune(self, request, context): """Replaces the fortune for the given zodiac sign with the provided one. errors: invalid zodiac sign """ context.set_code(grpc.StatusCode.UNIMPLEMENTED) context.set_details('Method not implemented!') raise NotImplementedError('Method not implemented!') def add_FortuneTellerServicer_to_server(servicer, server): rpc_method_handlers = { 'TellFortune': grpc.unary_unary_rpc_method_handler( servicer.TellFortune, request_deserializer=fortune_pb2.HoroscopeRequest.FromString, response_serializer=fortune_pb2.HoroscopeResponse.SerializeToString, ), 'SuggestFortune': grpc.unary_unary_rpc_method_handler( servicer.SuggestFortune, request_deserializer=fortune_pb2.SuggestionRequest.FromString, response_serializer=fortune_pb2.SuggestionResponse.SerializeToString, ), } generic_handler = grpc.method_handlers_generic_handler( 'example.FortuneTeller', rpc_method_handlers) server.add_generic_rpc_handlers((generic_handler,)) ``` ## Code Elements The gRPC generated code starts by importing the `grpc` package and the plain `_pb2` module, synthesized by `protoc`, which defines non-gRPC-specific code elements, like the classes corresponding to protocol buffers messages and descriptors used by reflection. For each service `Foo` in the `.proto` file, three primary elements are generated: - **Stub** : `FooStub` used by the client to connect to a gRPC service. - **Servicer** : `FooServicer` used by the server to implement a gRPC service. - **Registration Function** : `add_FooServicer_to_server` function used to register a servicer with a `grpc.Server` object. ### Stub The generated `Stub` class is used by the gRPC clients. It has a constructor that takes a `grpc.Channel` object and initializes the stub. For each method in the service, the initializer adds a corresponding attribute to the stub object with the same name. Depending on the RPC type (unary or streaming), the value of that attribute will be callable objects of type [UnaryUnaryMultiCallable](/grpc/python/grpc.html?#grpc.UnaryUnaryMultiCallable), [UnaryStreamMultiCallable](/grpc/python/grpc.html?#grpc.UnaryStreamMultiCallable), [StreamUnaryMultiCallable](/grpc/python/grpc.html?#grpc.StreamUnaryMultiCallable), or [StreamStreamMultiCallable](/grpc/python/grpc.html?#grpc.StreamStreamMultiCallable). ### Servicer For each service, a `Servicer` class is generated, which serves as the superclass of a service implementation. For each method in the service, a corresponding function in the `Servicer` class is generated. Override this function with the service implementation. Comments associated with code elements in the `.proto` file appear as docstrings in the generated python code. ### Registration Function For each service, a function is generated that registers a `Servicer` object implementing it on a `grpc.Server` object, so that the server can route queries to the respective servicer. This function takes an object that implements the `Servicer`, typically an instance of a subclass of the generated `Servicer` code element described above, and a [grpc.Server](/grpc/python/_modules/grpc.html#Server) object. Last modified August 11, 2021: [Replace use of short_title with linkTitle in page front matter (#821) (78a4d99)](https://github.com/grpc/grpc.io/commit/78a4d993c127e34eff95fc9a0b7144328c9db958) [View page source](https://github.com/grpc/grpc.io/tree/main/content/en/docs/languages/python/generated-code.md) [Edit this page](https://github.com/grpc/grpc.io/edit/main/content/en/docs/languages/python/generated-code.md) [Create child page](https://github.com/grpc/grpc.io/new/main/content/en/docs/languages/python/generated-code.md?filename=change-me.md&value=---%0Atitle%3A+%22Long+Page+Title%22%0AlinkTitle%3A+%22Short+Nav+Title%22%0Aweight%3A+100%0Adescription%3A+%3E-%0A+++++Page+description+for+heading+and+indexes.%0A---%0A%0A%23%23+Heading%0A%0AEdit+this+template+to+create+your+new+page.%0A%0A%2A+Give+it+a+good+name%2C+ending+in+%60.md%60+-+e.g.+%60getting-started.md%60%0A%2A+Edit+the+%22front+matter%22+section+at+the+top+of+the+page+%28weight+controls+how+its+ordered+amongst+other+pages+in+the+same+directory%3B+lowest+number+first%29.%0A%2A+Add+a+good+commit+message+at+the+bottom+of+the+page+%28%3C80+characters%3B+use+the+extended+description+field+for+more+detail%29.%0A%2A+Create+a+new+branch+so+you+can+preview+your+new+file+and+request+a+review+via+Pull+Request.%0A) [Create documentation issue](https://github.com/grpc/grpc.io/issues/new?title=Generated-code%20reference) [Create project issue](https://github.com/grpc/grpc.io/issues/new)