class documentation

Manage high-level gRPC channels for the SDK.

Responsibilities and behavior

  • Resolve service names and create gRPC channels for the resolved addresses.
  • Keep a small pool for each address to reuse connections. See max_free_channels_per_address.
  • Attach authorization credentials and manage token providers.
  • Get tokens with get_token or get_token_sync.
  • Return unary-unary RPC channels to the pool after use. See NebiusUnaryUnaryMultiCallable.
  • Support asynchronous and synchronous use.
  • Use async with Channel(...), close(), or sync_close() to release resources.

Important notes

  • By default the channel starts a dedicated daemon event-loop thread and a private daemon executor. All SDK asynchronous work uses that loop.
  • Awaitable SDK handles bridge their internal result into any caller loop.
  • A supplied event_loop must already be running. The caller owns it, and closing the channel does not stop or reconfigure it. Its default executor is caller-owned too; do not occupy every worker with blocking synchronous SDK calls because SDK extensions may need that executor.
  • Initialization connects token bearers, authorization providers, the idempotency interceptor, and a resolver.
  • Public methods include get_token, get_token_sync, run_sync, bg_task, get_channel_by_method, and create_address_channel.

Usage example

Async usage (recommended):

async with Channel(...) as channel:
    # Use the channel or give it to generated service clients.
    pass

Synchronous usage:

channel = Channel(...)
try:
    channel.run_sync(some_coroutine())
finally:
    channel.sync_close()
Parameters
resolverOptional custom Resolver used to resolve service names to concrete addresses. If omitted a Conventional resolver is used. If provided, it will be chained with the built-in resolver so both can be consulted.
substitutionsOptional mapping of template substitutions applied to resolved addresses. The construct inserts {"{domain}": domain} and then updates it with this mapping. Typical use is to override domain placeholders in generated service addresses.
user_agent_prefixOptional string prepended to the default SDK user-agent. The final user-agent string follows the pattern "<user_agent_prefix> nebius-python-sdk/<version> (python/X.Y.Z)". Recommended format: "my-app/1.0 (dependency-to-track/version; other-dependency)".
domainOptional domain for service addresses. If absent, the constructor calls config_reader.endpoint(). If that has no value, it uses the package DOMAIN constant.
optionsGlobal channel options passed to gRPC when creating address channels. This should follow the ChannelArgumentType shape (sequence of key/value tuples). The constructor copies the sequence; later caller mutations do not change channel behavior.
interceptorsGlobal list of gRPC ClientInterceptor instances that will be applied to all address channels. An idempotency-key interceptor is added by default; pass a list to extend or override additional behavior.
address_optionsOptional mapping from a resolved address to per-address channel options. Each value must follow the ChannelArgumentType shape (sequence of key/value tuples). If omitted an empty mapping is used. The constructor copies the mapping and each option sequence before SDK work can read them on another thread.
address_interceptorsOptional mapping from a resolved address to a sequence of per-address interceptors. Per-address interceptors are invoked in addition to the global interceptors. The constructor copies the mapping and each interceptor sequence.
credentials

Credentials can be provided in several forms:

  • None (default): attempts to read credentials from
    credentials_file_name, then from provided service account fields, then from config_reader.get_credentials(...), and finally falls back to an environment-backed bearer (nebius.aio.token.static.EnvBearer).
  • str or Token: treated as a
    static token and wrapped with a static bearer.
  • TokenBearer to use an existing token bearer as-is.
  • TokenRequester to exchange tokens on demand.
  • AuthorizationProvider: an explicit authorization provider
    (used rarely by advanced users).
  • NoCredentials: disables authorization entirely.

A supplied bearer or provider runs on this channel's SDK event loop. Custom implementations must be thread-safe and loop-neutral. Do not attach one stateful instance to SDKs with different loops. Create one credential object per SDK unless the implementation explicitly supports concurrent use and independent close calls.

Unsupported types raise SDKError.

