Skip to content

Commit

Permalink
Use ContextVar for default bus
Browse files Browse the repository at this point in the history
  • Loading branch information
igo95862 committed Jun 11, 2022
1 parent a9c2534 commit 1535f65
Show file tree
Hide file tree
Showing 2 changed files with 11 additions and 14 deletions.
6 changes: 3 additions & 3 deletions docs/general.rst
Original file line number Diff line number Diff line change
Expand Up @@ -133,8 +133,8 @@ Default bus
++++++++++++++++++++++++++

Most object methods that take a bus as a parameter
will use a default bus connection if a bus object is
not explicitly passed.
will use a thread-local default bus connection if a bus object
is not explicitly passed.

Session bus is default bus when running as a user and
system bus otherwise.
Expand Down Expand Up @@ -167,4 +167,4 @@ Contents
++++++++++++++++++++
* :ref:`genindex`
* :doc:`/api_index`
* :ref:`search`
* :ref:`search`
19 changes: 8 additions & 11 deletions src/sdbus/dbus_common_funcs.py
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,8 @@
from __future__ import annotations

from asyncio import get_running_loop
from typing import Iterator, Optional
from contextvars import ContextVar
from typing import Iterator

from .sd_bus_internals import (
DbusPropertyConstFlag,
Expand All @@ -32,7 +33,7 @@
sd_bus_open,
)

DEFAULT_BUS: Optional[SdBus] = None
DEFAULT_BUS: ContextVar[SdBus] = ContextVar('DEFAULT_BUS')

PROPERTY_FLAGS_MASK = (
DbusPropertyConstFlag | DbusPropertyEmitsChangeFlag |
Expand All @@ -50,20 +51,16 @@ def _is_property_flags_correct(flags: int) -> bool:


def get_default_bus() -> SdBus:
global DEFAULT_BUS
old_bus = DEFAULT_BUS
if old_bus is None:
try:
return DEFAULT_BUS.get()
except LookupError:
new_bus = sd_bus_open()
DEFAULT_BUS = new_bus
DEFAULT_BUS.set(new_bus)
return new_bus
else:
return old_bus


def set_default_bus(new_default: SdBus) -> None:
global DEFAULT_BUS

DEFAULT_BUS = new_default
DEFAULT_BUS.set(new_default)


async def request_default_bus_name_async(
Expand Down

0 comments on commit 1535f65

Please sign in to comment.