Client-Side Python Mapping for Operations
Mapping for Operations
As we saw in the Client-Side Python Mapping for Interfaces, for each operation on an interface, the generated proxy class contains 2 methods for this operation. To invoke an operation, you call one of these methods on the proxy. For example, let’s take the generated code from the greeter example:
module VisitorCenter
{
interface Greeter
{
string greet(string name);
}
}
The proxy class generated from the Greeter interface, after removing extra details, is as follows:
class GreeterPrx(ObjectPrx):
def greet(self, name: str, context: dict[str, str] | None = None) -> str:
# ...
def greetAsync(self, name: str, context: dict[str, str] | None = None) -> Awaitable[str]:
# ...
Given a proxy to an object of type Greeter, the client can invoke the greet operation as follows:
greeter = VisitorCenter.GreeterPrx(communicator, "greeter:tcp -h localhost -p 4061")
greeting = await greeter.greetAsync("Alice") # Get name via RPC
Sync and Async Methods
For each operation, the Slice compiler generates 2 methods on the proxy class:
a “sync” method with the same name as the operation. When you call this method, your program waits synchronously until the invocation completes. A successful invocation completes with a return value (which can be void), while an unsuccessful invocation completes with an exception.
an “async” method, named
<operation-name>Async. When you call this method, your program marshals the arguments to the method synchronously, but the remainder of this invocation is asynchronous, and the method returns a future immediately. These async methods are described in more detail in Asynchronous Method Invocation (AMI) in Python.
We recommend using asyncio and async invocations in new applications.
Exception Handling
Any operation invocation may throw a runtime exception and, if the operation has an exception specification, may also throw user exceptions. Suppose we have the following simple interface:
exception Tantrum
{
string reason;
}
interface Child
{
void askToCleanUp() throws Tantrum;
}
Slice exceptions are thrown as Python exceptions, so you can simply enclose one or more operation invocations in a try-except block:
child = ... # Get child proxy...
try:
await child.askToCleanUpAsync()
except Tantrum as t:
print(f"The child says: {t.reason}")