service_account_idService account ID used when a private key file is supplied directly (alternate to using credentials_file_name). See the README for examples. If credentials is provided explicitly this parameter is ignored.
service_account_public_key_idPublic key ID corresponding to the private key file used for service-account authentication, as described in the README. If credentials is provided explicitly this parameter is ignored.
service_account_private_key_file_namePath to a PEM private key file. When provided with the key ID and service account ID fields above, the constructor wraps it in a service-account reader.
credentials_file_namePath to a credentials JSON file containing service-account information. If supplied this takes precedence over other implicit credential discovery (unless credentials is explicitly provided).
config_readerOptional nebius.aio.cli_config.Config instance used to populate defaults like domain, default parent ID, and to obtain credentials via the CLI-style configuration.
keepaliveOptional SDK gRPC keepalive configuration. By default the channel uses defaults compatible with the Nebius SDK for Go. It reads NEBIUS_GRPC_KEEPALIVE_* environment variables. Set False to disable SDK keepalive, or give nebius.aio.keepalive.KeepaliveOptions / a mapping with time_ms, timeout_ms and permit_without_stream overrides. Explicit keepalive options ignore the environment variables. Channel options and address_options apply later and can replace individual keepalive arguments.
metricsOptional callback object or mapping that receives both config-reader and authorization metrics. Callback names can use Python snake_case, such as token_acquire and credentials_resolve. camelCase names support compatibility with the TypeScript SDK.
auth_metricsOptional callback object or mapping that receives auth-only metrics. This is ignored when metrics is also provided because full metrics are used for auth callbacks too.
tls_credentialsOptional gRPC channel TLS credentials (ChannelCredentials). If omitted the constructor will load system root certificates via nebius.base.tls_certificates.get_system_certificates and create an SSL channel credentials object.
event_loopOptional already-running asyncio event loop used for all SDK work. The caller retains ownership: close does not stop the loop or replace its default executor. The caller must keep it running and responsive until close completes. Do not fill its default executor with synchronous SDK waits; work running on the loop may need the same executor, and the SDK cannot reliably identify arbitrary caller-owned executor threads. If omitted, the Channel eagerly starts and owns a dedicated daemon loop thread.
loop_exception_handlerOptional synchronous asyncio exception handler installed on the SDK event loop. Do not use an async def function. A synchronous wrapper must also return None instead of a coroutine or another awaitable. The SDK rejects directly recognizable async functions. If a synchronous handler returns any other value, the SDK closes a newly returned, unstarted native coroutine and reports both the original context and the contract violation through asyncio's default exception handler. It does not change a suspended coroutine, returned Future, Task, or opaque awaitable because the handler might not own that work. The SDK cannot know whether an invalid handler processed the original context, so default reporting can duplicate a diagnostic that the handler already emitted. The loop calls the handler with the loop and an exception context mapping. The handler runs on the loop thread and must return promptly. A blocking handler stops all work on that loop. On a supplied event_loop, the handler receives diagnostics from SDK work and other loop users. It replaces the loop's current handler and remains installed after SDK close. It starts receiving diagnostics after all other SDK initialization succeeds. It does not automatically call asyncio's default handler. A later successful assignment by another SDK or component replaces it. The context can contain sensitive data and objects owned by the event loop. Read loop-owned objects only on that loop. Copy and redact the required immutable fields before another thread processes them. Do not log or export the complete context without checking its contents. The handler can retain objects that it captures until another handler replaces it or the loop closes. Request and operation failures continue through their returned awaitables. The event loop stores an SDK forwarding callable for the handler, so get_exception_handler() does not have to return the same callable. Handler installation is the final SDK initialization action. If an asynchronous BaseException arrives after the loop accepts the handler but before the constructor returns, the handler can remain installed even though construction did not return a Channel. Construction from another thread waits up to 30 seconds for a supplied loop to install the handler.
executor_max_workersNumber of daemon workers in the private default executor attached to an SDK-owned loop. Defaults to 2. This setting is ignored when event_loop is supplied because the caller owns that loop and its executor configuration.
max_free_channels_per_addressNumber of free underlying gRPC channels to keep in the pool per resolved address. Defaults to 2. Lower values reduce resource usage but increase connection churn; larger values raise resource consumption.
parent_idOptional parent ID which will be automatically applied to many requests when left empty by the caller. If not provided and a config_reader is supplied the constructor will attempt to use config_reader.parent_id. An explicit empty string is treated as an error.
federation_invitation_writerOptional file-like writer passed to the config reader to display the URL for federation authentication during interactive credential acquisition.
federation_invitation_no_browser_openWhen using the config reader, set to True to avoid opening a web browser during interactive federation flows. Defaults to False.
Async Method __aenter__ Enter the async context manager.
Async Method __aexit__ Exit the async context manager.
Method __init__ Construct a new Channel.
Method bg_task Run an awaitable in the background.
Async Method channel_ready Channel is always ready, nothing to do here.
Async Method close Gracefully close the channel and all associated background work.
Method create_address_channel Create a new underlying gRPC channel for the given address.
Method discard_channel Dispose of an AddressChannel by scheduling its close.
Method get_addr_by_method Return the cached address for a fully-qualified RPC method name.
Method get_addr_by_route Resolve immutable generated route metadata without global descriptors.
Method get_addr_from_service_name Resolve a logical service name into a transport address.
Method get_addr_from_stub Resolve the concrete address for a generated service stub class.
Method get_address_interceptors Return the ordered list of interceptors to apply to a channel.
Method get_address_options Compute effective gRPC channel options for a specific address.
Method get_authorization_provider Return the configured AuthorizationProvider.
Method get_channel_by_addr Request an AddressChannel for the given resolved address.
Method get_channel_by_method Get an AddressChannel for an RPC method name.
Method get_channel_by_route Return a pooled channel selected from generated route metadata.
Method get_corresponding_operation_service Return an operations service stub for a generated service stub's address.
Method get_corresponding_operation_service_alpha Return an alpha-version operations stub for a generated service's address.
Method get_state Nebius Python SDK channels are always ready unless closed.
Async Method get_token Asynchronously fetch an authorization Token.
Method get_token_sync Get an authorization Token synchronously.
Method parent_id Return the channel-wide default parent ID used for certain requests.
Method release_channel Release an internal transport without masking a concurrent shutdown.
Method return_channel Return an AddressChannel to the internal pool.
Method run_async Submit SDK work to the channel's event loop.
Method run_sync Run an awaitable to completion on the channel's event loop.
Method stream_stream Nebius Python SDK does not support streaming RPCs.
Method stream_unary Nebius Python SDK does not support streaming RPCs.
Method sync_close Synchronously close the channel and wait for graceful shutdown.
Method unary_stream Nebius Python SDK does not support streaming RPCs.
Method unary_unary A method to support using SDK channel as gRPC Channel.
Async Method wait_for_state_change Nebius Python SDK channels are always ready unless closed.
Instance Variable user_agent The user-agent string used by channels created by this Channel instance.
Static Method _registry_for_service Undocumented
Method _check_process Reject a channel inherited from another process before locking.
Async Method _close_address_channel Close a pooled transport on its owner loop when that loop is running.
Async Method _close_internal Close SDK resources without stopping the runtime.
Method _configure_metrics_on_config_reader Undocumented
Async Method _create_address_channel Create an address channel on the SDK event loop.
Method _create_address_channel_internal Create a configured gRPC channel without loop dispatch.
Method _discard_background_task Remove completed background work from channel tracking.
Async Method _get_addr_by_method Resolve and cache a method address on the SDK event loop.
Method _get_addr_by_method_internal Resolve and cache a method address without loop dispatch.
Async Method _get_addr_by_route Resolve and cache a generated route on the SDK event loop.
Method _get_addr_by_route_internal Resolve and cache generated route metadata without loop dispatch.
Async Method _get_addr_from_service_name Resolve a service name on the SDK event loop.
Method _get_addr_from_service_name_internal Normalize and resolve a service name without loop dispatch.
Async Method _get_channel_by_addr Lease an address channel on the SDK event loop.
Method _get_channel_by_addr_internal Lease or create an address channel without loop dispatch.
Method _get_close_handle Return the single channel cleanup submission.
Method _get_runtime_authorization_provider Return a private provider that uses the SDK event loop.
Async Method _get_token_internal Get a token on the SDK event loop.
Async Method _get_token_with_deadline Fetch a token within a deadline captured on the caller thread.
Method _has_authorization_provider Return whether requests use this channel's fixed auth provider.
Method _is_config_metrics_aware_config_reader Undocumented
Method _lease_address_channel Track a checked-out transport or retire it if shutdown won the race.
Method _release_address_channel Undocumented
Async Method _release_address_channel_async Release an address channel from an SDK-loop coroutine.
Method _release_channel_on_sdk_loop Release a channel on the SDK loop or dispatch the release to it.
Method _release_channel_soon Schedule transport release without blocking the caller thread.
Method _run_sdk_callable Call a function on the SDK event loop.
Method _schedule_address_channel_close Schedule and retain an SDK-loop transport close until it finishes.
Method _shutdown_after_internal_caller Start shutdown after an internal close caller can return.
Instance Variable _address_interceptors Undocumented
Instance Variable _address_options Undocumented
Instance Variable _auth_metrics Undocumented
Instance Variable _authorization_provider Undocumented
Instance Variable _channel_lifecycle_ready Undocumented
Instance Variable _channel_pool_lock Undocumented
Instance Variable _close_completion Undocumented
Instance Variable _close_handle Undocumented
Instance Variable _close_submit_lock Undocumented
Instance Variable _close_task Undocumented
Instance Variable _closed Undocumented
Instance Variable _event_loop Undocumented
Instance Variable _free_channels Undocumented
Instance Variable _global_interceptors Undocumented
Instance Variable _global_interceptors_inner Undocumented
Instance Variable _global_options Undocumented
Instance Variable _gracefuls Undocumented
Instance Variable _keepalive_config Undocumented
Instance Variable _leased_channels Undocumented
Instance Variable _max_free_channels_per_address Undocumented
Instance Variable _methods Undocumented
Instance Variable _metrics Undocumented
Instance Variable _parent_id Undocumented
Instance Variable _process_id Undocumented
Instance Variable _resolver Undocumented
Instance Variable _route_custom_resolver Undocumented
Instance Variable _route_substitutions Undocumented
Instance Variable _routes Undocumented
Instance Variable _runtime Undocumented
Instance Variable _runtime_finalizer Undocumented
Instance Variable _tasks Undocumented
Instance Variable _tasks_lock Undocumented
Instance Variable _tls_credentials Undocumented
Instance Variable _token_bearer Undocumented
Instance Variable _transport_closes Undocumented
async def __aenter__(self) -> Channel: (source)

Enter the async context manager.

Returns self to allow usage like:

async with channel as chan:
    await chan.some_method()

Will close the channel on exit.

async def __aexit__(self, exc_type: Any, exc_val: Any, exc_tb: Any): (source)

Exit the async context manager.

Calls close() to gracefully shut down resources.

@_shutdown_runtime_on_init_failure
def __init__(self, *, resolver: Resolver | None = None, substitutions: dict[str, str] | None = None, user_agent_prefix: str | None = None, domain: str | None = None, options: ChannelArgumentType | None = None, interceptors: Sequence[ClientInterceptor] | None = None, address_options: dict[str, ChannelArgumentType] | None = None, address_interceptors: dict[str, Sequence[ClientInterceptor]] | None = None, credentials: Credentials = None, service_account_id: str | None = None, service_account_public_key_id: str | None = None, service_account_private_key_file_name: str | Path | None = None, credentials_file_name: str | Path | None = None, config_reader: ConfigReader | None = None, keepalive: KeepaliveOptions | Mapping[str, object] | bool | None = None, metrics: MetricsLike = None, auth_metrics: AuthMetricsLike = None, tls_credentials: ChannelCredentials | None = None, event_loop: AbstractEventLoop | None = None, loop_exception_handler: LoopExceptionHandler | None = None, executor_max_workers: int = 2, max_free_channels_per_address: int = 2, parent_id: str | None = None, federation_invitation_writer: TextIO | None = None, federation_invitation_no_browser_open: bool = False): (source)

Construct a new Channel.

The constructor connects gRPC channel management, credential providers, resolvers, TLS configuration, and interceptors.

The channel resolves logical service names to transport addresses. It creates and pools gRPC channels. It also supplies synchronous and asynchronous methods.

Notes

  • The constructor performs several discovery steps for credentials in the following precedence order when credentials is None: 1. credentials_file_name reader 2. service-account PEM reader (when id/key args are provided) 3. config_reader.get_credentials(...) 4. environment-backed bearer (EnvBearer)
  • The constructor wraps token readers in exchangeable and renewable bearers. These bearers refresh tokens in the background.
  • The channel adds each bearer to its shutdown set. close stops their background tasks.

Examples

Typical, minimal construction that reads token from environment:

>>> channel = Channel()

Using explicit static token:

>>> channel = Channel(credentials="MY_TOKEN")

Creating channel from CLI config and a custom resolver:

>>> from nebius.aio.cli_config import Config
>>> channel = Channel(config_reader=Config(), resolver=my_resolver)
Raises
SDKErrorRaised for unsupported credential types or if parent_id is an explicitly empty string.
TypeErrorRaised if loop_exception_handler is not a synchronous callable.
RuntimeErrorRaised if a supplied event loop stops or does not install loop_exception_handler before the time limit.
def bg_task(self, coro: Awaitable[T]) -> CrossLoopAwaitable[None]: (source)

Run an awaitable in the background.

The channel tracks the returned awaitable and cancels it during close. The method logs exceptions other than cancellation. The result is not an asyncio.Task; wrap it with asyncio.ensure_future before passing it to asyncio.wait.

Parameters
coro:Awaitable[T]Work to run in the background.
Returns
CrossLoopAwaitable[None]Cross-loop awaitable that completes after the background work.
async def channel_ready(self): (source)

Channel is always ready, nothing to do here.

async def close(self, grace: float | None = None): (source)

Gracefully close the channel and all associated background work.

The channel stops supplying address channels. It closes pooled gRPC channels and registered GracefulInterface objects, such as token bearers. It cancels tasks from bg_task and logs shutdown exceptions. For compatibility, individual resource-close failures are best-effort and logged after all cleanup has been attempted; failures of the SDK runtime's own finalization are propagated.

A custom transport can belong to a different caller-owned event loop. This method retires that transport and schedules its close on the owner loop, but it does not wait for that loop. Keep the owner loop running and able to process callbacks until the transport close finishes.

Parameters
grace:optional floatOptional per-transport grace period passed to underlying channel close methods.
Raises
LoopErrorIf called from an SDK-owned executor worker. Such a worker cannot wait for shutdown of the finite pool it belongs to.
def create_address_channel(self, addr: str) -> AddressChannel: (source)

Create a new underlying gRPC channel for the given address.

The method combines options and interceptors. It extracts special options such as INSECURE and COMPRESSION. Then, it constructs a secure or insecure gRPC channel wrapper. The returned AddressChannel contains the gRPC channel and resolved address.

Parameters
addr:strResolved address string.
Returns
AddressChannelAn AddressChannel containing the created channel.
Raises
LoopErrorIf called from an active event loop or an SDK-owned executor worker.
def discard_channel(self, chan: AddressChannel | None): (source)

Dispose of an AddressChannel by scheduling its close.

The close is performed asynchronously on the transport's owner loop without blocking the caller.

Parameters
chan:AddressChannel | NoneThe AddressChannel to discard, or None.
Raises
ChannelClosedErrorIf the SDK channel has been closed.
LoopErrorIf called from an active event loop or an SDK-owned executor worker.
def get_addr_by_method(self, method_name: str) -> str: (source)

Return the cached address for a fully-qualified RPC method name.

For a new method, call service_from_method_name to get its service. Then, resolve it with get_addr_from_service_name and cache the result.

Parameters
method_name:strFull RPC method string ('/package.service/Method').
Returns
strResolved address string.
Raises
LoopErrorIf called from an active event loop or an SDK-owned executor worker.
def get_addr_by_route(self, route: Route) -> str: (source)

Resolve immutable generated route metadata without global descriptors.

Parameters
route:RouteGenerated route metadata.
Returns
strResolved address string.
Raises
LoopErrorIf called from an active event loop or an SDK-owned executor worker.
def get_addr_from_service_name(self, service_name: str) -> str: (source)

Resolve a logical service name into a transport address.

The method strips a leading dot (".") if present and delegates to the configured Resolver.

Parameters
service_name:strLogical service name as generated by stubs or conventions.
Returns
strResolved address string.
Raises
LoopErrorIf called from an active event loop or an SDK-owned executor worker.
def get_addr_from_stub(self, service_stub_class: type[ServiceStub]) -> str: (source)

Resolve the concrete address for a generated service stub class.

Parameters
service_stub_class:type[ServiceStub]The generated gRPC stub class for a service.
Returns
strThe resolved address string used by the SDK to reach that service (for example 'host:port' or a resolver template expanded value).
Raises
LoopErrorIf called from an active event loop or an SDK-owned executor worker.
def get_address_interceptors(self, addr: str) -> Sequence[ClientInterceptor]: (source)

Return the ordered list of interceptors to apply to a channel.

Global interceptors are applied first, then any per-address interceptors, and finally internal interceptors added by the channel implementation.

Parameters
addr:strResolved address string.
Returns
A sequence of ClientInterceptorCombined global and per-address interceptors.
def get_address_options(self, addr: str) -> ChannelArgumentType: (source)

Compute effective gRPC channel options for a specific address.

Global options are combined with per-address options and the SDK user-agent is appended via grpc.primary_user_agent.

Parameters
addr:strResolved address string.
Returns
list of tuple[str, Any]A sequence of channel option tuples ready to be passed to gRPC when creating a channel.
def get_authorization_provider(self) -> AuthorizationProvider | None: (source)

Return the configured AuthorizationProvider.

Returns
AuthorizationProvider or NoneThe authorization provider instance if any authorization mechanism was configured; otherwise None.
def get_channel_by_addr(self, addr: str) -> AddressChannel: (source)

Request an AddressChannel for the given resolved address.

The method returns a pooled channel if available; otherwise a new underlying gRPC channel is created. Pooled channels with state grpc.ChannelConnectivity.SHUTDOWN are closed asynchronously and skipped.

Warning

AddressChannel.channel is a native grpc.aio.Channel owned by the SDK loop. Direct calls on it are loop-affine. Use generated clients or unary_unary for cross-loop call handling.

Parameters
addr:strResolved address string.
Returns
AddressChannelAn AddressChannel wrapper for a gRPC channel.
Raises
ChannelClosedErrorIf the SDK channel has already been closed.
LoopErrorIf called from an active event loop or an SDK-owned executor worker.
def get_channel_by_method(self, method_name: str) -> AddressChannel: (source)

Get an AddressChannel for an RPC method name.

The method resolves the address via get_addr_by_method and then calls get_channel_by_addr to obtain the channel.

Parameters
method_name:strFull RPC method string.
Returns
AddressChannelAn AddressChannel bound to the resolved address.
def get_channel_by_route(self, route: Route) -> AddressChannel: (source)

Return a pooled channel selected from generated route metadata.

def get_corresponding_operation_service(self, service_stub_class: type[ServiceStub]) -> OperationServiceTransportStub: (source)

Return an operations service stub for a generated service stub's address.

Long-running operations are associated with their source service. This method returns an OperationServiceStub that resolves the generated stub's source service on the SDK event loop when its first call starts, then reuses that address for the lifetime of the returned adapter. Deferring resolution keeps this synchronous factory safe to call from asynchronous application code without blocking either event loop; retaining it keeps every poll for one operation on the same endpoint.

Parameters
service_stub_class:type[ServiceStub]Generated gRPC service stub class (the SDK service descriptor type).
Returns
OperationServiceStubAn operations service stub bound to the same backend used by the provided service.
def get_corresponding_operation_service_alpha(self, service_stub_class: type[ServiceStub]) -> OperationServiceTransportStub: (source)

Return an alpha-version operations stub for a generated service's address.

See get_corresponding_operation_service for details. This method returns the older alpha operations stub for callers that need to interoperate with legacy server implementations.

def get_state(self, try_to_connect: bool = False) -> ChannelConnectivity: (source)

Nebius Python SDK channels are always ready unless closed.

Parameters
try_to_connect:boolIgnored parameter to satisfy the gRPC Channel interface.
Returns
grpc.ChannelConnectivitygrpc.ChannelConnectivity.READY if the channel is open, grpc.ChannelConnectivity.SHUTDOWN if closed.
async def get_token(self, timeout: float | None, options: dict[str, str] | None = None) -> Token: (source)

Asynchronously fetch an authorization Token.

This helper delegates to the configured token bearer and performs any necessary refresh or exchange logic implemented by the bearer, if any was configured. If no bearer was configured, the method raises SDKError.

Parameters
timeout:optional floatMaximum time in seconds to wait for a token, including dispatch to the SDK loop. If None the operation may block indefinitely according to the bearer semantics.
options:optional dict[str, str]Optional mapping of string options passed to the underlying token receiver.
Returns
TokenA Token instance containing the access token.
Raises
ValueErrorIf timeout is NaN or infinite. Use None for an unlimited timeout.
SDKErrorIf no token bearer was configured on the channel.
def get_token_sync(self, timeout: float | None, options: dict[str, str] | None = None) -> Token: (source)

Get an authorization Token synchronously.

This method runs get_token on the channel event loop. It blocks the calling thread until a token is available or time expires.

A small grace period is added to the supplied timeout to allow the internal token bearer shutdown logic to complete during immediate handoff. The method copies options before it dispatches work, so a later caller-side change does not affect the token request.

Parameters
timeout:optional floatMaximum time in seconds to wait for a token; may be None to wait indefinitely.
options:optional dict[str, str]Optional mapping of string options passed to the underlying token receiver.
Returns
TokenA Token instance.
Raises
TimeoutErrorIf the token could not be obtained within the supplied timeout.
def parent_id(self) -> str | None: (source)

Return the channel-wide default parent ID used for certain requests.

Some SDK methods automatically populate a parent_id field when missing using this channel-level default. The value may be None if not configured.

Returns
str | NoneThe configured parent ID or None.
def release_channel(self, chan: AddressChannel | None, *, discard: bool = False): (source)

Release an internal transport without masking a concurrent shutdown.

Generated request and stream paths use this method so a ChannelClosedError raised during cleanup cannot replace the RPC result or its original error. Direct callers of return_channel and discard_channel retain their previous closed-channel error.

def return_channel(self, chan: AddressChannel | None): (source)

Return an AddressChannel to the internal pool.

Later get_channel_by_addr calls reuse channels in the pool. The pool keeps at most max_free_channels_per_address channels. The method closes excess or stopped channels asynchronously.

Parameters
chan:AddressChannel | NoneThe AddressChannel to return, or None.
Raises
ChannelClosedErrorIf the SDK channel has been closed.
LoopErrorIf called from an active event loop or an SDK-owned executor worker.
def run_async(self, awaitable: Awaitable[T]) -> CrossLoopAwaitable[T]: (source)

Submit SDK work to the channel's event loop.

The returned awaitable is backed by a thread-safe concurrent future, so callers can await it from the SDK loop or from an external event loop.

Parameters
awaitable:Awaitable[T]Work to run on the SDK event loop.
Returns
CrossLoopAwaitable[T]Cross-loop awaitable for the result.
Raises
ChannelClosedErrorIf channel close has started.
def run_sync(self, awaitable: Awaitable[T], timeout: float | None = None) -> T: (source)

Run an awaitable to completion on the channel's event loop.

This method blocks the calling thread. It rejects calls from the SDK event loop and from any other running event loop. Async callers must await the cross-loop handle so their loop can continue making progress.

Parameters
awaitable:Awaitable[T]The awaitable to run to completion.
timeout:float | NoneOptional maximum wait time in seconds.
Returns
TThe awaitable's result.
Raises
LoopErrorIf the caller runs in any asynchronous context or is any SDK-owned executor worker.
ValueErrorIf timeout is NaN or infinite. Use None for an unlimited timeout.
TimeoutErrorIf the time limit expires.
def stream_stream(self, method: str, request_serializer: SerializingFunction | None = None, response_deserializer: DeserializingFunction | None = None) -> StreamStreamMultiCallable: (source)

Nebius Python SDK does not support streaming RPCs.

Raises
NotImplementedError
def stream_unary(self, method: str, request_serializer: SerializingFunction | None = None, response_deserializer: DeserializingFunction | None = None) -> StreamUnaryMultiCallable: (source)

Nebius Python SDK does not support streaming RPCs.

Raises
NotImplementedError
def sync_close(self, timeout: float | None = None): (source)

Synchronously close the channel and wait for graceful shutdown.

This method calls close and blocks until shutdown is complete or time expires.

Parameters
timeout:optional floatOptional timeout in seconds for the shutdown.
Raises
LoopErrorIf called from the SDK event loop, an asynchronous context, or an SDK-owned executor worker.
ValueErrorIf timeout is NaN or infinite. Use None for an unlimited timeout.
TimeoutErrorIf the shutdown did not complete within the supplied timeout.
def unary_stream(self, method: str, request_serializer: SerializingFunction | None = None, response_deserializer: DeserializingFunction | None = None) -> UnaryStreamMultiCallable[Req, Res]: (source)

Nebius Python SDK does not support streaming RPCs.

Raises
NotImplementedError
def unary_unary(self, method_name: str, request_serializer: SerializingFunction | None = None, response_deserializer: DeserializingFunction | None = None) -> UnaryUnaryMultiCallable[Req, Res]: (source)

A method to support using SDK channel as gRPC Channel.

Parameters
method_name:strFull RPC method string, i.e., '/package.service/method'.
request_serializer:SerializingFunction | NoneA function that serializes a request message to bytes.
response_deserializer:DeserializingFunction | NoneA function that deserializes a response message from bytes.
Returns
NebiusUnaryUnaryMultiCallable wrapper.A UnaryUnaryMultiCallable object that can be used to make the call.
async def wait_for_state_change(self, last_observed_state: ChannelConnectivity): (source)

Nebius Python SDK channels are always ready unless closed.

This method is provided to satisfy the gRPC Channel interface.

Raises
NotImplementedError
user_agent = (source)

The user-agent string used by channels created by this Channel instance.

@staticmethod
def _registry_for_service(service_stub_class: type[ServiceStub]) -> Registry: (source)

Undocumented

def _check_process(self, awaitable: Awaitable[Any] | None = None): (source)

Reject a channel inherited from another process before locking.

After fork, inherited Python locks may be permanently owned by vanished threads. gRPC and event-loop state is not reusable. An application must fork before it creates SDK or gRPC objects. It must create separate SDK objects after each child starts.

Parameters
awaitable:Awaitable[Any] | NoneOptional coroutine to close when rejecting it.
Raises
RuntimeErrorIf this process did not create the channel.
async def _close_address_channel(self, chan: AddressChannel, grace: float | None): (source)

Close a pooled transport on its owner loop when that loop is running.

async def _close_internal(self, grace: float | None = None): (source)

Close SDK resources without stopping the runtime.

Parameters
grace:float | NoneOptional transport close period in seconds.
def _configure_metrics_on_config_reader(self, config_reader: ConfigReader): (source)

Undocumented

async def _create_address_channel(self, addr: str) -> AddressChannel: (source)

Create an address channel on the SDK event loop.

Parameters
addr:strResolved transport address.
Returns
AddressChannelNew address channel.
def _create_address_channel_internal(self, addr: str) -> AddressChannel: (source)

Create a configured gRPC channel without loop dispatch.

The new channel records the current SDK event loop as its owner.

Parameters
addr:strResolved transport address.
Returns
AddressChannelNew address channel.
def _discard_background_task(self, task: CrossLoopAwaitable[Any]): (source)

Remove completed background work from channel tracking.

Parameters
task:CrossLoopAwaitable[Any]Completed background submission.
async def _get_addr_by_method(self, method_name: str) -> str: (source)

Resolve and cache a method address on the SDK event loop.

Parameters
method_name:strFully qualified RPC method name.
Returns
strResolved transport address.
def _get_addr_by_method_internal(self, method_name: str) -> str: (source)

Resolve and cache a method address without loop dispatch.

Parameters
method_name:strFully qualified RPC method name.
Returns
strResolved transport address.
async def _get_addr_by_route(self, route: Route) -> str: (source)

Resolve and cache a generated route on the SDK event loop.

Parameters
route:RouteGenerated route metadata.
Returns
strResolved transport address.
def _get_addr_by_route_internal(self, route: Route) -> str: (source)

Resolve and cache generated route metadata without loop dispatch.

Parameters
route:RouteGenerated route metadata.
Returns
strResolved transport address.
async def _get_addr_from_service_name(self, service_name: str) -> str: (source)

Resolve a service name on the SDK event loop.

Parameters
service_name:strLogical service name.
Returns
strResolved transport address.
def _get_addr_from_service_name_internal(self, service_name: str) -> str: (source)

Normalize and resolve a service name without loop dispatch.

Parameters
service_name:strLogical service name.
Returns
strResolved transport address.
async def _get_channel_by_addr(self, addr: str) -> AddressChannel: (source)

Lease an address channel on the SDK event loop.

Parameters
addr:strResolved transport address.
Returns
AddressChannelLeased address channel.
def _get_channel_by_addr_internal(self, addr: str) -> AddressChannel: (source)

Lease or create an address channel without loop dispatch.

The method reuses only a channel that belongs to the SDK event loop. It schedules stopped pooled channels for closure.

Parameters
addr:strResolved transport address.
Returns
AddressChannelLeased address channel.
Raises
ChannelClosedErrorIf channel shutdown has started.
def _get_close_handle(self, grace: float | None) -> CrossLoopAwaitable[None]: (source)

Return the single channel cleanup submission.

Parameters
grace:float | NoneOptional transport close period in seconds.
Returns
CrossLoopAwaitable[None]Cross-loop awaitable for channel cleanup.
def _get_runtime_authorization_provider(self) -> AuthorizationProvider | None: (source)

Return a private provider that uses the SDK event loop.

async def _get_token_internal(self, deadline: float | None, options: dict[str, str] | None = None) -> Token: (source)

Get a token on the SDK event loop.

Parameters
deadline:float | NoneAbsolute monotonic deadline that includes caller-side SDK-loop dispatch, or None for no limit.
options:dict[str, str] | NoneOptional token receiver settings.
Returns
TokenAuthorization token.
Raises
SDKErrorIf the channel has no token bearer.
async def _get_token_with_deadline(self, deadline: float | None, options: dict[str, str] | None) -> Token: (source)

Fetch a token within a deadline captured on the caller thread.

Parameters
deadline:float | NoneAbsolute monotonic deadline that includes dispatch to the SDK loop, or None for no limit.
options:dict[str, str] | NoneSnapshot of the token receiver settings.
Returns
TokenAuthorization token.
Raises
TimeoutErrorIf dispatch or token retrieval exceeds the deadline.
def _has_authorization_provider(self) -> bool: (source)

Return whether requests use this channel's fixed auth provider.

The query is safe from caller threads because the provider reference is fixed during channel construction. It lets cross-loop wrappers decide whether an authorization-only deadline applies without constructing an authenticator or running authorization work outside the SDK loop.

Returns
boolTrue when the channel has an authorization provider.
def _is_config_metrics_aware_config_reader(self, config_reader: ConfigReader) -> bool: (source)

Undocumented

def _lease_address_channel(self, chan: AddressChannel) -> AddressChannel: (source)

Track a checked-out transport or retire it if shutdown won the race.

def _release_address_channel(self, chan: AddressChannel | None, *, discard: bool, raise_if_closed: bool): (source)

Undocumented

async def _release_address_channel_async(self, chan: AddressChannel | None, *, discard: bool, raise_if_closed: bool): (source)

Release an address channel from an SDK-loop coroutine.

Parameters
chan:AddressChannel | NoneAddress channel to release. Use None for no action.
discard:boolClose the channel instead of returning it to the pool.
raise_if_closed:boolRaise when SDK channel shutdown has started.
Raises
ChannelClosedErrorIf shutdown has started and raise_if_closed is True.
def _release_channel_on_sdk_loop(self, chan: AddressChannel | None, *, discard: bool, raise_if_closed: bool): (source)

Release a channel on the SDK loop or dispatch the release to it.

Parameters
chan:AddressChannel | NoneAddress channel to release. Use None for no action.
discard:boolClose the channel instead of returning it to the pool.
raise_if_closed:boolRaise when SDK channel shutdown has started.
Raises
ChannelClosedErrorIf shutdown has started and raise_if_closed is True.
def _release_channel_soon(self, chan: AddressChannel | None, *, discard: bool = False): (source)

Schedule transport release without blocking the caller thread.

Parameters
chan:AddressChannel | NoneAddress channel to release. Use None for no action.
discard:boolClose the channel instead of returning it to the pool.
def _run_sdk_callable(self, callable_: Callable[..., T], *args: Any) -> T: (source)

Call a function on the SDK event loop.

Parameters
callable_:Callable[..., T]Function to call.
*args:AnyPositional arguments for callable_.
Returns
TResult of callable_.
def _schedule_address_channel_close(self, chan: AddressChannel, grace: float | None, *, already_retired: bool = False): (source)

Schedule and retain an SDK-loop transport close until it finishes.

A transport explicitly owned by another loop remains that loop's lifecycle responsibility. Its close is dispatched there but is not allowed to make SDK shutdown depend on a caller-owned loop.

def _shutdown_after_internal_caller(self, current_submission: CrossLoopAwaitable[Any] | None, closing: CrossLoopAwaitable[Any] | None = None): (source)

Start shutdown after an internal close caller can return.

Parameters
current_submission:CrossLoopAwaitable[Any] | NoneInternal submission that called close.
closing:CrossLoopAwaitable[Any] | NoneOptional channel cleanup submission.
_address_interceptors = (source)

Undocumented

_address_options = (source)

Undocumented

_auth_metrics = (source)

Undocumented

_authorization_provider: AuthorizationProvider | None = (source)

Undocumented

_channel_lifecycle_ready: bool = (source)

Undocumented

_channel_pool_lock = (source)

Undocumented

_close_completion: ConcurrentFuture[None] | None = (source)

Undocumented

_close_handle: CrossLoopAwaitable[None] | None = (source)

Undocumented

_close_submit_lock = (source)

Undocumented

_close_task: Task[None] | None = (source)

Undocumented

Undocumented

_event_loop = (source)

Undocumented

_free_channels = (source)

Undocumented

_global_interceptors: list[ClientInterceptor] = (source)

Undocumented

_global_interceptors_inner: list[ClientInterceptor] = (source)

Undocumented

_global_options = (source)

Undocumented

_gracefuls = (source)

Undocumented

_keepalive_config = (source)

Undocumented

_leased_channels = (source)

Undocumented

_max_free_channels_per_address = (source)

Undocumented

_methods = (source)

Undocumented

_metrics = (source)

Undocumented

_parent_id = (source)

Undocumented

_process_id = (source)

Undocumented

Undocumented

_route_custom_resolver: Resolver | None = (source)

Undocumented

_route_substitutions = (source)

Undocumented

Undocumented

_runtime = (source)

Undocumented

_runtime_finalizer = (source)

Undocumented

Undocumented

_tasks_lock = (source)

Undocumented

_tls_credentials = (source)

Undocumented

_token_bearer: TokenBearer | None = (source)

Undocumented

_transport_closes = (source)

Undocumented