trio API Reference

Friendly Python library for async concurrency and I/O designed around structured concurrency.

trio.BrokenResourceError
Python Library Documentation: class BrokenResourceError in module trio

class BrokenResourceError(builtins.Exception)
 |  Raised when an attempt to use a resource fails due to external
 |  circumstances.
 |
 |  For example, you might get this if you try to send data on a stream where
 |  the remote side has already closed the connection.
 |
 |  You *don't* get this error if *you* closed the resource – in that case you
 |  get :class:`ClosedResourceError`.
 |
 |  This exception's ``__cause__`` attribute will often contain more
 |  information about the underlying error.
 |
 |  Method resolution order:
 |      BrokenResourceError
 |      builtins.Exception
 |      builtins.BaseException
 |      builtins.object
 |
 |  Data descriptors defined here:
 |
 |  __weakref__
 |      list of weak references to the object
 |
 |  ----------------------------------------------------------------------
 |  Methods inherited from builtins.Exception:
 |
 |  __init__(self, /, *args, **kwargs)
 |      Initialize self.  See help(type(self)) for accurate signature.
 |
 |  ----------------------------------------------------------------------
 |  Static methods inherited from builtins.Exception:
 |
 |  __new__(*args, **kwargs) class method of builtins.Exception
 |      Create and return a new object.  See help(type) for accurate signature.
 |
 |  ----------------------------------------------------------------------
 |  Methods inherited from builtins.BaseException:
 |
 |  __getattribute__(self, name, /)
 |      Return getattr(self, name).
 |
 |  __reduce__(...)
 |      Helper for pickle.
 |
 |  __repr__(self, /)
 |      Return repr(self).
 |
 |  __setstate__(...)
 |
 |  __str__(self, /)
 |      Return str(self).
 |
 |  add_note(...)
 |      Exception.add_note(note) --
 |      add a note to the exception
 |
 |  with_traceback(...)
 |      Exception.with_traceback(tb) --
 |      set self.__traceback__ to tb and return self.
 |
 |  ----------------------------------------------------------------------
 |  Data descriptors inherited from builtins.BaseException:
 |
 |  __cause__
 |      exception cause
 |
 |  __context__
 |      exception context
 |
 |  __dict__
 |
 |  __suppress_context__
 |
 |  __traceback__
 |
 |  args
trio.BusyResourceError
Python Library Documentation: class BusyResourceError in module trio

class BusyResourceError(builtins.Exception)
 |  Raised when a task attempts to use a resource that some other task is
 |  already using, and this would lead to bugs and nonsense.
 |
 |  For example, if two tasks try to send data through the same socket at the
 |  same time, Trio will raise :class:`BusyResourceError` instead of letting
 |  the data get scrambled.
 |
 |  Method resolution order:
 |      BusyResourceError
 |      builtins.Exception
 |      builtins.BaseException
 |      builtins.object
 |
 |  Data descriptors defined here:
 |
 |  __weakref__
 |      list of weak references to the object
 |
 |  ----------------------------------------------------------------------
 |  Methods inherited from builtins.Exception:
 |
 |  __init__(self, /, *args, **kwargs)
 |      Initialize self.  See help(type(self)) for accurate signature.
 |
 |  ----------------------------------------------------------------------
 |  Static methods inherited from builtins.Exception:
 |
 |  __new__(*args, **kwargs) class method of builtins.Exception
 |      Create and return a new object.  See help(type) for accurate signature.
 |
 |  ----------------------------------------------------------------------
 |  Methods inherited from builtins.BaseException:
 |
 |  __getattribute__(self, name, /)
 |      Return getattr(self, name).
 |
 |  __reduce__(...)
 |      Helper for pickle.
 |
 |  __repr__(self, /)
 |      Return repr(self).
 |
 |  __setstate__(...)
 |
 |  __str__(self, /)
 |      Return str(self).
 |
 |  add_note(...)
 |      Exception.add_note(note) --
 |      add a note to the exception
 |
 |  with_traceback(...)
 |      Exception.with_traceback(tb) --
 |      set self.__traceback__ to tb and return self.
 |
 |  ----------------------------------------------------------------------
 |  Data descriptors inherited from builtins.BaseException:
 |
 |  __cause__
 |      exception cause
 |
 |  __context__
 |      exception context
 |
 |  __dict__
 |
 |  __suppress_context__
 |
 |  __traceback__
 |
 |  args
trio.CancelScope
Python Library Documentation: class CancelScope in module trio

class CancelScope(builtins.object)
 |  CancelScope(*, relative_deadline: 'float' = inf, deadline: 'float' = inf, shield: 'bool' = False) -> None
 |
 |  A *cancellation scope*: the link between a unit of cancellable
 |  work and Trio's cancellation system.
 |
 |  A :class:`CancelScope` becomes associated with some cancellable work
 |  when it is used as a context manager surrounding that work::
 |
 |      cancel_scope = trio.CancelScope()
 |      ...
 |      with cancel_scope:
 |          await long_running_operation()
 |
 |  Inside the ``with`` block, a cancellation of ``cancel_scope`` (via
 |  a call to its :meth:`cancel` method or via the expiry of its
 |  :attr:`deadline`) will immediately interrupt the
 |  ``long_running_operation()`` by raising :exc:`Cancelled` at its
 |  next :ref:`checkpoint <checkpoints>`.
 |
 |  The context manager ``__enter__`` returns the :class:`CancelScope`
 |  object itself, so you can also write ``with trio.CancelScope() as
 |  cancel_scope:``.
 |
 |  If a cancel scope becomes cancelled before entering its ``with`` block,
 |  the :exc:`Cancelled` exception will be raised at the first
 |  checkpoint inside the ``with`` block. This allows a
 |  :class:`CancelScope` to be created in one :ref:`task <tasks>` and
 |  passed to another, so that the first task can later cancel some work
 |  inside the second.
 |
 |  Cancel scopes are not reusable or reentrant; that is, each cancel
 |  scope can be used for at most one ``with`` block.  (You'll get a
 |  :exc:`RuntimeError` if you violate this rule.)
 |
 |  The :class:`CancelScope` constructor takes initial values for the
 |  cancel scope's :attr:`deadline` and :attr:`shield` attributes; these
 |  may be freely modified after construction, whether or not the scope
 |  has been entered yet, and changes take immediate effect.
 |
 |  Methods defined here:
 |
 |  __attrs_post_init__(self) -> 'None'
 |
 |  __enter__(self) -> 'Self'
 |
 |  __exit__(self, etype: 'type[BaseException] | None', exc: 'BaseException | None', tb: 'TracebackType | None') -> 'bool'
 |
 |  __getstate__ = slots_getstate(self) from attr._make._ClassBuilder._make_getstate_setstate.<locals>
 |      Automatically created by attrs.
 |
 |  __init__(self, *, relative_deadline: 'float' = inf, deadline: 'float' = inf, shield: 'bool' = False) -> None
 |      Method generated by attrs for class CancelScope.
 |
 |  __repr__(self) -> 'str'
 |      Return repr(self).
 |
 |  __setstate__ = slots_setstate(self, state) from attr._make._ClassBuilder._make_getstate_setstate.<locals>
 |      Automatically created by attrs.
 |
 |  cancel(self, reason: 'str | None' = None) -> 'None'
 |      Cancels this scope immediately.
 |
 |      The optional ``reason`` argument accepts a string, which will be attached to
 |      any resulting :exc:`Cancelled` exception to help you understand where that
 |      cancellation is coming from and why it happened.
 |
 |      This method is idempotent, i.e., if the scope was already
 |      cancelled then this method silently does nothing.
 |
 |  ----------------------------------------------------------------------
 |  Class methods defined here:
 |
 |  __init_subclass__ = _init_final_cls() -> 'NoReturn' from trio._util
 |      Raises an exception when a final class is subclassed.
 |
 |  ----------------------------------------------------------------------
 |  Readonly properties defined here:
 |
 |  cancel_called
 |      Readonly :class:`bool`. Records whether cancellation has been
 |      requested for this scope, either by an explicit call to
 |      :meth:`cancel` or by the deadline expiring.
 |
 |      This attribute being True does *not* necessarily mean that the
 |      code within the scope has been, or will be, affected by the
 |      cancellation. For example, if :meth:`cancel` was called after
 |      the last checkpoint in the ``with`` block, when it's too late to
 |      deliver a :exc:`~trio.Cancelled` exception, then this attribute
 |      will still be True.
 |
 |      This attribute is mostly useful for debugging and introspection.
 |      If you want to know whether or not a chunk of code was actually
 |      cancelled, then :attr:`cancelled_caught` is usually more
 |      appropriate.
 |
 |  is_relative
 |      Returns None after entering. Returns False if both deadline and
 |      relative_deadline are inf.
 |
 |  ----------------------------------------------------------------------
 |  Data descriptors defined here:
 |
 |  __weakref__
 |      list of weak references to the object
 |
 |  cancelled_caught
 |
 |  deadline
 |      Read-write, :class:`float`. An absolute time on the current
 |      run's clock at which this scope will automatically become
 |      cancelled. You can adjust the deadline by modifying this
 |      attribute, e.g.::
 |
 |         # I need a little more time!
 |         cancel_scope.deadline += 30
 |
 |      Note that for efficiency, the core run loop only checks for
 |      expired deadlines every once in a while. This means that in
 |      certain cases there may be a short delay between when the clock
 |      says the deadline should have expired, and when checkpoints
 |      start raising :exc:`~trio.Cancelled`. This is a very obscure
 |      corner case that you're unlikely to notice, but we document it
 |      for completeness. (If this *does* cause problems for you, of
 |      course, then `we want to know!
 |      <https://github.com/python-trio/trio/issues>`__)
 |
 |      Defaults to :data:`math.inf`, which means "no deadline", though
 |      this can be overridden by the ``deadline=`` argument to
 |      the :class:`~trio.CancelScope` constructor.
 |
 |  relative_deadline
 |      Read-write, :class:`float`. The number of seconds remaining until this
 |      scope's deadline, relative to the current time.
 |
 |      Defaults to :data:`math.inf` ("no deadline"). Must be non-negative.
 |
 |      When modified
 |      Before entering: sets the deadline relative to when the scope enters.
 |      After entering: sets a new deadline relative to the current time.
 |
 |      Raises:
 |        RuntimeError: if trying to read or modify an unentered scope with an absolute deadline, i.e. when :attr:`is_relative` is ``False``.
 |
 |  shield
 |      Read-write, :class:`bool`, default :data:`False`. So long as
 |      this is set to :data:`True`, then the code inside this scope
 |      will not receive :exc:`~trio.Cancelled` exceptions from scopes
 |      that are outside this scope. They can still receive
 |      :exc:`~trio.Cancelled` exceptions from (1) this scope, or (2)
 |      scopes inside this scope. You can modify this attribute::
 |
 |         with trio.CancelScope() as cancel_scope:
 |             cancel_scope.shield = True
 |             # This cannot be interrupted by any means short of
 |             # killing the process:
 |             await sleep(10)
 |
 |             cancel_scope.shield = False
 |             # Now this can be cancelled normally:
 |             await sleep(10)
 |
 |      Defaults to :data:`False`, though this can be overridden by the
 |      ``shield=`` argument to the :class:`~trio.CancelScope` constructor.
 |
 |  ----------------------------------------------------------------------
 |  Data and other attributes defined here:
 |
 |  __annotations__ = {'_cancel_called': 'bool', '_cancel_reason': 'Cancel...
 |
 |  __attrs_attrs__ = (Attribute(name='_cancel_status', default=None, ...n...
 |
 |  __attrs_own_setattr__ = False
 |
 |  __final__ = True
 |
 |  __match_args__ = ()
trio.Cancelled
Python Library Documentation: class Cancelled in module trio

class Cancelled(builtins.BaseException)
 |  Cancelled(*args: 'object', **kwargs: 'object') -> 'None'
 |
 |  Raised by blocking calls if the surrounding scope has been cancelled.
 |
 |  You should let this exception propagate, to be caught by the relevant
 |  cancel scope. To remind you of this, it inherits from :exc:`BaseException`
 |  instead of :exc:`Exception`, just like :exc:`KeyboardInterrupt` and
 |  :exc:`SystemExit` do. This means that if you write something like::
 |
 |     try:
 |         ...
 |     except Exception:
 |         ...
 |
 |  then this *won't* catch a :exc:`Cancelled` exception.
 |
 |  You cannot raise :exc:`Cancelled` yourself. Attempting to do so
 |  will produce a :exc:`TypeError`. Use :meth:`cancel_scope.cancel()
 |  <trio.CancelScope.cancel>` instead.
 |
 |  .. note::
 |
 |     In the US it's also common to see this word spelled "canceled", with
 |     only one "l". This is a `recent
 |     <https://books.google.com/ngrams/graph?content=canceled%2Ccancelled&year_start=1800&year_end=2000&corpus=5&smoothing=3&direct_url=t1%3B%2Ccanceled%3B%2Cc0%3B.t1%3B%2Ccancelled%3B%2Cc0>`__
 |     and `US-specific
 |     <https://books.google.com/ngrams/graph?content=canceled%2Ccancelled&year_start=1800&year_end=2000&corpus=18&smoothing=3&share=&direct_url=t1%3B%2Ccanceled%3B%2Cc0%3B.t1%3B%2Ccancelled%3B%2Cc0>`__
 |     innovation, and even in the US both forms are still commonly used. So
 |     for consistency with the rest of the world and with "cancellation"
 |     (which always has two "l"s), Trio uses the two "l" spelling
 |     everywhere.
 |
 |  Method resolution order:
 |      Cancelled
 |      builtins.BaseException
 |      builtins.object
 |
 |  Methods defined here:
 |
 |  __getstate__ = slots_getstate(self) from attr._make._ClassBuilder._make_getstate_setstate.<locals>
 |      Automatically created by attrs.
 |
 |  __init__(self, *, source: 'CancelReasonLiteral' = 'unknown', source_task: 'str | None' = None, reason: 'str | None' = None) -> None
 |      Method generated by attrs for class Cancelled.
 |
 |  __reduce__(self) -> 'tuple[Callable[[], Cancelled], tuple[()]]'
 |      Helper for pickle.
 |
 |  __repr__(self)
 |      Method generated by attrs for class Cancelled.
 |
 |  __setstate__ = slots_setstate(self, state) from attr._make._ClassBuilder._make_getstate_setstate.<locals>
 |      Automatically created by attrs.
 |
 |  __str__(self) -> 'str'
 |      Return str(self).
 |
 |  ----------------------------------------------------------------------
 |  Class methods defined here:
 |
 |  __init_subclass__ = _init_final_cls() -> 'NoReturn' from trio._util
 |      Raises an exception when a final class is subclassed.
 |
 |  ----------------------------------------------------------------------
 |  Data descriptors defined here:
 |
 |  __weakref__
 |      list of weak references to the object
 |
 |  reason
 |
 |  source
 |
 |  source_task
 |
 |  ----------------------------------------------------------------------
 |  Data and other attributes defined here:
 |
 |  __abstractmethods__ = frozenset()
 |
 |  __annotations__ = {'reason': 'str | None', 'source': 'CancelReasonLite...
 |
 |  __attrs_attrs__ = (Attribute(name='source', default='unknown', val...n...
 |
 |  __attrs_own_setattr__ = False
 |
 |  __final__ = True
 |
 |  __match_args__ = ()
 |
 |  ----------------------------------------------------------------------
 |  Methods inherited from builtins.BaseException:
 |
 |  __getattribute__(self, name, /)
 |      Return getattr(self, name).
 |
 |  add_note(...)
 |      Exception.add_note(note) --
 |      add a note to the exception
 |
 |  with_traceback(...)
 |      Exception.with_traceback(tb) --
 |      set self.__traceback__ to tb and return self.
 |
 |  ----------------------------------------------------------------------
 |  Static methods inherited from builtins.BaseException:
 |
 |  __new__(*args, **kwargs) class method of builtins.BaseException
 |      Create and return a new object.  See help(type) for accurate signature.
 |
 |  ----------------------------------------------------------------------
 |  Data descriptors inherited from builtins.BaseException:
 |
 |  __cause__
 |      exception cause
 |
 |  __context__
 |      exception context
 |
 |  __dict__
 |
 |  __suppress_context__
 |
 |  __traceback__
 |
 |  args
trio.CapacityLimiter
Python Library Documentation: class CapacityLimiter in module trio

class CapacityLimiter(trio._sync.AsyncContextManagerMixin)
 |  CapacityLimiter(total_tokens: 'int | float') -> 'None'
 |
 |  An object for controlling access to a resource with limited capacity.
 |
 |  Sometimes you need to put a limit on how many tasks can do something at
 |  the same time. For example, you might want to use some threads to run
 |  multiple blocking I/O operations in parallel... but if you use too many
 |  threads at once, then your system can become overloaded and it'll actually
 |  make things slower. One popular solution is to impose a policy like "run
 |  up to 40 threads at the same time, but no more". But how do you implement
 |  a policy like this?
 |
 |  That's what :class:`CapacityLimiter` is for. You can think of a
 |  :class:`CapacityLimiter` object as a sack that starts out holding some fixed
 |  number of tokens::
 |
 |     limit = trio.CapacityLimiter(40)
 |
 |  Then tasks can come along and borrow a token out of the sack::
 |
 |     # Borrow a token:
 |     async with limit:
 |         # We are holding a token!
 |         await perform_expensive_operation()
 |     # Exiting the 'async with' block puts the token back into the sack
 |
 |  And crucially, if you try to borrow a token but the sack is empty, then
 |  you have to wait for another task to finish what it's doing and put its
 |  token back first before you can take it and continue.
 |
 |  Another way to think of it: a :class:`CapacityLimiter` is like a sofa with a
 |  fixed number of seats, and if they're all taken then you have to wait for
 |  someone to get up before you can sit down.
 |
 |  By default, :func:`trio.to_thread.run_sync` uses a
 |  :class:`CapacityLimiter` to limit the number of threads running at once;
 |  see `trio.to_thread.current_default_thread_limiter` for details.
 |
 |  If you're familiar with semaphores, then you can think of this as a
 |  restricted semaphore that's specialized for one common use case, with
 |  additional error checking. For a more traditional semaphore, see
 |  :class:`Semaphore`.
 |
 |  .. note::
 |
 |     Don't confuse this with the `"leaky bucket"
 |     <https://en.wikipedia.org/wiki/Leaky_bucket>`__ or `"token bucket"
 |     <https://en.wikipedia.org/wiki/Token_bucket>`__ algorithms used to
 |     limit bandwidth usage on networks. The basic idea of using tokens to
 |     track a resource limit is similar, but this is a very simple sack where
 |     tokens aren't automatically created or destroyed over time; they're
 |     just borrowed and then put back.
 |
 |  Method resolution order:
 |      CapacityLimiter
 |      trio._sync.AsyncContextManagerMixin
 |      builtins.object
 |
 |  Methods defined here:
 |
 |  __init__(self, total_tokens: 'int | float') -> 'None'
 |      Initialize self.  See help(type(self)) for accurate signature.
 |
 |  __repr__(self) -> 'str'
 |      Return repr(self).
 |
 |  async acquire(self) -> 'None'
 |      Borrow a token from the sack, blocking if necessary.
 |
 |      Raises:
 |        RuntimeError: if the current task already holds one of this sack's
 |            tokens.
 |
 |  acquire_nowait(self) -> 'None'
 |      Borrow a token from the sack, without blocking.
 |
 |      Raises:
 |        WouldBlock: if no tokens are available.
 |        RuntimeError: if the current task already holds one of this sack's
 |            tokens.
 |
 |  async acquire_on_behalf_of(self, borrower: 'Task | object') -> 'None'
 |      Borrow a token from the sack on behalf of ``borrower``, blocking if
 |      necessary.
 |
 |      Args:
 |        borrower: A :class:`trio.lowlevel.Task` or arbitrary opaque object
 |           used to record who is borrowing this token; see
 |           :meth:`acquire_on_behalf_of_nowait` for details.
 |
 |      Raises:
 |        RuntimeError: if ``borrower`` task already holds one of this sack's
 |           tokens.
 |
 |  acquire_on_behalf_of_nowait(self, borrower: 'Task | object') -> 'None'
 |      Borrow a token from the sack on behalf of ``borrower``, without
 |      blocking.
 |
 |      Args:
 |        borrower: A :class:`trio.lowlevel.Task` or arbitrary opaque object
 |           used to record who is borrowing this token. This is used by
 |           :func:`trio.to_thread.run_sync` to allow threads to "hold
 |           tokens", with the intention in the future of using it to `allow
 |           deadlock detection and other useful things
 |           <https://github.com/python-trio/trio/issues/182>`__
 |
 |      Raises:
 |        WouldBlock: if no tokens are available.
 |        RuntimeError: if ``borrower`` already holds one of this sack's
 |            tokens.
 |
 |  release(self) -> 'None'
 |      Put a token back into the sack.
 |
 |      Raises:
 |        RuntimeError: if the current task has not acquired one of this
 |            sack's tokens.
 |
 |  release_on_behalf_of(self, borrower: 'Task | object') -> 'None'
 |      Put a token back into the sack on behalf of ``borrower``.
 |
 |      Raises:
 |        RuntimeError: if the given borrower has not acquired one of this
 |            sack's tokens.
 |
 |  statistics(self) -> 'CapacityLimiterStatistics'
 |      Return an object containing debugging information.
 |
 |      Currently the following fields are defined:
 |
 |      * ``borrowed_tokens``: The number of tokens currently borrowed from
 |        the sack.
 |      * ``total_tokens``: The total number of tokens in the sack. Usually
 |        this will be larger than ``borrowed_tokens``, but it's possibly for
 |        it to be smaller if :attr:`total_tokens` was recently decreased.
 |      * ``borrowers``: A list of all tasks or other entities that currently
 |        hold a token.
 |      * ``tasks_waiting``: The number of tasks blocked on this
 |        :class:`CapacityLimiter`'s :meth:`acquire` or
 |        :meth:`acquire_on_behalf_of` methods.
 |
 |  ----------------------------------------------------------------------
 |  Class methods defined here:
 |
 |  __init_subclass__ = _init_final_cls() -> 'NoReturn' from trio._util
 |      Raises an exception when a final class is subclassed.
 |
 |  ----------------------------------------------------------------------
 |  Readonly properties defined here:
 |
 |  available_tokens
 |      The amount of capacity that's available to use.
 |
 |  borrowed_tokens
 |      The amount of capacity that's currently in use.
 |
 |  ----------------------------------------------------------------------
 |  Data descriptors defined here:
 |
 |  total_tokens
 |      The total capacity available.
 |
 |      You can change :attr:`total_tokens` by assigning to this attribute. If
 |      you make it larger, then the appropriate number of waiting tasks will
 |      be woken immediately to take the new tokens. If you decrease
 |      total_tokens below the number of tasks that are currently using the
 |      resource, then all current tasks will be allowed to finish as normal,
 |      but no new tasks will be allowed in until the total number of tasks
 |      drops below the new total_tokens.
 |
 |  ----------------------------------------------------------------------
 |  Data and other attributes defined here:
 |
 |  __final__ = True
 |
 |  ----------------------------------------------------------------------
 |  Methods inherited from trio._sync.AsyncContextManagerMixin:
 |
 |  async __aenter__(self: '_HasAcquireRelease') -> 'None'
 |
 |  async __aexit__(self: '_HasAcquireRelease', exc_type: 'type[BaseException] | None', exc_value: 'BaseException | None', traceback: 'TracebackType | None') -> 'None'
 |
 |  ----------------------------------------------------------------------
 |  Data descriptors inherited from trio._sync.AsyncContextManagerMixin:
 |
 |  __dict__
 |      dictionary for instance variables
 |
 |  __weakref__
 |      list of weak references to the object
trio.CapacityLimiterStatistics
Python Library Documentation: class CapacityLimiterStatistics in module trio

class CapacityLimiterStatistics(builtins.object)
 |  CapacityLimiterStatistics(borrowed_tokens: 'int', total_tokens: 'int | float', borrowers: 'list[Task | object]', tasks_waiting: 'int') -> None
 |
 |  An object containing debugging information.
 |
 |  Currently the following fields are defined:
 |
 |  * ``borrowed_tokens``: The number of tokens currently borrowed from
 |    the sack.
 |  * ``total_tokens``: The total number of tokens in the sack. Usually
 |    this will be larger than ``borrowed_tokens``, but it's possibly for
 |    it to be smaller if :attr:`trio.CapacityLimiter.total_tokens` was recently decreased.
 |  * ``borrowers``: A list of all tasks or other entities that currently
 |    hold a token.
 |  * ``tasks_waiting``: The number of tasks blocked on this
 |    :class:`CapacityLimiter`'s :meth:`trio.CapacityLimiter.acquire` or
 |    :meth:`trio.CapacityLimiter.acquire_on_behalf_of` methods.
 |
 |  Methods defined here:
 |
 |  __delattr__ = _frozen_delattrs(self, name) from attr._make
 |      Attached to frozen classes as __delattr__.
 |
 |  __eq__(self, other)
 |      Method generated by attrs for class CapacityLimiterStatistics.
 |
 |  __getstate__ = slots_getstate(self) from attr._make._ClassBuilder._make_getstate_setstate.<locals>
 |      Automatically created by attrs.
 |
 |  __hash__(self)
 |      Method generated by attrs for class CapacityLimiterStatistics.
 |
 |  __init__(self, borrowed_tokens: 'int', total_tokens: 'int | float', borrowers: 'list[Task | object]', tasks_waiting: 'int') -> None
 |      Method generated by attrs for class CapacityLimiterStatistics.
 |
 |  __ne__(self, other)
 |      Method generated by attrs for class CapacityLimiterStatistics.
 |
 |  __repr__(self)
 |      Method generated by attrs for class CapacityLimiterStatistics.
 |
 |  __setattr__ = _frozen_setattrs(self, name, value) from attr._make
 |      Attached to frozen classes as __setattr__.
 |
 |  __setstate__ = slots_setstate(self, state) from attr._make._ClassBuilder._make_getstate_setstate.<locals>
 |      Automatically created by attrs.
 |
 |  ----------------------------------------------------------------------
 |  Data descriptors defined here:
 |
 |  __weakref__
 |      list of weak references to the object
 |
 |  borrowed_tokens
 |
 |  borrowers
 |
 |  tasks_waiting
 |
 |  total_tokens
 |
 |  ----------------------------------------------------------------------
 |  Data and other attributes defined here:
 |
 |  __annotations__ = {'borrowed_tokens': 'int', 'borrowers': 'list[Task |...
 |
 |  __attrs_attrs__ = (Attribute(name='borrowed_tokens', default=NOTHI...d...
 |
 |  __match_args__ = ('borrowed_tokens', 'total_tokens', 'borrowers', 'tas...
trio.ClosedResourceError
Python Library Documentation: class ClosedResourceError in module trio

class ClosedResourceError(builtins.Exception)
 |  Raised when attempting to use a resource after it has been closed.
 |
 |  Note that "closed" here means that *your* code closed the resource,
 |  generally by calling a method with a name like ``close`` or ``aclose``, or
 |  by exiting a context manager. If a problem arises elsewhere – for example,
 |  because of a network failure, or because a remote peer closed their end of
 |  a connection – then that should be indicated by a different exception
 |  class, like :exc:`BrokenResourceError` or an :exc:`OSError` subclass.
 |
 |  Method resolution order:
 |      ClosedResourceError
 |      builtins.Exception
 |      builtins.BaseException
 |      builtins.object
 |
 |  Data descriptors defined here:
 |
 |  __weakref__
 |      list of weak references to the object
 |
 |  ----------------------------------------------------------------------
 |  Methods inherited from builtins.Exception:
 |
 |  __init__(self, /, *args, **kwargs)
 |      Initialize self.  See help(type(self)) for accurate signature.
 |
 |  ----------------------------------------------------------------------
 |  Static methods inherited from builtins.Exception:
 |
 |  __new__(*args, **kwargs) class method of builtins.Exception
 |      Create and return a new object.  See help(type) for accurate signature.
 |
 |  ----------------------------------------------------------------------
 |  Methods inherited from builtins.BaseException:
 |
 |  __getattribute__(self, name, /)
 |      Return getattr(self, name).
 |
 |  __reduce__(...)
 |      Helper for pickle.
 |
 |  __repr__(self, /)
 |      Return repr(self).
 |
 |  __setstate__(...)
 |
 |  __str__(self, /)
 |      Return str(self).
 |
 |  add_note(...)
 |      Exception.add_note(note) --
 |      add a note to the exception
 |
 |  with_traceback(...)
 |      Exception.with_traceback(tb) --
 |      set self.__traceback__ to tb and return self.
 |
 |  ----------------------------------------------------------------------
 |  Data descriptors inherited from builtins.BaseException:
 |
 |  __cause__
 |      exception cause
 |
 |  __context__
 |      exception context
 |
 |  __dict__
 |
 |  __suppress_context__
 |
 |  __traceback__
 |
 |  args
trio.Condition
Python Library Documentation: class Condition in module trio

class Condition(trio._sync.AsyncContextManagerMixin)
 |  Condition(lock: 'Lock | None' = None) -> 'None'
 |
 |  A classic `condition variable
 |  <https://en.wikipedia.org/wiki/Monitor_(synchronization)>`__, similar to
 |  :class:`threading.Condition`.
 |
 |  A :class:`Condition` object can be used as an async context manager to
 |  acquire the underlying lock; it blocks on entry but not on exit.
 |
 |  Args:
 |    lock (Lock): the lock object to use. If given, must be a
 |        :class:`trio.Lock`. If None, a new :class:`Lock` will be allocated
 |        and used.
 |
 |  Method resolution order:
 |      Condition
 |      trio._sync.AsyncContextManagerMixin
 |      builtins.object
 |
 |  Methods defined here:
 |
 |  __init__(self, lock: 'Lock | None' = None) -> 'None'
 |      Initialize self.  See help(type(self)) for accurate signature.
 |
 |  async acquire(self) -> 'None'
 |      Acquire the underlying lock, blocking if necessary.
 |
 |      Raises:
 |        BrokenResourceError: if the owner of the underlying lock exits without releasing.
 |
 |  acquire_nowait(self) -> 'None'
 |      Attempt to acquire the underlying lock, without blocking.
 |
 |      Raises:
 |        WouldBlock: if the lock is currently held.
 |
 |  locked(self) -> 'bool'
 |      Check whether the underlying lock is currently held.
 |
 |      Returns:
 |        bool: True if the lock is held, False otherwise.
 |
 |  notify(self, n: 'int' = 1) -> 'None'
 |      Wake one or more tasks that are blocked in :meth:`wait`.
 |
 |      Args:
 |        n (int): The number of tasks to wake.
 |
 |      Raises:
 |        RuntimeError: if the calling task does not hold the lock.
 |
 |  notify_all(self) -> 'None'
 |      Wake all tasks that are currently blocked in :meth:`wait`.
 |
 |      Raises:
 |        RuntimeError: if the calling task does not hold the lock.
 |
 |  release(self) -> 'None'
 |      Release the underlying lock.
 |
 |  statistics(self) -> 'ConditionStatistics'
 |      Return an object containing debugging information.
 |
 |      Currently the following fields are defined:
 |
 |      * ``tasks_waiting``: The number of tasks blocked on this condition's
 |        :meth:`wait` method.
 |      * ``lock_statistics``: The result of calling the underlying
 |        :class:`Lock`\s  :meth:`~Lock.statistics` method.
 |
 |  async wait(self) -> 'None'
 |      Wait for another task to call :meth:`notify` or
 |      :meth:`notify_all`.
 |
 |      When calling this method, you must hold the lock. It releases the lock
 |      while waiting, and then re-acquires it before waking up.
 |
 |      There is a subtlety with how this method interacts with cancellation:
 |      when cancelled it will block to re-acquire the lock before raising
 |      :exc:`Cancelled`. This may cause cancellation to be less prompt than
 |      expected. The advantage is that it makes code like this work::
 |
 |         async with condition:
 |             await condition.wait()
 |
 |      If we didn't re-acquire the lock before waking up, and :meth:`wait`
 |      were cancelled here, then we'd crash in ``condition.__aexit__`` when
 |      we tried to release the lock we no longer held.
 |
 |      Raises:
 |        RuntimeError: if the calling task does not hold the lock.
 |        BrokenResourceError: if the owner of the lock exits without releasing, when attempting to re-acquire.
 |
 |  ----------------------------------------------------------------------
 |  Class methods defined here:
 |
 |  __init_subclass__ = _init_final_cls() -> 'NoReturn' from trio._util
 |      Raises an exception when a final class is subclassed.
 |
 |  ----------------------------------------------------------------------
 |  Data and other attributes defined here:
 |
 |  __final__ = True
 |
 |  ----------------------------------------------------------------------
 |  Methods inherited from trio._sync.AsyncContextManagerMixin:
 |
 |  async __aenter__(self: '_HasAcquireRelease') -> 'None'
 |
 |  async __aexit__(self: '_HasAcquireRelease', exc_type: 'type[BaseException] | None', exc_value: 'BaseException | None', traceback: 'TracebackType | None') -> 'None'
 |
 |  ----------------------------------------------------------------------
 |  Data descriptors inherited from trio._sync.AsyncContextManagerMixin:
 |
 |  __dict__
 |      dictionary for instance variables
 |
 |  __weakref__
 |      list of weak references to the object
trio.ConditionStatistics
Python Library Documentation: class ConditionStatistics in module trio

class ConditionStatistics(builtins.object)
 |  ConditionStatistics(tasks_waiting: 'int', lock_statistics: 'LockStatistics') -> None
 |
 |  An object containing debugging information for a Condition.
 |
 |  Currently the following fields are defined:
 |
 |  * ``tasks_waiting`` (int): The number of tasks blocked on this condition's
 |    :meth:`trio.Condition.wait` method.
 |  * ``lock_statistics``: The result of calling the underlying
 |    :class:`Lock`\s  :meth:`~Lock.statistics` method.
 |
 |  Methods defined here:
 |
 |  __delattr__ = _frozen_delattrs(self, name) from attr._make
 |      Attached to frozen classes as __delattr__.
 |
 |  __eq__(self, other)
 |      Method generated by attrs for class ConditionStatistics.
 |
 |  __getstate__ = slots_getstate(self) from attr._make._ClassBuilder._make_getstate_setstate.<locals>
 |      Automatically created by attrs.
 |
 |  __hash__(self)
 |      Method generated by attrs for class ConditionStatistics.
 |
 |  __init__(self, tasks_waiting: 'int', lock_statistics: 'LockStatistics') -> None
 |      Method generated by attrs for class ConditionStatistics.
 |
 |  __ne__(self, other)
 |      Method generated by attrs for class ConditionStatistics.
 |
 |  __repr__(self)
 |      Method generated by attrs for class ConditionStatistics.
 |
 |  __setattr__ = _frozen_setattrs(self, name, value) from attr._make
 |      Attached to frozen classes as __setattr__.
 |
 |  __setstate__ = slots_setstate(self, state) from attr._make._ClassBuilder._make_getstate_setstate.<locals>
 |      Automatically created by attrs.
 |
 |  ----------------------------------------------------------------------
 |  Data descriptors defined here:
 |
 |  __weakref__
 |      list of weak references to the object
 |
 |  lock_statistics
 |
 |  tasks_waiting
 |
 |  ----------------------------------------------------------------------
 |  Data and other attributes defined here:
 |
 |  __annotations__ = {'lock_statistics': 'LockStatistics', 'tasks_waiting...
 |
 |  __attrs_attrs__ = (Attribute(name='tasks_waiting', default=NOTHING...F...
 |
 |  __match_args__ = ('tasks_waiting', 'lock_statistics')
trio.DTLSChannel
Python Library Documentation: class DTLSChannel in module trio

class DTLSChannel(trio.abc.Channel)
 |  DTLSChannel(*args: 'object', **kwargs: 'object') -> 'None'
 |
 |  A DTLS connection.
 |
 |  This class has no public constructor – you get instances by calling
 |  `DTLSEndpoint.serve` or `~DTLSEndpoint.connect`.
 |
 |  .. attribute:: endpoint
 |
 |     The `DTLSEndpoint` that this connection is using.
 |
 |  .. attribute:: peer_address
 |
 |     The IP/port of the remote peer that this connection is associated with.
 |
 |  Method resolution order:
 |      DTLSChannel
 |      trio.abc.Channel
 |      trio.abc.SendChannel
 |      trio.abc.ReceiveChannel
 |      trio.abc.AsyncResource
 |      abc.ABC
 |      typing.Generic
 |      builtins.object
 |
 |  Methods defined here:
 |
 |  __enter__(self) -> 'Self'
 |
 |  __exit__(self, exc_type: 'type[BaseException] | None', exc_value: 'BaseException | None', traceback: 'TracebackType | None') -> 'None'
 |
 |  __init__(self, endpoint: 'DTLSEndpoint', peer_address: 'AddressFormat', ctx: 'SSL.Context') -> 'None'
 |      Initialize self.  See help(type(self)) for accurate signature.
 |
 |  async aclose(self) -> 'None'
 |      Close this connection, but asynchronously.
 |
 |      This is included to satisfy the `trio.abc.Channel` contract. It's
 |      identical to `close`, but async.
 |
 |  close(self) -> 'None'
 |      Close this connection.
 |
 |      `DTLSChannel`\s don't actually own any OS-level resources – the
 |      socket is owned by the `DTLSEndpoint`, not the individual connections. So
 |      you don't really *have* to call this. But it will interrupt any other tasks
 |      calling `receive` with a `ClosedResourceError`, and cause future attempts to use
 |      this connection to fail.
 |
 |      You can also use this object as a synchronous or asynchronous context manager.
 |
 |  async do_handshake(self, *, initial_retransmit_timeout: 'float' = 1.0) -> 'None'
 |      Perform the handshake.
 |
 |      Calling this is optional – if you don't, then it will be automatically called
 |      the first time you call `send` or `receive`. But calling it explicitly can be
 |      useful in case you want to control the retransmit timeout, use a cancel scope to
 |      place an overall timeout on the handshake, or catch errors from the handshake
 |      specifically.
 |
 |      It's safe to call this multiple times, or call it simultaneously from multiple
 |      tasks – the first call will perform the handshake, and the rest will be no-ops.
 |
 |      Args:
 |
 |        initial_retransmit_timeout (float): Since UDP is an unreliable protocol, it's
 |          possible that some of the packets we send during the handshake will get
 |          lost. To handle this, DTLS uses a timer to automatically retransmit
 |          handshake packets that don't receive a response. This lets you set the
 |          timeout we use to detect packet loss. Ideally, it should be set to ~1.5
 |          times the round-trip time to your peer, but 1 second is a reasonable
 |          default. There's `some useful guidance here
 |          <https://tlswg.org/dtls13-spec/draft-ietf-tls-dtls13.html#name-timer-values>`__.
 |
 |          This is the *initial* timeout, because if packets keep being lost then Trio
 |          will automatically back off to longer values, to avoid overloading the
 |          network.
 |
 |  get_cleartext_mtu(self) -> 'int'
 |      Returns the largest number of bytes that you can pass in a single call to
 |      `send` while still fitting within the network-level MTU.
 |
 |      See `set_ciphertext_mtu` for more details.
 |
 |  async receive(self) -> 'bytes'
 |      Fetch the next packet of data from this connection's peer, waiting if
 |      necessary.
 |
 |      This is safe to call from multiple tasks simultaneously, in case you have some
 |      reason to do that. And more importantly, it's cancellation-safe, meaning that
 |      cancelling a call to `receive` will never cause a packet to be lost or corrupt
 |      the underlying connection.
 |
 |  async send(self, data: 'bytes') -> 'None'
 |      Send a packet of data, securely.
 |
 |  set_ciphertext_mtu(self, new_mtu: 'int') -> 'None'
 |      Tells Trio the `largest amount of data that can be sent in a single packet to
 |      this peer <https://en.wikipedia.org/wiki/Maximum_transmission_unit>`__.
 |
 |      Trio doesn't actually enforce this limit – if you pass a huge packet to `send`,
 |      then we'll dutifully encrypt it and attempt to send it. But calling this method
 |      does have two useful effects:
 |
 |      - If called before the handshake is performed, then Trio will automatically
 |        fragment handshake messages to fit within the given MTU. It also might
 |        fragment them even smaller, if it detects signs of packet loss, so setting
 |        this should never be necessary to make a successful connection. But, the
 |        packet loss detection only happens after multiple timeouts have expired, so if
 |        you have reason to believe that a smaller MTU is required, then you can set
 |        this to skip those timeouts and establish the connection more quickly.
 |
 |      - It changes the value returned from `get_cleartext_mtu`. So if you have some
 |        kind of estimate of the network-level MTU, then you can use this to figure out
 |        how much overhead DTLS will need for hashes/padding/etc., and how much space
 |        you have left for your application data.
 |
 |      The MTU here is measuring the largest UDP *payload* you think can be sent, the
 |      amount of encrypted data that can be handed to the operating system in a single
 |      call to `send`. It should *not* include IP/UDP headers. Note that OS estimates
 |      of the MTU often are link-layer MTUs, so you have to subtract off 28 bytes on
 |      IPv4 and 48 bytes on IPv6 to get the ciphertext MTU.
 |
 |      By default, Trio assumes an MTU of 1472 bytes on IPv4, and 1452 bytes on IPv6,
 |      which correspond to the common Ethernet MTU of 1500 bytes after accounting for
 |      IP/UDP overhead.
 |
 |  statistics(self) -> 'DTLSChannelStatistics'
 |      Returns a `DTLSChannelStatistics` object with statistics about this connection.
 |
 |  ----------------------------------------------------------------------
 |  Class methods defined here:
 |
 |  __init_subclass__ = _init_final_cls() -> 'NoReturn' from trio._util
 |      Raises an exception when a final class is subclassed.
 |
 |  ----------------------------------------------------------------------
 |  Data descriptors defined here:
 |
 |  __dict__
 |      dictionary for instance variables
 |
 |  __weakref__
 |      list of weak references to the object
 |
 |  ----------------------------------------------------------------------
 |  Data and other attributes defined here:
 |
 |  __abstractmethods__ = frozenset()
 |
 |  __final__ = True
 |
 |  __orig_bases__ = (trio.abc.Channel[bytes],)
 |
 |  __parameters__ = ()
 |
 |  ----------------------------------------------------------------------
 |  Methods inherited from trio.abc.ReceiveChannel:
 |
 |  __aiter__(self) -> 'Self'
 |
 |  async __anext__(self) -> 'ReceiveType'
 |
 |  ----------------------------------------------------------------------
 |  Methods inherited from trio.abc.AsyncResource:
 |
 |  async __aenter__(self) -> 'Self'
 |
 |  async __aexit__(self, exc_type: 'type[BaseException] | None', exc_value: 'BaseException | None', traceback: 'TracebackType | None') -> 'None'
 |
 |  ----------------------------------------------------------------------
 |  Class methods inherited from typing.Generic:
 |
 |  __class_getitem__(...)
 |      Parameterizes a generic class.
 |
 |      At least, parameterizing a generic class is the *main* thing this
 |      method does. For example, for some generic class `Foo`, this is called
 |      when we do `Foo[int]` - there, with `cls=Foo` and `params=int`.
 |
 |      However, note that this method is also called when defining generic
 |      classes in the first place with `class Foo[T]: ...`.
trio.DTLSChannelStatistics
Python Library Documentation: class DTLSChannelStatistics in module trio

class DTLSChannelStatistics(builtins.object)
 |  DTLSChannelStatistics(incoming_packets_dropped_in_trio: 'int') -> None
 |
 |  Currently this has only one attribute:
 |
 |  - ``incoming_packets_dropped_in_trio`` (``int``): Gives a count of the number of
 |    incoming packets from this peer that Trio successfully received from the
 |    network, but then got dropped because the internal channel buffer was full. If
 |    this is non-zero, then you might want to call ``receive`` more often, or use a
 |    larger ``incoming_packets_buffer``, or just not worry about it because your
 |    UDP-based protocol should be able to handle the occasional lost packet, right?
 |
 |  Methods defined here:
 |
 |  __delattr__ = _frozen_delattrs(self, name) from attr._make
 |      Attached to frozen classes as __delattr__.
 |
 |  __eq__(self, other)
 |      Method generated by attrs for class DTLSChannelStatistics.
 |
 |  __getstate__ = slots_getstate(self) from attr._make._ClassBuilder._make_getstate_setstate.<locals>
 |      Automatically created by attrs.
 |
 |  __hash__(self)
 |      Method generated by attrs for class DTLSChannelStatistics.
 |
 |  __init__(self, incoming_packets_dropped_in_trio: 'int') -> None
 |      Method generated by attrs for class DTLSChannelStatistics.
 |
 |  __ne__(self, other)
 |      Method generated by attrs for class DTLSChannelStatistics.
 |
 |  __repr__(self)
 |      Method generated by attrs for class DTLSChannelStatistics.
 |
 |  __setattr__ = _frozen_setattrs(self, name, value) from attr._make
 |      Attached to frozen classes as __setattr__.
 |
 |  __setstate__ = slots_setstate(self, state) from attr._make._ClassBuilder._make_getstate_setstate.<locals>
 |      Automatically created by attrs.
 |
 |  ----------------------------------------------------------------------
 |  Data descriptors defined here:
 |
 |  __weakref__
 |      list of weak references to the object
 |
 |  incoming_packets_dropped_in_trio
 |
 |  ----------------------------------------------------------------------
 |  Data and other attributes defined here:
 |
 |  __annotations__ = {'incoming_packets_dropped_in_trio': 'int'}
 |
 |  __attrs_attrs__ = (Attribute(name='incoming_packets_dropped_in_tri...N...
 |
 |  __match_args__ = ('incoming_packets_dropped_in_trio',)
trio.DTLSEndpoint
Python Library Documentation: class DTLSEndpoint in module trio

class DTLSEndpoint(builtins.object)
 |  DTLSEndpoint(socket: 'SocketType', *, incoming_packets_buffer: 'int' = 10) -> 'None'
 |
 |  A DTLS endpoint.
 |
 |  A single UDP socket can handle arbitrarily many DTLS connections simultaneously,
 |  acting as a client or server as needed. A `DTLSEndpoint` object holds a UDP socket
 |  and manages these connections, which are represented as `DTLSChannel` objects.
 |
 |  Args:
 |    socket: (trio.socket.SocketType): A ``SOCK_DGRAM`` socket. If you want to accept
 |      incoming connections in server mode, then you should probably bind the socket to
 |      some known port.
 |    incoming_packets_buffer (int): Each `DTLSChannel` using this socket has its own
 |      buffer that holds incoming packets until you call `~DTLSChannel.receive` to read
 |      them. This lets you adjust the size of this buffer. `~DTLSChannel.statistics`
 |      lets you check if the buffer has overflowed.
 |
 |  .. attribute:: socket
 |                 incoming_packets_buffer
 |
 |     Both constructor arguments are also exposed as attributes, in case you need to
 |     access them later.
 |
 |  Methods defined here:
 |
 |  __del__(self) -> 'None'
 |
 |  __enter__(self) -> 'Self'
 |
 |  __exit__(self, exc_type: 'type[BaseException] | None', exc_value: 'BaseException | None', traceback: 'TracebackType | None') -> 'None'
 |
 |  __init__(self, socket: 'SocketType', *, incoming_packets_buffer: 'int' = 10) -> 'None'
 |      Initialize self.  See help(type(self)) for accurate signature.
 |
 |  close(self) -> 'None'
 |      Close this socket, and all associated DTLS connections.
 |
 |      This object can also be used as a context manager.
 |
 |  connect(self, address: 'tuple[str, int]', ssl_context: 'SSL.Context') -> 'DTLSChannel'
 |      Initiate an outgoing DTLS connection.
 |
 |      Notice that this is a synchronous method. That's because it doesn't actually
 |      initiate any I/O – it just sets up a `DTLSChannel` object. The actual handshake
 |      doesn't occur until you start using the `DTLSChannel`. This gives you a chance
 |      to do further configuration first, like setting MTU etc.
 |
 |      Args:
 |        address: The address to connect to. Usually a (host, port) tuple, like
 |          ``("127.0.0.1", 12345)``.
 |        ssl_context (OpenSSL.SSL.Context): The PyOpenSSL context object to use for
 |          this connection.
 |
 |      Returns:
 |        DTLSChannel
 |
 |  async serve(self, ssl_context: 'SSL.Context', async_fn: 'Callable[[DTLSChannel, Unpack[PosArgsT]], Awaitable[object]]', *args: 'Unpack[PosArgsT]', task_status: 'trio.TaskStatus[None]' = TASK_STATUS_IGNORED) -> 'None'
 |      Listen for incoming connections, and spawn a handler for each using an
 |      internal nursery.
 |
 |      Similar to `~trio.serve_tcp`, this function never returns until cancelled, or
 |      the `DTLSEndpoint` is closed and all handlers have exited.
 |
 |      Usage commonly looks like::
 |
 |          async def handler(dtls_channel):
 |              ...
 |
 |          async with trio.open_nursery() as nursery:
 |              await nursery.start(dtls_endpoint.serve, ssl_context, handler)
 |              # ... do other things here ...
 |
 |      The ``dtls_channel`` passed into the handler function has already performed the
 |      "cookie exchange" part of the DTLS handshake, so the peer address is
 |      trustworthy. But the actual cryptographic handshake doesn't happen until you
 |      start using it, giving you a chance for any last minute configuration, and the
 |      option to catch and handle handshake errors.
 |
 |      Args:
 |        ssl_context (OpenSSL.SSL.Context): The PyOpenSSL context object to use for
 |          incoming connections.
 |        async_fn: The handler function that will be invoked for each incoming
 |          connection.
 |        *args: Additional arguments to pass to the handler function.
 |
 |  ----------------------------------------------------------------------
 |  Class methods defined here:
 |
 |  __init_subclass__ = _init_final_cls() -> 'NoReturn' from trio._util
 |      Raises an exception when a final class is subclassed.
 |
 |  ----------------------------------------------------------------------
 |  Data descriptors defined here:
 |
 |  __dict__
 |      dictionary for instance variables
 |
 |  __weakref__
 |      list of weak references to the object
 |
 |  ----------------------------------------------------------------------
 |  Data and other attributes defined here:
 |
 |  __final__ = True
trio.EndOfChannel
Python Library Documentation: class EndOfChannel in module trio

class EndOfChannel(builtins.Exception)
 |  Raised when trying to receive from a :class:`trio.abc.ReceiveChannel`
 |  that has no more data to receive.
 |
 |  This is analogous to an "end-of-file" condition, but for channels.
 |
 |  Method resolution order:
 |      EndOfChannel
 |      builtins.Exception
 |      builtins.BaseException
 |      builtins.object
 |
 |  Data descriptors defined here:
 |
 |  __weakref__
 |      list of weak references to the object
 |
 |  ----------------------------------------------------------------------
 |  Methods inherited from builtins.Exception:
 |
 |  __init__(self, /, *args, **kwargs)
 |      Initialize self.  See help(type(self)) for accurate signature.
 |
 |  ----------------------------------------------------------------------
 |  Static methods inherited from builtins.Exception:
 |
 |  __new__(*args, **kwargs) class method of builtins.Exception
 |      Create and return a new object.  See help(type) for accurate signature.
 |
 |  ----------------------------------------------------------------------
 |  Methods inherited from builtins.BaseException:
 |
 |  __getattribute__(self, name, /)
 |      Return getattr(self, name).
 |
 |  __reduce__(...)
 |      Helper for pickle.
 |
 |  __repr__(self, /)
 |      Return repr(self).
 |
 |  __setstate__(...)
 |
 |  __str__(self, /)
 |      Return str(self).
 |
 |  add_note(...)
 |      Exception.add_note(note) --
 |      add a note to the exception
 |
 |  with_traceback(...)
 |      Exception.with_traceback(tb) --
 |      set self.__traceback__ to tb and return self.
 |
 |  ----------------------------------------------------------------------
 |  Data descriptors inherited from builtins.BaseException:
 |
 |  __cause__
 |      exception cause
 |
 |  __context__
 |      exception context
 |
 |  __dict__
 |
 |  __suppress_context__
 |
 |  __traceback__
 |
 |  args
trio.Event
Python Library Documentation: class Event in module trio

class Event(builtins.object)
 |  Event() -> None
 |
 |  A waitable boolean value useful for inter-task synchronization,
 |  inspired by :class:`threading.Event`.
 |
 |  An event object has an internal boolean flag, representing whether
 |  the event has happened yet. The flag is initially False, and the
 |  :meth:`wait` method waits until the flag is True. If the flag is
 |  already True, then :meth:`wait` returns immediately. (If the event has
 |  already happened, there's nothing to wait for.) The :meth:`set` method
 |  sets the flag to True, and wakes up any waiters.
 |
 |  This behavior is useful because it helps avoid race conditions and
 |  lost wakeups: it doesn't matter whether :meth:`set` gets called just
 |  before or after :meth:`wait`. If you want a lower-level wakeup
 |  primitive that doesn't have this protection, consider :class:`Condition`
 |  or :class:`trio.lowlevel.ParkingLot`.
 |
 |  .. note:: Unlike `threading.Event`, `trio.Event` has no
 |     `~threading.Event.clear` method. In Trio, once an `Event` has happened,
 |     it cannot un-happen. If you need to represent a series of events,
 |     consider creating a new `Event` object for each one (they're cheap!),
 |     or other synchronization methods like :ref:`channels <channels>` or
 |     `trio.lowlevel.ParkingLot`.
 |
 |  Methods defined here:
 |
 |  __bool__(self) -> 'Literal[True]'
 |      Return True and raise warning.
 |
 |  __getstate__ = slots_getstate(self) from attr._make._ClassBuilder._make_getstate_setstate.<locals>
 |      Automatically created by attrs.
 |
 |  __init__(self) -> None
 |      Method generated by attrs for class Event.
 |
 |  __setstate__ = slots_setstate(self, state) from attr._make._ClassBuilder._make_getstate_setstate.<locals>
 |      Automatically created by attrs.
 |
 |  is_set(self) -> 'bool'
 |      Return the current value of the internal flag.
 |
 |  set(self) -> 'None'
 |      Set the internal flag value to True, and wake any waiting tasks.
 |
 |  statistics(self) -> 'EventStatistics'
 |      Return an object containing debugging information.
 |
 |      Currently the following fields are defined:
 |
 |      * ``tasks_waiting``: The number of tasks blocked on this event's
 |        :meth:`wait` method.
 |
 |  async wait(self) -> 'None'
 |      Block until the internal flag value becomes True.
 |
 |      If it's already True, then this method returns immediately.
 |
 |  ----------------------------------------------------------------------
 |  Class methods defined here:
 |
 |  __init_subclass__ = _init_final_cls() -> 'NoReturn' from trio._util
 |      Raises an exception when a final class is subclassed.
 |
 |  ----------------------------------------------------------------------
 |  Data descriptors defined here:
 |
 |  __weakref__
 |      list of weak references to the object
 |
 |  ----------------------------------------------------------------------
 |  Data and other attributes defined here:
 |
 |  __annotations__ = {'_flag': 'bool', '_tasks': 'set[Task]'}
 |
 |  __attrs_attrs__ = (Attribute(name='_tasks', default=Factory(factor... ...
 |
 |  __attrs_own_setattr__ = False
 |
 |  __final__ = True
 |
 |  __match_args__ = ()
trio.EventStatistics
Python Library Documentation: class EventStatistics in module trio

class EventStatistics(builtins.object)
 |  EventStatistics(tasks_waiting: 'int') -> None
 |
 |  An object containing debugging information.
 |
 |  Currently the following fields are defined:
 |
 |  * ``tasks_waiting``: The number of tasks blocked on this event's
 |    :meth:`trio.Event.wait` method.
 |
 |  Methods defined here:
 |
 |  __delattr__ = _frozen_delattrs(self, name) from attr._make
 |      Attached to frozen classes as __delattr__.
 |
 |  __eq__(self, other)
 |      Method generated by attrs for class EventStatistics.
 |
 |  __getstate__ = slots_getstate(self) from attr._make._ClassBuilder._make_getstate_setstate.<locals>
 |      Automatically created by attrs.
 |
 |  __hash__(self)
 |      Method generated by attrs for class EventStatistics.
 |
 |  __init__(self, tasks_waiting: 'int') -> None
 |      Method generated by attrs for class EventStatistics.
 |
 |  __ne__(self, other)
 |      Method generated by attrs for class EventStatistics.
 |
 |  __repr__(self)
 |      Method generated by attrs for class EventStatistics.
 |
 |  __setattr__ = _frozen_setattrs(self, name, value) from attr._make
 |      Attached to frozen classes as __setattr__.
 |
 |  __setstate__ = slots_setstate(self, state) from attr._make._ClassBuilder._make_getstate_setstate.<locals>
 |      Automatically created by attrs.
 |
 |  ----------------------------------------------------------------------
 |  Data descriptors defined here:
 |
 |  __weakref__
 |      list of weak references to the object
 |
 |  tasks_waiting
 |
 |  ----------------------------------------------------------------------
 |  Data and other attributes defined here:
 |
 |  __annotations__ = {'tasks_waiting': 'int'}
 |
 |  __attrs_attrs__ = (Attribute(name='tasks_waiting', default=NOTHING...=...
 |
 |  __match_args__ = ('tasks_waiting',)
trio.Lock
Python Library Documentation: class Lock in module trio

class Lock(trio._sync._LockImpl)
 |  Lock() -> None
 |
 |  A classic `mutex
 |  <https://en.wikipedia.org/wiki/Lock_(computer_science)>`__.
 |
 |  This is a non-reentrant, single-owner lock. Unlike
 |  :class:`threading.Lock`, only the owner of the lock is allowed to release
 |  it.
 |
 |  A :class:`Lock` object can be used as an async context manager; it
 |  blocks on entry but not on exit.
 |
 |  Method resolution order:
 |      Lock
 |      trio._sync._LockImpl
 |      trio._sync.AsyncContextManagerMixin
 |      builtins.object
 |
 |  Class methods defined here:
 |
 |  __init_subclass__ = _init_final_cls() -> 'NoReturn' from trio._util
 |      Raises an exception when a final class is subclassed.
 |
 |  ----------------------------------------------------------------------
 |  Data and other attributes defined here:
 |
 |  __annotations__ = {}
 |
 |  __final__ = True
 |
 |  ----------------------------------------------------------------------
 |  Methods inherited from trio._sync._LockImpl:
 |
 |  __init__(self) -> None
 |      Method generated by attrs for class _LockImpl.
 |
 |  __repr__(self) -> 'str'
 |      Return repr(self).
 |
 |  async acquire(self) -> 'None'
 |      Acquire the lock, blocking if necessary.
 |
 |      Raises:
 |        BrokenResourceError: if the owner of the lock exits without releasing.
 |
 |  acquire_nowait(self) -> 'None'
 |      Attempt to acquire the lock, without blocking.
 |
 |      Raises:
 |        WouldBlock: if the lock is held.
 |
 |  locked(self) -> 'bool'
 |      Check whether the lock is currently held.
 |
 |      Returns:
 |        bool: True if the lock is held, False otherwise.
 |
 |  release(self) -> 'None'
 |      Release the lock.
 |
 |      Raises:
 |        RuntimeError: if the calling task does not hold the lock.
 |
 |  statistics(self) -> 'LockStatistics'
 |      Return an object containing debugging information.
 |
 |      Currently the following fields are defined:
 |
 |      * ``locked``: boolean indicating whether the lock is held.
 |      * ``owner``: the :class:`trio.lowlevel.Task` currently holding the lock,
 |        or None if the lock is not held.
 |      * ``tasks_waiting``: The number of tasks blocked on this lock's
 |        :meth:`acquire` method.
 |
 |  ----------------------------------------------------------------------
 |  Data and other attributes inherited from trio._sync._LockImpl:
 |
 |  __attrs_attrs__ = (Attribute(name='_lot', default=Factory(factory=...i...
 |
 |  __match_args__ = ()
 |
 |  ----------------------------------------------------------------------
 |  Methods inherited from trio._sync.AsyncContextManagerMixin:
 |
 |  async __aenter__(self: '_HasAcquireRelease') -> 'None'
 |
 |  async __aexit__(self: '_HasAcquireRelease', exc_type: 'type[BaseException] | None', exc_value: 'BaseException | None', traceback: 'TracebackType | None') -> 'None'
 |
 |  ----------------------------------------------------------------------
 |  Data descriptors inherited from trio._sync.AsyncContextManagerMixin:
 |
 |  __dict__
 |      dictionary for instance variables
 |
 |  __weakref__
 |      list of weak references to the object
trio.LockStatistics
Python Library Documentation: class LockStatistics in module trio

class LockStatistics(builtins.object)
 |  LockStatistics(locked: 'bool', owner: 'Task | None', tasks_waiting: 'int') -> None
 |
 |  An object containing debugging information for a Lock.
 |
 |  Currently the following fields are defined:
 |
 |  * ``locked`` (boolean): indicating whether the lock is held.
 |  * ``owner``: the :class:`trio.lowlevel.Task` currently holding the lock,
 |    or None if the lock is not held.
 |  * ``tasks_waiting`` (int): The number of tasks blocked on this lock's
 |    :meth:`trio.Lock.acquire` method.
 |
 |  Methods defined here:
 |
 |  __delattr__ = _frozen_delattrs(self, name) from attr._make
 |      Attached to frozen classes as __delattr__.
 |
 |  __eq__(self, other)
 |      Method generated by attrs for class LockStatistics.
 |
 |  __getstate__ = slots_getstate(self) from attr._make._ClassBuilder._make_getstate_setstate.<locals>
 |      Automatically created by attrs.
 |
 |  __hash__(self)
 |      Method generated by attrs for class LockStatistics.
 |
 |  __init__(self, locked: 'bool', owner: 'Task | None', tasks_waiting: 'int') -> None
 |      Method generated by attrs for class LockStatistics.
 |
 |  __ne__(self, other)
 |      Method generated by attrs for class LockStatistics.
 |
 |  __repr__(self)
 |      Method generated by attrs for class LockStatistics.
 |
 |  __setattr__ = _frozen_setattrs(self, name, value) from attr._make
 |      Attached to frozen classes as __setattr__.
 |
 |  __setstate__ = slots_setstate(self, state) from attr._make._ClassBuilder._make_getstate_setstate.<locals>
 |      Automatically created by attrs.
 |
 |  ----------------------------------------------------------------------
 |  Data descriptors defined here:
 |
 |  __weakref__
 |      list of weak references to the object
 |
 |  locked
 |
 |  owner
 |
 |  tasks_waiting
 |
 |  ----------------------------------------------------------------------
 |  Data and other attributes defined here:
 |
 |  __annotations__ = {'locked': 'bool', 'owner': 'Task | None', 'tasks_wa...
 |
 |  __attrs_attrs__ = (Attribute(name='locked', default=NOTHING, valid...d...
 |
 |  __match_args__ = ('locked', 'owner', 'tasks_waiting')
trio.MemoryChannelStatistics
Python Library Documentation: class MemoryChannelStatistics in module trio

class MemoryChannelStatistics(builtins.object)
 |  MemoryChannelStatistics(current_buffer_used: 'int', max_buffer_size: 'int | float', open_send_channels: 'int', open_receive_channels: 'int', tasks_waiting_send: 'int', tasks_waiting_receive: 'int') -> None
 |
 |  Methods defined here:
 |
 |  __delattr__ = _frozen_delattrs(self, name) from attr._make
 |      Attached to frozen classes as __delattr__.
 |
 |  __eq__(self, other)
 |      Method generated by attrs for class MemoryChannelStatistics.
 |
 |  __getstate__ = slots_getstate(self) from attr._make._ClassBuilder._make_getstate_setstate.<locals>
 |      Automatically created by attrs.
 |
 |  __hash__(self)
 |      Method generated by attrs for class MemoryChannelStatistics.
 |
 |  __init__(self, current_buffer_used: 'int', max_buffer_size: 'int | float', open_send_channels: 'int', open_receive_channels: 'int', tasks_waiting_send: 'int', tasks_waiting_receive: 'int') -> None
 |      Method generated by attrs for class MemoryChannelStatistics.
 |
 |  __ne__(self, other)
 |      Method generated by attrs for class MemoryChannelStatistics.
 |
 |  __repr__(self)
 |      Method generated by attrs for class MemoryChannelStatistics.
 |
 |  __setattr__ = _frozen_setattrs(self, name, value) from attr._make
 |      Attached to frozen classes as __setattr__.
 |
 |  __setstate__ = slots_setstate(self, state) from attr._make._ClassBuilder._make_getstate_setstate.<locals>
 |      Automatically created by attrs.
 |
 |  ----------------------------------------------------------------------
 |  Data descriptors defined here:
 |
 |  __weakref__
 |      list of weak references to the object
 |
 |  current_buffer_used
 |
 |  max_buffer_size
 |
 |  open_receive_channels
 |
 |  open_send_channels
 |
 |  tasks_waiting_receive
 |
 |  tasks_waiting_send
 |
 |  ----------------------------------------------------------------------
 |  Data and other attributes defined here:
 |
 |  __annotations__ = {'current_buffer_used': 'int', 'max_buffer_size': 'i...
 |
 |  __attrs_attrs__ = (Attribute(name='current_buffer_used', default=N... ...
 |
 |  __match_args__ = ('current_buffer_used', 'max_buffer_size', 'open_send...
trio.MemoryReceiveChannel
Python Library Documentation: class MemoryReceiveChannel in module trio

class MemoryReceiveChannel(trio.abc.ReceiveChannel)
 |  MemoryReceiveChannel(*args: 'object', **kwargs: 'object') -> 'None'
 |
 |  Method resolution order:
 |      MemoryReceiveChannel
 |      trio.abc.ReceiveChannel
 |      trio.abc.AsyncResource
 |      abc.ABC
 |      typing.Generic
 |      builtins.object
 |
 |  Methods defined here:
 |
 |  __attrs_post_init__(self) -> 'None'
 |
 |  __enter__(self) -> 'Self'
 |
 |  __exit__(self, exc_type: 'type[BaseException] | None', exc_value: 'BaseException | None', traceback: 'TracebackType | None') -> 'None'
 |
 |  __init__(self, state: 'MemoryChannelState[ReceiveType]', closed: 'bool' = False, tasks: 'set[trio._core._run.Task]' = NOTHING) -> None
 |      Method generated by attrs for class MemoryReceiveChannel.
 |
 |  __repr__(self) -> 'str'
 |      Return repr(self).
 |
 |  async aclose(self) -> 'None'
 |      Close this receive channel object asynchronously.
 |
 |      See `MemoryReceiveChannel.close`.
 |
 |  clone(self) -> 'MemoryReceiveChannel[ReceiveType]'
 |      Clone this receive channel object.
 |
 |      This returns a new `MemoryReceiveChannel` object, which acts as a
 |      duplicate of the original: receiving on the new object does exactly
 |      the same thing as receiving on the old object.
 |
 |      However, closing one of the objects does not close the other, and the
 |      underlying channel is not closed until all clones are closed. (If
 |      you're familiar with `os.dup`, then this is a similar idea.)
 |
 |      This is useful for communication patterns that involve multiple
 |      consumers all receiving objects from the same underlying channel. See
 |      :ref:`channel-mpmc` for examples.
 |
 |      .. warning:: The clones all share the same underlying channel.
 |         Whenever a clone :meth:`receive`\s a value, it is removed from the
 |         channel and the other clones do *not* receive that value. If you
 |         want to send multiple copies of the same stream of values to
 |         multiple destinations, like :func:`itertools.tee`, then you need to
 |         find some other solution; this method does *not* do that.
 |
 |      Raises:
 |        trio.ClosedResourceError: if you already closed this
 |            `MemoryReceiveChannel` object.
 |
 |  close(self) -> 'None'
 |      Close this receive channel object synchronously.
 |
 |      All channel objects have an asynchronous `~.AsyncResource.aclose` method.
 |      Memory channels can also be closed synchronously. This has the same
 |      effect on the channel and other tasks using it, but `close` is not a
 |      trio checkpoint. This simplifies cleaning up in cancelled tasks.
 |
 |      Using ``with receive_channel:`` will close the channel object on
 |      leaving the with block.
 |
 |  async receive(self) -> 'ReceiveType'
 |      See `ReceiveChannel.receive <trio.abc.ReceiveChannel.receive>`.
 |
 |      Memory channels allow multiple tasks to call `receive` at the same
 |      time. The first task will get the first item sent, the second task
 |      will get the second item sent, and so on.
 |
 |  receive_nowait(self) -> 'ReceiveType'
 |      Like `~trio.abc.ReceiveChannel.receive`, but if there's nothing
 |      ready to receive, raises `WouldBlock` instead of blocking.
 |
 |  statistics(self) -> 'MemoryChannelStatistics'
 |      Returns a `MemoryChannelStatistics` for the memory channel this is
 |      associated with.
 |
 |  ----------------------------------------------------------------------
 |  Class methods defined here:
 |
 |  __init_subclass__ = _init_final_cls() -> 'NoReturn' from trio._util
 |      Raises an exception when a final class is subclassed.
 |
 |  ----------------------------------------------------------------------
 |  Data descriptors defined here:
 |
 |  __dict__
 |      dictionary for instance variables
 |
 |  __weakref__
 |      list of weak references to the object
 |
 |  ----------------------------------------------------------------------
 |  Data and other attributes defined here:
 |
 |  __abstractmethods__ = frozenset()
 |
 |  __annotations__ = {'_closed': 'bool', '_state': 'MemoryChannelState[Re...
 |
 |  __attrs_attrs__ = (Attribute(name='_state', default=NOTHING, valid...i...
 |
 |  __final__ = True
 |
 |  __match_args__ = ('_state', '_closed', '_tasks')
 |
 |  __orig_bases__ = (trio.abc.ReceiveChannel[+ReceiveType],)
 |
 |  __parameters__ = (+ReceiveType,)
 |
 |  ----------------------------------------------------------------------
 |  Methods inherited from trio.abc.ReceiveChannel:
 |
 |  __aiter__(self) -> 'Self'
 |
 |  async __anext__(self) -> 'ReceiveType'
 |
 |  ----------------------------------------------------------------------
 |  Methods inherited from trio.abc.AsyncResource:
 |
 |  async __aenter__(self) -> 'Self'
 |
 |  async __aexit__(self, exc_type: 'type[BaseException] | None', exc_value: 'BaseException | None', traceback: 'TracebackType | None') -> 'None'
 |
 |  ----------------------------------------------------------------------
 |  Class methods inherited from typing.Generic:
 |
 |  __class_getitem__(...)
 |      Parameterizes a generic class.
 |
 |      At least, parameterizing a generic class is the *main* thing this
 |      method does. For example, for some generic class `Foo`, this is called
 |      when we do `Foo[int]` - there, with `cls=Foo` and `params=int`.
 |
 |      However, note that this method is also called when defining generic
 |      classes in the first place with `class Foo[T]: ...`.
trio.MemorySendChannel
Python Library Documentation: class MemorySendChannel in module trio

class MemorySendChannel(trio.abc.SendChannel)
 |  MemorySendChannel(*args: 'object', **kwargs: 'object') -> 'None'
 |
 |  Method resolution order:
 |      MemorySendChannel
 |      trio.abc.SendChannel
 |      trio.abc.AsyncResource
 |      abc.ABC
 |      typing.Generic
 |      builtins.object
 |
 |  Methods defined here:
 |
 |  __attrs_post_init__(self) -> 'None'
 |
 |  __enter__(self) -> 'Self'
 |
 |  __exit__(self, exc_type: 'type[BaseException] | None', exc_value: 'BaseException | None', traceback: 'TracebackType | None') -> 'None'
 |
 |  __init__(self, state: 'MemoryChannelState[SendType]', closed: 'bool' = False, tasks: 'set[Task]' = NOTHING) -> None
 |      Method generated by attrs for class MemorySendChannel.
 |
 |  __repr__(self) -> 'str'
 |      Return repr(self).
 |
 |  async aclose(self) -> 'None'
 |      Close this send channel object asynchronously.
 |
 |      See `MemorySendChannel.close`.
 |
 |  clone(self) -> 'MemorySendChannel[SendType]'
 |      Clone this send channel object.
 |
 |      This returns a new `MemorySendChannel` object, which acts as a
 |      duplicate of the original: sending on the new object does exactly the
 |      same thing as sending on the old object. (If you're familiar with
 |      `os.dup`, then this is a similar idea.)
 |
 |      However, closing one of the objects does not close the other, and
 |      receivers don't get `EndOfChannel` until *all* clones have been
 |      closed.
 |
 |      This is useful for communication patterns that involve multiple
 |      producers all sending objects to the same destination. If you give
 |      each producer its own clone of the `MemorySendChannel`, and then make
 |      sure to close each `MemorySendChannel` when it's finished, receivers
 |      will automatically get notified when all producers are finished. See
 |      :ref:`channel-mpmc` for examples.
 |
 |      Raises:
 |        trio.ClosedResourceError: if you already closed this
 |            `MemorySendChannel` object.
 |
 |  close(self) -> 'None'
 |      Close this send channel object synchronously.
 |
 |      All channel objects have an asynchronous `~.AsyncResource.aclose` method.
 |      Memory channels can also be closed synchronously. This has the same
 |      effect on the channel and other tasks using it, but `close` is not a
 |      trio checkpoint. This simplifies cleaning up in cancelled tasks.
 |
 |      Using ``with send_channel:`` will close the channel object on leaving
 |      the with block.
 |
 |  async send(self, value: 'SendType') -> 'None'
 |      See `SendChannel.send <trio.abc.SendChannel.send>`.
 |
 |      Memory channels allow multiple tasks to call `send` at the same time.
 |
 |  send_nowait(self, value: 'SendType') -> 'None'
 |      Like `~trio.abc.SendChannel.send`, but if the channel's buffer is
 |      full, raises `WouldBlock` instead of blocking.
 |
 |  statistics(self) -> 'MemoryChannelStatistics'
 |      Returns a `MemoryChannelStatistics` for the memory channel this is
 |      associated with.
 |
 |  ----------------------------------------------------------------------
 |  Class methods defined here:
 |
 |  __init_subclass__ = _init_final_cls() -> 'NoReturn' from trio._util
 |      Raises an exception when a final class is subclassed.
 |
 |  ----------------------------------------------------------------------
 |  Data descriptors defined here:
 |
 |  __dict__
 |      dictionary for instance variables
 |
 |  __weakref__
 |      list of weak references to the object
 |
 |  ----------------------------------------------------------------------
 |  Data and other attributes defined here:
 |
 |  __abstractmethods__ = frozenset()
 |
 |  __annotations__ = {'_closed': 'bool', '_state': 'MemoryChannelState[Se...
 |
 |  __attrs_attrs__ = (Attribute(name='_state', default=NOTHING, valid...i...
 |
 |  __final__ = True
 |
 |  __match_args__ = ('_state', '_closed', '_tasks')
 |
 |  __orig_bases__ = (trio.abc.SendChannel[-SendType],)
 |
 |  __parameters__ = (-SendType,)
 |
 |  ----------------------------------------------------------------------
 |  Methods inherited from trio.abc.AsyncResource:
 |
 |  async __aenter__(self) -> 'Self'
 |
 |  async __aexit__(self, exc_type: 'type[BaseException] | None', exc_value: 'BaseException | None', traceback: 'TracebackType | None') -> 'None'
 |
 |  ----------------------------------------------------------------------
 |  Class methods inherited from typing.Generic:
 |
 |  __class_getitem__(...)
 |      Parameterizes a generic class.
 |
 |      At least, parameterizing a generic class is the *main* thing this
 |      method does. For example, for some generic class `Foo`, this is called
 |      when we do `Foo[int]` - there, with `cls=Foo` and `params=int`.
 |
 |      However, note that this method is also called when defining generic
 |      classes in the first place with `class Foo[T]: ...`.
trio.NeedHandshakeError
Python Library Documentation: class NeedHandshakeError in module trio

class NeedHandshakeError(builtins.Exception)
 |  Some :class:`SSLStream` methods can't return any meaningful data until
 |  after the handshake. If you call them before the handshake, they raise
 |  this error.
 |
 |  Method resolution order:
 |      NeedHandshakeError
 |      builtins.Exception
 |      builtins.BaseException
 |      builtins.object
 |
 |  Data descriptors defined here:
 |
 |  __weakref__
 |      list of weak references to the object
 |
 |  ----------------------------------------------------------------------
 |  Methods inherited from builtins.Exception:
 |
 |  __init__(self, /, *args, **kwargs)
 |      Initialize self.  See help(type(self)) for accurate signature.
 |
 |  ----------------------------------------------------------------------
 |  Static methods inherited from builtins.Exception:
 |
 |  __new__(*args, **kwargs) class method of builtins.Exception
 |      Create and return a new object.  See help(type) for accurate signature.
 |
 |  ----------------------------------------------------------------------
 |  Methods inherited from builtins.BaseException:
 |
 |  __getattribute__(self, name, /)
 |      Return getattr(self, name).
 |
 |  __reduce__(...)
 |      Helper for pickle.
 |
 |  __repr__(self, /)
 |      Return repr(self).
 |
 |  __setstate__(...)
 |
 |  __str__(self, /)
 |      Return str(self).
 |
 |  add_note(...)
 |      Exception.add_note(note) --
 |      add a note to the exception
 |
 |  with_traceback(...)
 |      Exception.with_traceback(tb) --
 |      set self.__traceback__ to tb and return self.
 |
 |  ----------------------------------------------------------------------
 |  Data descriptors inherited from builtins.BaseException:
 |
 |  __cause__
 |      exception cause
 |
 |  __context__
 |      exception context
 |
 |  __dict__
 |
 |  __suppress_context__
 |
 |  __traceback__
 |
 |  args
trio.Nursery
Python Library Documentation: class Nursery in module trio

class Nursery(builtins.object)
 |  Nursery(*args: 'object', **kwargs: 'object') -> 'None'
 |
 |  A context which may be used to spawn (or cancel) child tasks.
 |
 |  Not constructed directly, use `open_nursery` instead.
 |
 |  The nursery will remain open until all child tasks have completed,
 |  or until it is cancelled, at which point it will cancel all its
 |  remaining child tasks and close.
 |
 |  Nurseries ensure the absence of orphaned Tasks, since all running
 |  tasks will belong to an open Nursery.
 |
 |  Attributes:
 |      cancel_scope:
 |          Creating a nursery also implicitly creates a cancellation scope,
 |          which is exposed as the :attr:`cancel_scope` attribute. This is
 |          used internally to implement the logic where if an error occurs
 |          then ``__aexit__`` cancels all children, but you can use it for
 |          other things, e.g. if you want to explicitly cancel all children
 |          in response to some external event.
 |
 |  Methods defined here:
 |
 |  __del__(self) -> 'None'
 |
 |  __init__(self, parent_task: 'Task', cancel_scope: 'CancelScope', strict_exception_groups: 'bool') -> 'None'
 |      Initialize self.  See help(type(self)) for accurate signature.
 |
 |  async start(self, async_fn: 'Callable[..., Awaitable[object]]', *args: 'object', name: 'object' = None) -> 'Any'
 |      Creates and initializes a child task.
 |
 |      Like :meth:`start_soon`, but blocks until the new task has
 |      finished initializing itself, and optionally returns some
 |      information from it.
 |
 |      The ``async_fn`` must accept a ``task_status`` keyword argument,
 |      and it must make sure that it (or someone) eventually calls
 |      :meth:`task_status.started() <TaskStatus.started>`.
 |
 |      The conventional way to define ``async_fn`` is like::
 |
 |          async def async_fn(arg1, arg2, *, task_status=trio.TASK_STATUS_IGNORED):
 |              ...  # Caller is blocked waiting for this code to run
 |              task_status.started()
 |              ...  # This async code can be interleaved with the caller
 |
 |      :attr:`trio.TASK_STATUS_IGNORED` is a special global object with
 |      a do-nothing ``started`` method. This way your function supports
 |      being called either like ``await nursery.start(async_fn, arg1,
 |      arg2)`` or directly like ``await async_fn(arg1, arg2)``, and
 |      either way it can call :meth:`task_status.started() <TaskStatus.started>`
 |      without worrying about which mode it's in. Defining your function like
 |      this will make it obvious to readers that it supports being used
 |      in both modes.
 |
 |      Before the child calls :meth:`task_status.started() <TaskStatus.started>`,
 |      it's effectively run underneath the call to :meth:`start`: if it
 |      raises an exception then that exception is reported by
 |      :meth:`start`, and does *not* propagate out of the nursery. If
 |      :meth:`start` is cancelled, then the child task is also
 |      cancelled.
 |
 |      When the child calls :meth:`task_status.started() <TaskStatus.started>`,
 |      it's moved out from underneath :meth:`start` and into the given nursery.
 |
 |      If the child task passes a value to :meth:`task_status.started(value) <TaskStatus.started>`,
 |      then :meth:`start` returns this value. Otherwise, it returns ``None``.
 |
 |  start_soon(self, async_fn: 'Callable[[Unpack[PosArgT]], Awaitable[object]]', *args: 'Unpack[PosArgT]', name: 'object' = None) -> 'None'
 |      Creates a child task, scheduling ``await async_fn(*args)``.
 |
 |      If you want to run a function and immediately wait for its result,
 |      then you don't need a nursery; just use ``await async_fn(*args)``.
 |      If you want to wait for the task to initialize itself before
 |      continuing, see :meth:`start`, the other fundamental method for
 |      creating concurrent tasks in Trio.
 |
 |      Note that this is *not* an async function and you don't use await
 |      when calling it. It sets up the new task, but then returns
 |      immediately, *before* the new task has a chance to do anything.
 |      New tasks may start running in any order, and at any checkpoint the
 |      scheduler chooses - at latest when the nursery is waiting to exit.
 |
 |      It's possible to pass a nursery object into another task, which
 |      allows that task to start new child tasks in the first task's
 |      nursery.
 |
 |      The child task inherits its parent nursery's cancel scopes.
 |
 |      Args:
 |          async_fn: An async callable.
 |          args: Positional arguments for ``async_fn``. If you want
 |                to pass keyword arguments, use
 |                :func:`functools.partial`.
 |          name: The name for this task. Only used for
 |                debugging/introspection
 |                (e.g. ``repr(task_obj)``). If this isn't a string,
 |                :meth:`start_soon` will try to make it one. A
 |                common use case is if you're wrapping a function
 |                before spawning a new task, you might pass the
 |                original function as the ``name=`` to make
 |                debugging easier.
 |
 |      Raises:
 |          RuntimeError: If this nursery is no longer open
 |                        (i.e. its ``async with`` block has
 |                        exited).
 |
 |  ----------------------------------------------------------------------
 |  Class methods defined here:
 |
 |  __init_subclass__ = _init_final_cls() -> 'NoReturn' from trio._util
 |      Raises an exception when a final class is subclassed.
 |
 |  ----------------------------------------------------------------------
 |  Readonly properties defined here:
 |
 |  child_tasks
 |      (`frozenset`): Contains all the child :class:`~trio.lowlevel.Task`
 |      objects which are still running.
 |
 |  parent_task
 |      (`~trio.lowlevel.Task`):  The Task that opened this nursery.
 |
 |  ----------------------------------------------------------------------
 |  Data descriptors defined here:
 |
 |  __dict__
 |      dictionary for instance variables
 |
 |  __weakref__
 |      list of weak references to the object
 |
 |  ----------------------------------------------------------------------
 |  Data and other attributes defined here:
 |
 |  __abstractmethods__ = frozenset()
 |
 |  __final__ = True
trio.Path
Python Library Documentation: class Path in module trio

class Path(pathlib.PurePath)
 |  Path(*args: 'str | os.PathLike[str]') -> 'Self'
 |
 |  An async :class:`pathlib.Path` that executes blocking methods in :meth:`trio.to_thread.run_sync`.
 |
 |  Instantiating :class:`Path` returns a concrete platform-specific subclass, one of :class:`PosixPath` or
 |  :class:`WindowsPath`.
 |
 |  Method resolution order:
 |      Path
 |      pathlib.PurePath
 |      builtins.object
 |
 |  Methods defined here:
 |
 |  __repr__(self) -> 'str'
 |      Return repr(self).
 |
 |  async absolute(self) from pathlib.Path
 |      Like :meth:`~pathlib.Path.absolute`, but async.
 |
 |      Return an absolute version of this path by prepending the current
 |      working directory. No normalization or symlink resolution is performed.
 |
 |      Use resolve() to get the canonical path to a file.
 |
 |  as_uri(self) -> 'str'
 |      Return the path as a 'file' URI.
 |
 |  async chmod(self, mode, *, follow_symlinks=True) from pathlib.Path
 |      Like :meth:`~pathlib.Path.chmod`, but async.
 |
 |      Change the permissions of the path, like os.chmod().
 |
 |  async exists(self, *, follow_symlinks=True) from pathlib.Path
 |      Like :meth:`~pathlib.Path.exists`, but async.
 |
 |      Whether this path exists.
 |
 |      This method normally follows symlinks; to check whether a symlink exists,
 |      add the argument follow_symlinks=False.
 |
 |  async expanduser(self) from pathlib.Path
 |      Like :meth:`~pathlib.Path.expanduser`, but async.
 |
 |      Return a new path with expanded ~ and ~user constructs
 |      (as returned by os.path.expanduser)
 |
 |  async glob(self, pattern, *, case_sensitive=None) from pathlib.Path
 |      Like :meth:`~pathlib.Path.glob`, but async.
 |
 |      Iterate over this subtree and yield all existing files (of any
 |      kind, including directories) matching the given relative pattern.
 |
 |      This is an async method that returns a synchronous iterator, so you
 |      use it like:
 |
 |      .. code:: python
 |
 |          for subpath in await mypath.glob():
 |              ...
 |
 |      .. note::
 |
 |          The iterator is loaded into memory immediately during the initial
 |          call (see `issue #501
 |          <https://github.com/python-trio/trio/issues/501>`__ for discussion).
 |
 |  async hardlink_to(self, target) from pathlib.Path
 |      Like :meth:`~pathlib.Path.hardlink_to`, but async.
 |
 |      Make this path a hard link pointing to the same file as *target*.
 |
 |      Note the order of arguments (self, target) is the reverse of os.link's.
 |
 |  async is_block_device(self) from pathlib.Path
 |      Like :meth:`~pathlib.Path.is_block_device`, but async.
 |
 |      Whether this path is a block device.
 |
 |  async is_char_device(self) from pathlib.Path
 |      Like :meth:`~pathlib.Path.is_char_device`, but async.
 |
 |      Whether this path is a character device.
 |
 |  async is_dir(self) from pathlib.Path
 |      Like :meth:`~pathlib.Path.is_dir`, but async.
 |
 |      Whether this path is a directory.
 |
 |  async is_fifo(self) from pathlib.Path
 |      Like :meth:`~pathlib.Path.is_fifo`, but async.
 |
 |      Whether this path is a FIFO.
 |
 |  async is_file(self) from pathlib.Path
 |      Like :meth:`~pathlib.Path.is_file`, but async.
 |
 |      Whether this path is a regular file (also True for symlinks pointing
 |      to regular files).
 |
 |  async is_junction(self) from pathlib.Path
 |      Like :meth:`~pathlib.Path.is_junction`, but async.
 |
 |      Whether this path is a junction.
 |
 |  async is_mount(self) from pathlib.Path
 |      Like :meth:`~pathlib.Path.is_mount`, but async.
 |
 |      Check if this path is a mount point
 |
 |  async is_socket(self) from pathlib.Path
 |      Like :meth:`~pathlib.Path.is_socket`, but async.
 |
 |      Whether this path is a socket.
 |
 |  async is_symlink(self) from pathlib.Path
 |      Like :meth:`~pathlib.Path.is_symlink`, but async.
 |
 |      Whether this path is a symbolic link.
 |
 |  async iterdir(self) from pathlib.Path
 |      Like :meth:`~pathlib.Path.iterdir`, but async.
 |
 |      Yield path objects of the directory contents.
 |
 |      The children are yielded in arbitrary order, and the
 |      special entries '.' and '..' are not included.
 |
 |      This is an async method that returns a synchronous iterator, so you
 |      use it like:
 |
 |      .. code:: python
 |
 |          for subpath in await mypath.iterdir():
 |              ...
 |
 |      .. note::
 |
 |          The iterator is loaded into memory immediately during the initial
 |          call (see `issue #501
 |          <https://github.com/python-trio/trio/issues/501>`__ for discussion).
 |
 |  async lchmod(self, mode) from pathlib.Path
 |      Like :meth:`~pathlib.Path.lchmod`, but async.
 |
 |      Like chmod(), except if the path points to a symlink, the symlink's
 |      permissions are changed, rather than its target's.
 |
 |  async lstat(self) from pathlib.Path
 |      Like :meth:`~pathlib.Path.lstat`, but async.
 |
 |      Like stat(), except if the path points to a symlink, the symlink's
 |      status information is returned, rather than its target's.
 |
 |  async mkdir(self, mode=511, parents=False, exist_ok=False) from pathlib.Path
 |      Like :meth:`~pathlib.Path.mkdir`, but async.
 |
 |      Create a new directory at this given path.
 |
 |  async open(self, mode='r', buffering=-1, encoding=None, errors=None, newline=None) from pathlib.Path
 |      Like :meth:`~pathlib.Path.open`, but async.
 |
 |      Open the file pointed to by this path and return a file object, as
 |      the built-in open() function does.
 |
 |  async read_bytes(self) from pathlib.Path
 |      Like :meth:`~pathlib.Path.read_bytes`, but async.
 |
 |      Open the file in bytes mode, read it, and close the file.
 |
 |  async read_text(self, encoding=None, errors=None) from pathlib.Path
 |      Like :meth:`~pathlib.Path.read_text`, but async.
 |
 |      Open the file in text mode, read it, and close the file.
 |
 |  async readlink(self) from pathlib.Path
 |      Like :meth:`~pathlib.Path.readlink`, but async.
 |
 |      Return the path to which the symbolic link points.
 |
 |  async rename(self, target) from pathlib.Path
 |      Like :meth:`~pathlib.Path.rename`, but async.
 |
 |      Rename this path to the target path.
 |
 |      The target path may be absolute or relative. Relative paths are
 |      interpreted relative to the current working directory, *not* the
 |      directory of the Path object.
 |
 |      Returns the new Path instance pointing to the target path.
 |
 |  async replace(self, target) from pathlib.Path
 |      Like :meth:`~pathlib.Path.replace`, but async.
 |
 |      Rename this path to the target path, overwriting if that path exists.
 |
 |      The target path may be absolute or relative. Relative paths are
 |      interpreted relative to the current working directory, *not* the
 |      directory of the Path object.
 |
 |      Returns the new Path instance pointing to the target path.
 |
 |  async resolve(self, strict=False) from pathlib.Path
 |      Like :meth:`~pathlib.Path.resolve`, but async.
 |
 |      Make the path absolute, resolving all symlinks on the way and also
 |      normalizing it.
 |
 |  async rglob(self, pattern, *, case_sensitive=None) from pathlib.Path
 |      Like :meth:`~pathlib.Path.rglob`, but async.
 |
 |      Recursively yield all existing files (of any kind, including
 |      directories) matching the given relative pattern, anywhere in
 |      this subtree.
 |
 |      This is an async method that returns a synchronous iterator, so you
 |      use it like:
 |
 |      .. code:: python
 |
 |          for subpath in await mypath.rglob():
 |              ...
 |
 |      .. note::
 |
 |          The iterator is loaded into memory immediately during the initial
 |          call (see `issue #501
 |          <https://github.com/python-trio/trio/issues/501>`__ for discussion).
 |
 |  async rmdir(self) from pathlib.Path
 |      Like :meth:`~pathlib.Path.rmdir`, but async.
 |
 |      Remove this directory.  The directory must be empty.
 |
 |  async samefile(self, other_path) from pathlib.Path
 |      Like :meth:`~pathlib.Path.samefile`, but async.
 |
 |      Return whether other_path is the same or not as this file
 |      (as returned by os.path.samefile()).
 |
 |  async stat(self, *, follow_symlinks=True) from pathlib.Path
 |      Like :meth:`~pathlib.Path.stat`, but async.
 |
 |      Return the result of the stat() system call on this path, like
 |      os.stat() does.
 |
 |  async symlink_to(self, target, target_is_directory=False) from pathlib.Path
 |      Like :meth:`~pathlib.Path.symlink_to`, but async.
 |
 |      Make this path a symlink pointing to the target path.
 |      Note the order of arguments (link, target) is the reverse of os.symlink.
 |
 |  async touch(self, mode=438, exist_ok=True) from pathlib.Path
 |      Like :meth:`~pathlib.Path.touch`, but async.
 |
 |      Create this file with the given access mode, if it doesn't exist.
 |
 |  async unlink(self, missing_ok=False) from pathlib.Path
 |      Like :meth:`~pathlib.Path.unlink`, but async.
 |
 |      Remove this file or link.
 |      If the path is a directory, use rmdir() instead.
 |
 |  async write_bytes(self, data) from pathlib.Path
 |      Like :meth:`~pathlib.Path.write_bytes`, but async.
 |
 |      Open the file in bytes mode, write to it, and close the file.
 |
 |  async write_text(self, data, encoding=None, errors=None, newline=None) from pathlib.Path
 |      Like :meth:`~pathlib.Path.write_text`, but async.
 |
 |      Open the file in text mode, write to it, and close the file.
 |
 |  ----------------------------------------------------------------------
 |  Class methods defined here:
 |
 |  async cwd(...) from pathlib.Path
 |      Like :meth:`~pathlib.Path.cwd`, but async.
 |
 |      Return a new path pointing to the current working directory.
 |
 |  async home(...) from pathlib.Path
 |      Like :meth:`~pathlib.Path.home`, but async.
 |
 |      Return a new path pointing to the user's home directory (as
 |      returned by os.path.expanduser('~')).
 |
 |  ----------------------------------------------------------------------
 |  Static methods defined here:
 |
 |  __new__(cls, *args: 'str | os.PathLike[str]') -> 'Self' from trio._path.Path
 |      Construct a PurePath from one or several strings and or existing
 |      PurePath objects.  The strings and path objects are combined so as
 |      to yield a canonicalized path, which is incorporated into the
 |      new PurePath object.
 |
 |  ----------------------------------------------------------------------
 |  Data and other attributes defined here:
 |
 |  __annotations__ = {'_wrapped_cls': 'ClassVar[type[pathlib.Path]]'}
 |
 |  ----------------------------------------------------------------------
 |  Methods inherited from pathlib.PurePath:
 |
 |  __bytes__(self)
 |      Return the bytes representation of the path.  This is only
 |      recommended to use under Unix.
 |
 |  __eq__(self, other)
 |      Return self==value.
 |
 |  __fspath__(self)
 |
 |  __ge__(self, other)
 |      Return self>=value.
 |
 |  __gt__(self, other)
 |      Return self>value.
 |
 |  __hash__(self)
 |      Return hash(self).
 |
 |  __init__(self, *args)
 |      Initialize self.  See help(type(self)) for accurate signature.
 |
 |  __le__(self, other)
 |      Return self<=value.
 |
 |  __lt__(self, other)
 |      Return self<value.
 |
 |  __reduce__(self)
 |      Helper for pickle.
 |
 |  __rtruediv__(self, key)
 |
 |  __str__(self)
 |      Return the string representation of the path, suitable for
 |      passing to system calls.
 |
 |  __truediv__(self, key)
 |
 |  as_posix(self)
 |      Return the string representation of the path with forward (/)
 |      slashes.
 |
 |  is_absolute(self)
 |      True if the path is absolute (has both a root and, if applicable,
 |      a drive).
 |
 |  is_relative_to(self, other, /, *_deprecated)
 |      Return True if the path is relative to another path or False.
 |
 |  is_reserved(self)
 |      Return True if the path contains one of the special names reserved
 |      by the system, if any.
 |
 |  joinpath(self, *pathsegments)
 |      Combine this path with one or several arguments, and return a
 |      new path representing either a subpath (if all arguments are relative
 |      paths) or a totally different path (if one of the arguments is
 |      anchored).
 |
 |  match(self, path_pattern, *, case_sensitive=None)
 |      Return True if this path matches the given pattern.
 |
 |  relative_to(self, other, /, *_deprecated, walk_up=False)
 |      Return the relative path to another path identified by the passed
 |      arguments.  If the operation is not possible (because this is not
 |      related to the other path), raise ValueError.
 |
 |      The *walk_up* parameter controls whether ``..`` may be used to resolve
 |      the path.
 |
 |  with_name(self, name)
 |      Return a new path with the file name changed.
 |
 |  with_segments(self, *pathsegments)
 |      Construct a new path object from any number of path-like objects.
 |      Subclasses may override this method to customize how new path objects
 |      are created from methods like `iterdir()`.
 |
 |  with_stem(self, stem)
 |      Return a new path with the stem changed.
 |
 |  with_suffix(self, suffix)
 |      Return a new path with the file suffix changed.  If the path
 |      has no suffix, add given suffix.  If the given suffix is an empty
 |      string, remove the suffix from the path.
 |
 |  ----------------------------------------------------------------------
 |  Readonly properties inherited from pathlib.PurePath:
 |
 |  anchor
 |      The concatenation of the drive and root, or ''.
 |
 |  drive
 |      The drive prefix (letter or UNC path), if any.
 |
 |  name
 |      The final path component, if any.
 |
 |  parent
 |      The logical parent of the path.
 |
 |  parents
 |      A sequence of this path's logical parents.
 |
 |  parts
 |      An object providing sequence-like access to the
 |      components in the filesystem path.
 |
 |  root
 |      The root of the path, if any.
 |
 |  stem
 |      The final path component, minus its last suffix.
 |
 |  suffix
 |      The final component's last suffix, if any.
 |
 |      This includes the leading period. For example: '.txt'
 |
 |  suffixes
 |      A list of the final component's suffixes, if any.
 |
 |      These include the leading periods. For example: ['.tar', '.gz']
trio.PosixPath
Python Library Documentation: class PosixPath in module trio

class PosixPath(Path, pathlib.PurePosixPath)
 |  PosixPath(*args: 'str | os.PathLike[str]') -> 'Self'
 |
 |  An async :class:`pathlib.PosixPath` that executes blocking methods in :meth:`trio.to_thread.run_sync`.
 |
 |  Method resolution order:
 |      PosixPath
 |      Path
 |      pathlib.PurePosixPath
 |      pathlib.PurePath
 |      builtins.object
 |
 |  Class methods defined here:
 |
 |  __init_subclass__ = _init_final_cls() -> 'NoReturn' from trio._util
 |      Raises an exception when a final class is subclassed.
 |
 |  ----------------------------------------------------------------------
 |  Data and other attributes defined here:
 |
 |  __annotations__ = {'_wrapped_cls': 'ClassVar[type[pathlib.Path]]'}
 |
 |  __final__ = True
 |
 |  ----------------------------------------------------------------------
 |  Methods inherited from Path:
 |
 |  __repr__(self) -> 'str'
 |      Return repr(self).
 |
 |  async absolute(self) from pathlib.Path
 |      Like :meth:`~pathlib.Path.absolute`, but async.
 |
 |      Return an absolute version of this path by prepending the current
 |      working directory. No normalization or symlink resolution is performed.
 |
 |      Use resolve() to get the canonical path to a file.
 |
 |  as_uri(self) -> 'str'
 |      Return the path as a 'file' URI.
 |
 |  async chmod(self, mode, *, follow_symlinks=True) from pathlib.Path
 |      Like :meth:`~pathlib.Path.chmod`, but async.
 |
 |      Change the permissions of the path, like os.chmod().
 |
 |  async exists(self, *, follow_symlinks=True) from pathlib.Path
 |      Like :meth:`~pathlib.Path.exists`, but async.
 |
 |      Whether this path exists.
 |
 |      This method normally follows symlinks; to check whether a symlink exists,
 |      add the argument follow_symlinks=False.
 |
 |  async expanduser(self) from pathlib.Path
 |      Like :meth:`~pathlib.Path.expanduser`, but async.
 |
 |      Return a new path with expanded ~ and ~user constructs
 |      (as returned by os.path.expanduser)
 |
 |  async glob(self, pattern, *, case_sensitive=None) from pathlib.Path
 |      Like :meth:`~pathlib.Path.glob`, but async.
 |
 |      Iterate over this subtree and yield all existing files (of any
 |      kind, including directories) matching the given relative pattern.
 |
 |      This is an async method that returns a synchronous iterator, so you
 |      use it like:
 |
 |      .. code:: python
 |
 |          for subpath in await mypath.glob():
 |              ...
 |
 |      .. note::
 |
 |          The iterator is loaded into memory immediately during the initial
 |          call (see `issue #501
 |          <https://github.com/python-trio/trio/issues/501>`__ for discussion).
 |
 |  async hardlink_to(self, target) from pathlib.Path
 |      Like :meth:`~pathlib.Path.hardlink_to`, but async.
 |
 |      Make this path a hard link pointing to the same file as *target*.
 |
 |      Note the order of arguments (self, target) is the reverse of os.link's.
 |
 |  async is_block_device(self) from pathlib.Path
 |      Like :meth:`~pathlib.Path.is_block_device`, but async.
 |
 |      Whether this path is a block device.
 |
 |  async is_char_device(self) from pathlib.Path
 |      Like :meth:`~pathlib.Path.is_char_device`, but async.
 |
 |      Whether this path is a character device.
 |
 |  async is_dir(self) from pathlib.Path
 |      Like :meth:`~pathlib.Path.is_dir`, but async.
 |
 |      Whether this path is a directory.
 |
 |  async is_fifo(self) from pathlib.Path
 |      Like :meth:`~pathlib.Path.is_fifo`, but async.
 |
 |      Whether this path is a FIFO.
 |
 |  async is_file(self) from pathlib.Path
 |      Like :meth:`~pathlib.Path.is_file`, but async.
 |
 |      Whether this path is a regular file (also True for symlinks pointing
 |      to regular files).
 |
 |  async is_junction(self) from pathlib.Path
 |      Like :meth:`~pathlib.Path.is_junction`, but async.
 |
 |      Whether this path is a junction.
 |
 |  async is_mount(self) from pathlib.Path
 |      Like :meth:`~pathlib.Path.is_mount`, but async.
 |
 |      Check if this path is a mount point
 |
 |  async is_socket(self) from pathlib.Path
 |      Like :meth:`~pathlib.Path.is_socket`, but async.
 |
 |      Whether this path is a socket.
 |
 |  async is_symlink(self) from pathlib.Path
 |      Like :meth:`~pathlib.Path.is_symlink`, but async.
 |
 |      Whether this path is a symbolic link.
 |
 |  async iterdir(self) from pathlib.Path
 |      Like :meth:`~pathlib.Path.iterdir`, but async.
 |
 |      Yield path objects of the directory contents.
 |
 |      The children are yielded in arbitrary order, and the
 |      special entries '.' and '..' are not included.
 |
 |      This is an async method that returns a synchronous iterator, so you
 |      use it like:
 |
 |      .. code:: python
 |
 |          for subpath in await mypath.iterdir():
 |              ...
 |
 |      .. note::
 |
 |          The iterator is loaded into memory immediately during the initial
 |          call (see `issue #501
 |          <https://github.com/python-trio/trio/issues/501>`__ for discussion).
 |
 |  async lchmod(self, mode) from pathlib.Path
 |      Like :meth:`~pathlib.Path.lchmod`, but async.
 |
 |      Like chmod(), except if the path points to a symlink, the symlink's
 |      permissions are changed, rather than its target's.
 |
 |  async lstat(self) from pathlib.Path
 |      Like :meth:`~pathlib.Path.lstat`, but async.
 |
 |      Like stat(), except if the path points to a symlink, the symlink's
 |      status information is returned, rather than its target's.
 |
 |  async mkdir(self, mode=511, parents=False, exist_ok=False) from pathlib.Path
 |      Like :meth:`~pathlib.Path.mkdir`, but async.
 |
 |      Create a new directory at this given path.
 |
 |  async open(self, mode='r', buffering=-1, encoding=None, errors=None, newline=None) from pathlib.Path
 |      Like :meth:`~pathlib.Path.open`, but async.
 |
 |      Open the file pointed to by this path and return a file object, as
 |      the built-in open() function does.
 |
 |  async read_bytes(self) from pathlib.Path
 |      Like :meth:`~pathlib.Path.read_bytes`, but async.
 |
 |      Open the file in bytes mode, read it, and close the file.
 |
 |  async read_text(self, encoding=None, errors=None) from pathlib.Path
 |      Like :meth:`~pathlib.Path.read_text`, but async.
 |
 |      Open the file in text mode, read it, and close the file.
 |
 |  async readlink(self) from pathlib.Path
 |      Like :meth:`~pathlib.Path.readlink`, but async.
 |
 |      Return the path to which the symbolic link points.
 |
 |  async rename(self, target) from pathlib.Path
 |      Like :meth:`~pathlib.Path.rename`, but async.
 |
 |      Rename this path to the target path.
 |
 |      The target path may be absolute or relative. Relative paths are
 |      interpreted relative to the current working directory, *not* the
 |      directory of the Path object.
 |
 |      Returns the new Path instance pointing to the target path.
 |
 |  async replace(self, target) from pathlib.Path
 |      Like :meth:`~pathlib.Path.replace`, but async.
 |
 |      Rename this path to the target path, overwriting if that path exists.
 |
 |      The target path may be absolute or relative. Relative paths are
 |      interpreted relative to the current working directory, *not* the
 |      directory of the Path object.
 |
 |      Returns the new Path instance pointing to the target path.
 |
 |  async resolve(self, strict=False) from pathlib.Path
 |      Like :meth:`~pathlib.Path.resolve`, but async.
 |
 |      Make the path absolute, resolving all symlinks on the way and also
 |      normalizing it.
 |
 |  async rglob(self, pattern, *, case_sensitive=None) from pathlib.Path
 |      Like :meth:`~pathlib.Path.rglob`, but async.
 |
 |      Recursively yield all existing files (of any kind, including
 |      directories) matching the given relative pattern, anywhere in
 |      this subtree.
 |
 |      This is an async method that returns a synchronous iterator, so you
 |      use it like:
 |
 |      .. code:: python
 |
 |          for subpath in await mypath.rglob():
 |              ...
 |
 |      .. note::
 |
 |          The iterator is loaded into memory immediately during the initial
 |          call (see `issue #501
 |          <https://github.com/python-trio/trio/issues/501>`__ for discussion).
 |
 |  async rmdir(self) from pathlib.Path
 |      Like :meth:`~pathlib.Path.rmdir`, but async.
 |
 |      Remove this directory.  The directory must be empty.
 |
 |  async samefile(self, other_path) from pathlib.Path
 |      Like :meth:`~pathlib.Path.samefile`, but async.
 |
 |      Return whether other_path is the same or not as this file
 |      (as returned by os.path.samefile()).
 |
 |  async stat(self, *, follow_symlinks=True) from pathlib.Path
 |      Like :meth:`~pathlib.Path.stat`, but async.
 |
 |      Return the result of the stat() system call on this path, like
 |      os.stat() does.
 |
 |  async symlink_to(self, target, target_is_directory=False) from pathlib.Path
 |      Like :meth:`~pathlib.Path.symlink_to`, but async.
 |
 |      Make this path a symlink pointing to the target path.
 |      Note the order of arguments (link, target) is the reverse of os.symlink.
 |
 |  async touch(self, mode=438, exist_ok=True) from pathlib.Path
 |      Like :meth:`~pathlib.Path.touch`, but async.
 |
 |      Create this file with the given access mode, if it doesn't exist.
 |
 |  async unlink(self, missing_ok=False) from pathlib.Path
 |      Like :meth:`~pathlib.Path.unlink`, but async.
 |
 |      Remove this file or link.
 |      If the path is a directory, use rmdir() instead.
 |
 |  async write_bytes(self, data) from pathlib.Path
 |      Like :meth:`~pathlib.Path.write_bytes`, but async.
 |
 |      Open the file in bytes mode, write to it, and close the file.
 |
 |  async write_text(self, data, encoding=None, errors=None, newline=None) from pathlib.Path
 |      Like :meth:`~pathlib.Path.write_text`, but async.
 |
 |      Open the file in text mode, write to it, and close the file.
 |
 |  ----------------------------------------------------------------------
 |  Class methods inherited from Path:
 |
 |  async cwd(...) from pathlib.Path
 |      Like :meth:`~pathlib.Path.cwd`, but async.
 |
 |      Return a new path pointing to the current working directory.
 |
 |  async home(...) from pathlib.Path
 |      Like :meth:`~pathlib.Path.home`, but async.
 |
 |      Return a new path pointing to the user's home directory (as
 |      returned by os.path.expanduser('~')).
 |
 |  ----------------------------------------------------------------------
 |  Static methods inherited from Path:
 |
 |  __new__(cls, *args: 'str | os.PathLike[str]') -> 'Self' from trio._path.Path
 |      Construct a PurePath from one or several strings and or existing
 |      PurePath objects.  The strings and path objects are combined so as
 |      to yield a canonicalized path, which is incorporated into the
 |      new PurePath object.
 |
 |  ----------------------------------------------------------------------
 |  Methods inherited from pathlib.PurePath:
 |
 |  __bytes__(self)
 |      Return the bytes representation of the path.  This is only
 |      recommended to use under Unix.
 |
 |  __eq__(self, other)
 |      Return self==value.
 |
 |  __fspath__(self)
 |
 |  __ge__(self, other)
 |      Return self>=value.
 |
 |  __gt__(self, other)
 |      Return self>value.
 |
 |  __hash__(self)
 |      Return hash(self).
 |
 |  __init__(self, *args)
 |      Initialize self.  See help(type(self)) for accurate signature.
 |
 |  __le__(self, other)
 |      Return self<=value.
 |
 |  __lt__(self, other)
 |      Return self<value.
 |
 |  __reduce__(self)
 |      Helper for pickle.
 |
 |  __rtruediv__(self, key)
 |
 |  __str__(self)
 |      Return the string representation of the path, suitable for
 |      passing to system calls.
 |
 |  __truediv__(self, key)
 |
 |  as_posix(self)
 |      Return the string representation of the path with forward (/)
 |      slashes.
 |
 |  is_absolute(self)
 |      True if the path is absolute (has both a root and, if applicable,
 |      a drive).
 |
 |  is_relative_to(self, other, /, *_deprecated)
 |      Return True if the path is relative to another path or False.
 |
 |  is_reserved(self)
 |      Return True if the path contains one of the special names reserved
 |      by the system, if any.
 |
 |  joinpath(self, *pathsegments)
 |      Combine this path with one or several arguments, and return a
 |      new path representing either a subpath (if all arguments are relative
 |      paths) or a totally different path (if one of the arguments is
 |      anchored).
 |
 |  match(self, path_pattern, *, case_sensitive=None)
 |      Return True if this path matches the given pattern.
 |
 |  relative_to(self, other, /, *_deprecated, walk_up=False)
 |      Return the relative path to another path identified by the passed
 |      arguments.  If the operation is not possible (because this is not
 |      related to the other path), raise ValueError.
 |
 |      The *walk_up* parameter controls whether ``..`` may be used to resolve
 |      the path.
 |
 |  with_name(self, name)
 |      Return a new path with the file name changed.
 |
 |  with_segments(self, *pathsegments)
 |      Construct a new path object from any number of path-like objects.
 |      Subclasses may override this method to customize how new path objects
 |      are created from methods like `iterdir()`.
 |
 |  with_stem(self, stem)
 |      Return a new path with the stem changed.
 |
 |  with_suffix(self, suffix)
 |      Return a new path with the file suffix changed.  If the path
 |      has no suffix, add given suffix.  If the given suffix is an empty
 |      string, remove the suffix from the path.
 |
 |  ----------------------------------------------------------------------
 |  Readonly properties inherited from pathlib.PurePath:
 |
 |  anchor
 |      The concatenation of the drive and root, or ''.
 |
 |  drive
 |      The drive prefix (letter or UNC path), if any.
 |
 |  name
 |      The final path component, if any.
 |
 |  parent
 |      The logical parent of the path.
 |
 |  parents
 |      A sequence of this path's logical parents.
 |
 |  parts
 |      An object providing sequence-like access to the
 |      components in the filesystem path.
 |
 |  root
 |      The root of the path, if any.
 |
 |  stem
 |      The final path component, minus its last suffix.
 |
 |  suffix
 |      The final component's last suffix, if any.
 |
 |      This includes the leading period. For example: '.txt'
 |
 |  suffixes
 |      A list of the final component's suffixes, if any.
 |
 |      These include the leading periods. For example: ['.tar', '.gz']
trio.Process
Python Library Documentation: class Process in module trio

class Process(builtins.object)
 |  Process(*args: 'object', **kwargs: 'object') -> 'None'
 |
 |  A child process. Like :class:`subprocess.Popen`, but async.
 |
 |  This class has no public constructor. The most common way to get a
 |  `Process` object is to combine `Nursery.start` with `run_process`::
 |
 |     process_object = await nursery.start(run_process, ...)
 |
 |  This way, `run_process` supervises the process and makes sure that it is
 |  cleaned up properly, while optionally checking the return value, feeding
 |  it input, and so on.
 |
 |  If you need more control – for example, because you want to spawn a child
 |  process that outlives your program – then another option is to use
 |  `trio.lowlevel.open_process`::
 |
 |     process_object = await trio.lowlevel.open_process(...)
 |
 |  Attributes:
 |    args (str or list): The ``command`` passed at construction time,
 |        specifying the process to execute and its arguments.
 |    pid (int): The process ID of the child process managed by this object.
 |    stdin (trio.abc.SendStream or None): A stream connected to the child's
 |        standard input stream: when you write bytes here, they become available
 |        for the child to read. Only available if the :class:`Process`
 |        was constructed using ``stdin=PIPE``; otherwise this will be None.
 |    stdout (trio.abc.ReceiveStream or None): A stream connected to
 |        the child's standard output stream: when the child writes to
 |        standard output, the written bytes become available for you
 |        to read here. Only available if the :class:`Process` was
 |        constructed using ``stdout=PIPE``; otherwise this will be None.
 |    stderr (trio.abc.ReceiveStream or None): A stream connected to
 |        the child's standard error stream: when the child writes to
 |        standard error, the written bytes become available for you
 |        to read here. Only available if the :class:`Process` was
 |        constructed using ``stderr=PIPE``; otherwise this will be None.
 |    stdio (trio.StapledStream or None): A stream that sends data to
 |        the child's standard input and receives from the child's standard
 |        output. Only available if both :attr:`stdin` and :attr:`stdout` are
 |        available; otherwise this will be None.
 |
 |  Methods defined here:
 |
 |  __init__(self, popen: 'subprocess.Popen[bytes]', stdin: 'SendStream | None', stdout: 'ReceiveStream | None', stderr: 'ReceiveStream | None') -> 'None'
 |      Initialize self.  See help(type(self)) for accurate signature.
 |
 |  __repr__(self) -> 'str'
 |      Return repr(self).
 |
 |  kill(self) -> 'None'
 |      Immediately terminate the process.
 |
 |      On UNIX, this is equivalent to
 |      ``send_signal(signal.SIGKILL)``.  On Windows, it calls
 |      ``TerminateProcess``. In both cases, the process cannot
 |      prevent itself from being killed, but the termination will be
 |      delivered asynchronously; use :meth:`wait` if you want to
 |      ensure the process is actually dead before proceeding.
 |
 |  poll(self) -> 'int | None'
 |      Returns the exit status of the process (an integer), or ``None`` if
 |      it's still running.
 |
 |      Note that on Trio (unlike the standard library `subprocess.Popen`),
 |      ``process.poll()`` and ``process.returncode`` always give the same
 |      result. See `returncode` for more details. This method is only
 |      included to make it easier to port code from `subprocess`.
 |
 |  send_signal(self, sig: 'signal.Signals | int') -> 'None'
 |      Send signal ``sig`` to the process.
 |
 |      On UNIX, ``sig`` may be any signal defined in the
 |      :mod:`signal` module, such as ``signal.SIGINT`` or
 |      ``signal.SIGTERM``. On Windows, it may be anything accepted by
 |      the standard library :meth:`subprocess.Popen.send_signal`.
 |
 |  terminate(self) -> 'None'
 |      Terminate the process, politely if possible.
 |
 |      On UNIX, this is equivalent to
 |      ``send_signal(signal.SIGTERM)``; by convention this requests
 |      graceful termination, but a misbehaving or buggy process might
 |      ignore it. On Windows, :meth:`terminate` forcibly terminates the
 |      process in the same manner as :meth:`kill`.
 |
 |  async wait(self) -> 'int'
 |      Block until the process exits.
 |
 |      Returns:
 |        The exit status of the process; see :attr:`returncode`.
 |
 |  ----------------------------------------------------------------------
 |  Class methods defined here:
 |
 |  __init_subclass__ = _init_final_cls() -> 'NoReturn' from trio._util
 |      Raises an exception when a final class is subclassed.
 |
 |  ----------------------------------------------------------------------
 |  Readonly properties defined here:
 |
 |  returncode
 |      The exit status of the process (an integer), or ``None`` if it's
 |      still running.
 |
 |      By convention, a return code of zero indicates success.  On
 |      UNIX, negative values indicate termination due to a signal,
 |      e.g., -11 if terminated by signal 11 (``SIGSEGV``).  On
 |      Windows, a process that exits due to a call to
 |      :meth:`Process.terminate` will have an exit status of 1.
 |
 |      Unlike the standard library `subprocess.Popen.returncode`, you don't
 |      have to call `poll` or `wait` to update this attribute; it's
 |      automatically updated as needed, and will always give you the latest
 |      information.
 |
 |  ----------------------------------------------------------------------
 |  Data descriptors defined here:
 |
 |  __dict__
 |      dictionary for instance variables
 |
 |  __weakref__
 |      list of weak references to the object
 |
 |  ----------------------------------------------------------------------
 |  Data and other attributes defined here:
 |
 |  __abstractmethods__ = frozenset()
 |
 |  __annotations__ = {'_wait_for_exit_data': 'object', 'encoding': 'Final...
 |
 |  __final__ = True
 |
 |  encoding = None
 |
 |  errors = None
 |
 |  universal_newlines = False
trio.RunFinishedError
Python Library Documentation: class RunFinishedError in module trio

class RunFinishedError(builtins.RuntimeError)
 |  Raised by `trio.from_thread.run` and similar functions if the
 |  corresponding call to :func:`trio.run` has already finished.
 |
 |  Method resolution order:
 |      RunFinishedError
 |      builtins.RuntimeError
 |      builtins.Exception
 |      builtins.BaseException
 |      builtins.object
 |
 |  Data descriptors defined here:
 |
 |  __weakref__
 |      list of weak references to the object
 |
 |  ----------------------------------------------------------------------
 |  Methods inherited from builtins.RuntimeError:
 |
 |  __init__(self, /, *args, **kwargs)
 |      Initialize self.  See help(type(self)) for accurate signature.
 |
 |  ----------------------------------------------------------------------
 |  Static methods inherited from builtins.RuntimeError:
 |
 |  __new__(*args, **kwargs) class method of builtins.RuntimeError
 |      Create and return a new object.  See help(type) for accurate signature.
 |
 |  ----------------------------------------------------------------------
 |  Methods inherited from builtins.BaseException:
 |
 |  __getattribute__(self, name, /)
 |      Return getattr(self, name).
 |
 |  __reduce__(...)
 |      Helper for pickle.
 |
 |  __repr__(self, /)
 |      Return repr(self).
 |
 |  __setstate__(...)
 |
 |  __str__(self, /)
 |      Return str(self).
 |
 |  add_note(...)
 |      Exception.add_note(note) --
 |      add a note to the exception
 |
 |  with_traceback(...)
 |      Exception.with_traceback(tb) --
 |      set self.__traceback__ to tb and return self.
 |
 |  ----------------------------------------------------------------------
 |  Data descriptors inherited from builtins.BaseException:
 |
 |  __cause__
 |      exception cause
 |
 |  __context__
 |      exception context
 |
 |  __dict__
 |
 |  __suppress_context__
 |
 |  __traceback__
 |
 |  args
trio.SSLListener
Python Library Documentation: class SSLListener in module trio

class SSLListener(trio.abc.Listener)
 |  SSLListener(transport_listener: 'Listener[T_Stream]', ssl_context: '_stdlib_ssl.SSLContext', *, https_compatible: 'bool' = False) -> 'None'
 |
 |  A :class:`~trio.abc.Listener` for SSL/TLS-encrypted servers.
 |
 |  :class:`SSLListener` wraps around another Listener, and converts
 |  all incoming connections to encrypted connections by wrapping them
 |  in a :class:`SSLStream`.
 |
 |  Args:
 |    transport_listener (~trio.abc.Listener): The listener whose incoming
 |        connections will be wrapped in :class:`SSLStream`.
 |
 |    ssl_context (~ssl.SSLContext): The :class:`~ssl.SSLContext` that will be
 |        used for incoming connections.
 |
 |    https_compatible (bool): Passed on to :class:`SSLStream`.
 |
 |  Attributes:
 |    transport_listener (trio.abc.Listener): The underlying listener that was
 |        passed to ``__init__``.
 |
 |  Method resolution order:
 |      SSLListener
 |      trio.abc.Listener
 |      trio.abc.AsyncResource
 |      abc.ABC
 |      typing.Generic
 |      builtins.object
 |
 |  Methods defined here:
 |
 |  __init__(self, transport_listener: 'Listener[T_Stream]', ssl_context: '_stdlib_ssl.SSLContext', *, https_compatible: 'bool' = False) -> 'None'
 |      Initialize self.  See help(type(self)) for accurate signature.
 |
 |  async accept(self) -> 'SSLStream[T_Stream]'
 |      Accept the next connection and wrap it in an :class:`SSLStream`.
 |
 |      See :meth:`trio.abc.Listener.accept` for details.
 |
 |  async aclose(self) -> 'None'
 |      Close the transport listener.
 |
 |  ----------------------------------------------------------------------
 |  Class methods defined here:
 |
 |  __init_subclass__ = _init_final_cls() -> 'NoReturn' from trio._util
 |      Raises an exception when a final class is subclassed.
 |
 |  ----------------------------------------------------------------------
 |  Data descriptors defined here:
 |
 |  __dict__
 |      dictionary for instance variables
 |
 |  __weakref__
 |      list of weak references to the object
 |
 |  ----------------------------------------------------------------------
 |  Data and other attributes defined here:
 |
 |  __abstractmethods__ = frozenset()
 |
 |  __annotations__ = {}
 |
 |  __final__ = True
 |
 |  __orig_bases__ = (trio.abc.Listener[trio.SSLStream[~T_Stream]],)
 |
 |  __parameters__ = (~T_Stream,)
 |
 |  ----------------------------------------------------------------------
 |  Methods inherited from trio.abc.AsyncResource:
 |
 |  async __aenter__(self) -> 'Self'
 |
 |  async __aexit__(self, exc_type: 'type[BaseException] | None', exc_value: 'BaseException | None', traceback: 'TracebackType | None') -> 'None'
 |
 |  ----------------------------------------------------------------------
 |  Class methods inherited from typing.Generic:
 |
 |  __class_getitem__(...)
 |      Parameterizes a generic class.
 |
 |      At least, parameterizing a generic class is the *main* thing this
 |      method does. For example, for some generic class `Foo`, this is called
 |      when we do `Foo[int]` - there, with `cls=Foo` and `params=int`.
 |
 |      However, note that this method is also called when defining generic
 |      classes in the first place with `class Foo[T]: ...`.
trio.SSLStream
Python Library Documentation: class SSLStream in module trio

class SSLStream(trio.abc.Stream, typing.Generic)
 |  SSLStream(transport_stream: 'T_Stream', ssl_context: '_stdlib_ssl.SSLContext', *, server_hostname: 'str | bytes | None' = None, server_side: 'bool' = False, https_compatible: 'bool' = False) -> 'None'
 |
 |  Encrypted communication using SSL/TLS.
 |
 |  :class:`SSLStream` wraps an arbitrary :class:`~trio.abc.Stream`, and
 |  allows you to perform encrypted communication over it using the usual
 |  :class:`~trio.abc.Stream` interface. You pass regular data to
 |  :meth:`send_all`, then it encrypts it and sends the encrypted data on the
 |  underlying :class:`~trio.abc.Stream`; :meth:`receive_some` takes encrypted
 |  data out of the underlying :class:`~trio.abc.Stream` and decrypts it
 |  before returning it.
 |
 |  You should read the standard library's :mod:`ssl` documentation carefully
 |  before attempting to use this class, and probably other general
 |  documentation on SSL/TLS as well. SSL/TLS is subtle and quick to
 |  anger. Really. I'm not kidding.
 |
 |  Args:
 |    transport_stream (~trio.abc.Stream): The stream used to transport
 |        encrypted data. Required.
 |
 |    ssl_context (~ssl.SSLContext): The :class:`~ssl.SSLContext` used for
 |        this connection. Required. Usually created by calling
 |        :func:`ssl.create_default_context`.
 |
 |    server_hostname (str, bytes, or None): The name of the server being
 |        connected to. Used for `SNI
 |        <https://en.wikipedia.org/wiki/Server_Name_Indication>`__ and for
 |        validating the server's certificate (if hostname checking is
 |        enabled). This is effectively mandatory for clients, and actually
 |        mandatory if ``ssl_context.check_hostname`` is ``True``.
 |
 |    server_side (bool): Whether this stream is acting as a client or
 |        server. Defaults to False, i.e. client mode.
 |
 |    https_compatible (bool): There are two versions of SSL/TLS commonly
 |        encountered in the wild: the standard version, and the version used
 |        for HTTPS (HTTP-over-SSL/TLS).
 |
 |        Standard-compliant SSL/TLS implementations always send a
 |        cryptographically signed ``close_notify`` message before closing the
 |        connection. This is important because if the underlying transport
 |        were simply closed, then there wouldn't be any way for the other
 |        side to know whether the connection was intentionally closed by the
 |        peer that they negotiated a cryptographic connection to, or by some
 |        `man-in-the-middle
 |        <https://en.wikipedia.org/wiki/Man-in-the-middle_attack>`__ attacker
 |        who can't manipulate the cryptographic stream, but can manipulate
 |        the transport layer (a so-called "truncation attack").
 |
 |        However, this part of the standard is widely ignored by real-world
 |        HTTPS implementations, which means that if you want to interoperate
 |        with them, then you NEED to ignore it too.
 |
 |        Fortunately this isn't as bad as it sounds, because the HTTP
 |        protocol already includes its own equivalent of ``close_notify``, so
 |        doing this again at the SSL/TLS level is redundant. But not all
 |        protocols do! Therefore, by default Trio implements the safer
 |        standard-compliant version (``https_compatible=False``). But if
 |        you're speaking HTTPS or some other protocol where
 |        ``close_notify``\s are commonly skipped, then you should set
 |        ``https_compatible=True``; with this setting, Trio will neither
 |        expect nor send ``close_notify`` messages.
 |
 |        If you have code that was written to use :class:`ssl.SSLSocket` and
 |        now you're porting it to Trio, then it may be useful to know that a
 |        difference between :class:`SSLStream` and :class:`ssl.SSLSocket` is
 |        that :class:`~ssl.SSLSocket` implements the
 |        ``https_compatible=True`` behavior by default.
 |
 |  Attributes:
 |    transport_stream (trio.abc.Stream): The underlying transport stream
 |        that was passed to ``__init__``. An example of when this would be
 |        useful is if you're using :class:`SSLStream` over a
 |        :class:`~trio.SocketStream` and want to call the
 |        :class:`~trio.SocketStream`'s :meth:`~trio.SocketStream.setsockopt`
 |        method.
 |
 |  Internally, this class is implemented using an instance of
 |  :class:`ssl.SSLObject`, and all of :class:`~ssl.SSLObject`'s methods and
 |  attributes are re-exported as methods and attributes on this class.
 |  However, there is one difference: :class:`~ssl.SSLObject` has several
 |  methods that return information about the encrypted connection, like
 |  :meth:`~ssl.SSLSocket.cipher` or
 |  :meth:`~ssl.SSLSocket.selected_alpn_protocol`. If you call them before the
 |  handshake, when they can't possibly return useful data, then
 |  :class:`ssl.SSLObject` returns None, but :class:`trio.SSLStream`
 |  raises :exc:`NeedHandshakeError`.
 |
 |  This also means that if you register a SNI callback using
 |  `~ssl.SSLContext.sni_callback`, then the first argument your callback
 |  receives will be a :class:`ssl.SSLObject`.
 |
 |  Method resolution order:
 |      SSLStream
 |      trio.abc.Stream
 |      trio.abc.SendStream
 |      trio.abc.ReceiveStream
 |      trio.abc.AsyncResource
 |      abc.ABC
 |      typing.Generic
 |      builtins.object
 |
 |  Methods defined here:
 |
 |  __dir__(self) -> 'list[str]' from trio._ssl.SSLStream
 |      Default dir() implementation.
 |
 |  __getattr__(self, name: 'str') -> 'Any' from trio._ssl.SSLStream
 |
 |  __init__(self, transport_stream: 'T_Stream', ssl_context: '_stdlib_ssl.SSLContext', *, server_hostname: 'str | bytes | None' = None, server_side: 'bool' = False, https_compatible: 'bool' = False) -> 'None' from trio._ssl.SSLStream
 |      Initialize self.  See help(type(self)) for accurate signature.
 |
 |  __setattr__(self, name: 'str', value: 'object') -> 'None' from trio._ssl.SSLStream
 |      Implement setattr(self, name, value).
 |
 |  async aclose(self) -> 'None' from trio._ssl.SSLStream
 |      Gracefully shut down this connection, and close the underlying
 |      transport.
 |
 |      If ``https_compatible`` is False (the default), then this attempts to
 |      first send a ``close_notify`` and then close the underlying stream by
 |      calling its :meth:`~trio.abc.AsyncResource.aclose` method.
 |
 |      If ``https_compatible`` is set to True, then this simply closes the
 |      underlying stream and marks this stream as closed.
 |
 |  async do_handshake(self) -> 'None' from trio._ssl.SSLStream
 |      Ensure that the initial handshake has completed.
 |
 |      The SSL protocol requires an initial handshake to exchange
 |      certificates, select cryptographic keys, and so forth, before any
 |      actual data can be sent or received. You don't have to call this
 |      method; if you don't, then :class:`SSLStream` will automatically
 |      perform the handshake as needed, the first time you try to send or
 |      receive data. But if you want to trigger it manually – for example,
 |      because you want to look at the peer's certificate before you start
 |      talking to them – then you can call this method.
 |
 |      If the initial handshake is already in progress in another task, this
 |      waits for it to complete and then returns.
 |
 |      If the initial handshake has already completed, this returns
 |      immediately without doing anything (except executing a checkpoint).
 |
 |      .. warning:: If this method is cancelled, then it may leave the
 |         :class:`SSLStream` in an unusable state. If this happens then any
 |         future attempt to use the object will raise
 |         :exc:`trio.BrokenResourceError`.
 |
 |  async receive_some(self, max_bytes: 'int | None' = None) -> 'bytes | bytearray' from trio._ssl.SSLStream
 |      Read some data from the underlying transport, decrypt it, and
 |      return it.
 |
 |      See :meth:`trio.abc.ReceiveStream.receive_some` for details.
 |
 |      .. warning:: If this method is cancelled while the initial handshake
 |         or a renegotiation are in progress, then it may leave the
 |         :class:`SSLStream` in an unusable state. If this happens then any
 |         future attempt to use the object will raise
 |         :exc:`trio.BrokenResourceError`.
 |
 |  async send_all(self, data: 'bytes | bytearray | memoryview') -> 'None' from trio._ssl.SSLStream
 |      Encrypt some data and then send it on the underlying transport.
 |
 |      See :meth:`trio.abc.SendStream.send_all` for details.
 |
 |      .. warning:: If this method is cancelled, then it may leave the
 |         :class:`SSLStream` in an unusable state. If this happens then any
 |         attempt to use the object will raise
 |         :exc:`trio.BrokenResourceError`.
 |
 |  async unwrap(self) -> 'tuple[Stream, bytes | bytearray]' from trio._ssl.SSLStream
 |      Cleanly close down the SSL/TLS encryption layer, allowing the
 |      underlying stream to be used for unencrypted communication.
 |
 |      You almost certainly don't need this.
 |
 |      Returns:
 |        A pair ``(transport_stream, trailing_bytes)``, where
 |        ``transport_stream`` is the underlying transport stream, and
 |        ``trailing_bytes`` is a byte string. Since :class:`SSLStream`
 |        doesn't necessarily know where the end of the encrypted data will
 |        be, it can happen that it accidentally reads too much from the
 |        underlying stream. ``trailing_bytes`` contains this extra data; you
 |        should process it as if it was returned from a call to
 |        ``transport_stream.receive_some(...)``.
 |
 |  async wait_send_all_might_not_block(self) -> 'None' from trio._ssl.SSLStream
 |      See :meth:`trio.abc.SendStream.wait_send_all_might_not_block`.
 |
 |  ----------------------------------------------------------------------
 |  Class methods defined here:
 |
 |  __init_subclass__ = _init_final_cls() -> 'NoReturn' from trio._util
 |      Raises an exception when a final class is subclassed.
 |
 |  ----------------------------------------------------------------------
 |  Data descriptors defined here:
 |
 |  __dict__
 |      dictionary for instance variables
 |
 |  __weakref__
 |      list of weak references to the object
 |
 |  ----------------------------------------------------------------------
 |  Data and other attributes defined here:
 |
 |  __abstractmethods__ = frozenset()
 |
 |  __annotations__ = {'_after_handshake': 'ClassVar', '_forwarded': 'Clas...
 |
 |  __final__ = True
 |
 |  __orig_bases__ = (<class 'trio.abc.Stream'>, typing.Generic[~T_Stream]...
 |
 |  __parameters__ = (~T_Stream,)
 |
 |  ----------------------------------------------------------------------
 |  Methods inherited from trio.abc.ReceiveStream:
 |
 |  __aiter__(self) -> 'Self'
 |
 |  async __anext__(self) -> 'bytes | bytearray'
 |
 |  ----------------------------------------------------------------------
 |  Methods inherited from trio.abc.AsyncResource:
 |
 |  async __aenter__(self) -> 'Self'
 |
 |  async __aexit__(self, exc_type: 'type[BaseException] | None', exc_value: 'BaseException | None', traceback: 'TracebackType | None') -> 'None'
 |
 |  ----------------------------------------------------------------------
 |  Class methods inherited from typing.Generic:
 |
 |  __class_getitem__(...)
 |      Parameterizes a generic class.
 |
 |      At least, parameterizing a generic class is the *main* thing this
 |      method does. For example, for some generic class `Foo`, this is called
 |      when we do `Foo[int]` - there, with `cls=Foo` and `params=int`.
 |
 |      However, note that this method is also called when defining generic
 |      classes in the first place with `class Foo[T]: ...`.
trio.Semaphore
Python Library Documentation: class Semaphore in module trio

class Semaphore(trio._sync.AsyncContextManagerMixin)
 |  Semaphore(initial_value: 'int', *, max_value: 'int | None' = None) -> 'None'
 |
 |  A `semaphore <https://en.wikipedia.org/wiki/Semaphore_(programming)>`__.
 |
 |  A semaphore holds an integer value, which can be incremented by
 |  calling :meth:`release` and decremented by calling :meth:`acquire` – but
 |  the value is never allowed to drop below zero. If the value is zero, then
 |  :meth:`acquire` will block until someone calls :meth:`release`.
 |
 |  If you're looking for a :class:`Semaphore` to limit the number of tasks
 |  that can access some resource simultaneously, then consider using a
 |  :class:`CapacityLimiter` instead.
 |
 |  This object's interface is similar to, but different from, that of
 |  :class:`threading.Semaphore`.
 |
 |  A :class:`Semaphore` object can be used as an async context manager; it
 |  blocks on entry but not on exit.
 |
 |  Args:
 |    initial_value (int): A non-negative integer giving semaphore's initial
 |      value.
 |    max_value (int or None): If given, makes this a "bounded" semaphore that
 |      raises an error if the value is about to exceed the given
 |      ``max_value``.
 |
 |  Method resolution order:
 |      Semaphore
 |      trio._sync.AsyncContextManagerMixin
 |      builtins.object
 |
 |  Methods defined here:
 |
 |  __init__(self, initial_value: 'int', *, max_value: 'int | None' = None) -> 'None'
 |      Initialize self.  See help(type(self)) for accurate signature.
 |
 |  __repr__(self) -> 'str'
 |      Return repr(self).
 |
 |  async acquire(self) -> 'None'
 |      Decrement the semaphore value, blocking if necessary to avoid
 |      letting it drop below zero.
 |
 |  acquire_nowait(self) -> 'None'
 |      Attempt to decrement the semaphore value, without blocking.
 |
 |      Raises:
 |        WouldBlock: if the value is zero.
 |
 |  release(self) -> 'None'
 |      Increment the semaphore value, possibly waking a task blocked in
 |      :meth:`acquire`.
 |
 |      Raises:
 |        ValueError: if incrementing the value would cause it to exceed
 |            :attr:`max_value`.
 |
 |  statistics(self) -> 'ParkingLotStatistics'
 |      Return an object containing debugging information.
 |
 |      Currently the following fields are defined:
 |
 |      * ``tasks_waiting``: The number of tasks blocked on this semaphore's
 |        :meth:`acquire` method.
 |
 |  ----------------------------------------------------------------------
 |  Class methods defined here:
 |
 |  __init_subclass__ = _init_final_cls() -> 'NoReturn' from trio._util
 |      Raises an exception when a final class is subclassed.
 |
 |  ----------------------------------------------------------------------
 |  Readonly properties defined here:
 |
 |  max_value
 |      The maximum allowed value. May be None to indicate no limit.
 |
 |  value
 |      The current value of the semaphore.
 |
 |  ----------------------------------------------------------------------
 |  Data and other attributes defined here:
 |
 |  __annotations__ = {}
 |
 |  __final__ = True
 |
 |  ----------------------------------------------------------------------
 |  Methods inherited from trio._sync.AsyncContextManagerMixin:
 |
 |  async __aenter__(self: '_HasAcquireRelease') -> 'None'
 |
 |  async __aexit__(self: '_HasAcquireRelease', exc_type: 'type[BaseException] | None', exc_value: 'BaseException | None', traceback: 'TracebackType | None') -> 'None'
 |
 |  ----------------------------------------------------------------------
 |  Data descriptors inherited from trio._sync.AsyncContextManagerMixin:
 |
 |  __dict__
 |      dictionary for instance variables
 |
 |  __weakref__
 |      list of weak references to the object
trio.SocketListener
Python Library Documentation: class SocketListener in module trio

class SocketListener(trio.abc.Listener)
 |  SocketListener(socket: 'SocketType') -> 'None'
 |
 |  A :class:`~trio.abc.Listener` that uses a listening socket to accept
 |  incoming connections as :class:`SocketStream` objects.
 |
 |  Args:
 |    socket: The Trio socket object to wrap. Must have type ``SOCK_STREAM``,
 |        and be listening.
 |
 |  Note that the :class:`SocketListener` "takes ownership" of the given
 |  socket; closing the :class:`SocketListener` will also close the socket.
 |
 |  .. attribute:: socket
 |
 |     The Trio socket object that this stream wraps.
 |
 |  Method resolution order:
 |      SocketListener
 |      trio.abc.Listener
 |      trio.abc.AsyncResource
 |      abc.ABC
 |      typing.Generic
 |      builtins.object
 |
 |  Methods defined here:
 |
 |  __init__(self, socket: 'SocketType') -> 'None'
 |      Initialize self.  See help(type(self)) for accurate signature.
 |
 |  async accept(self) -> 'SocketStream'
 |      Accept an incoming connection.
 |
 |      Returns:
 |        :class:`SocketStream`
 |
 |      Raises:
 |        OSError: if the underlying call to ``accept`` raises an unexpected
 |            error.
 |        ClosedResourceError: if you already closed the socket.
 |
 |      This method handles routine errors like ``ECONNABORTED``, but passes
 |      other errors on to its caller. In particular, it does *not* make any
 |      special effort to handle resource exhaustion errors like ``EMFILE``,
 |      ``ENFILE``, ``ENOBUFS``, ``ENOMEM``.
 |
 |  async aclose(self) -> 'None'
 |      Close this listener and its underlying socket.
 |
 |  ----------------------------------------------------------------------
 |  Class methods defined here:
 |
 |  __init_subclass__ = _init_final_cls() -> 'NoReturn' from trio._util
 |      Raises an exception when a final class is subclassed.
 |
 |  ----------------------------------------------------------------------
 |  Data descriptors defined here:
 |
 |  __dict__
 |      dictionary for instance variables
 |
 |  __weakref__
 |      list of weak references to the object
 |
 |  ----------------------------------------------------------------------
 |  Data and other attributes defined here:
 |
 |  __abstractmethods__ = frozenset()
 |
 |  __annotations__ = {}
 |
 |  __final__ = True
 |
 |  __orig_bases__ = (trio.abc.Listener[trio.SocketStream],)
 |
 |  __parameters__ = ()
 |
 |  ----------------------------------------------------------------------
 |  Methods inherited from trio.abc.AsyncResource:
 |
 |  async __aenter__(self) -> 'Self'
 |
 |  async __aexit__(self, exc_type: 'type[BaseException] | None', exc_value: 'BaseException | None', traceback: 'TracebackType | None') -> 'None'
 |
 |  ----------------------------------------------------------------------
 |  Class methods inherited from typing.Generic:
 |
 |  __class_getitem__(...)
 |      Parameterizes a generic class.
 |
 |      At least, parameterizing a generic class is the *main* thing this
 |      method does. For example, for some generic class `Foo`, this is called
 |      when we do `Foo[int]` - there, with `cls=Foo` and `params=int`.
 |
 |      However, note that this method is also called when defining generic
 |      classes in the first place with `class Foo[T]: ...`.
trio.SocketStream
Python Library Documentation: class SocketStream in module trio

class SocketStream(trio.abc.HalfCloseableStream)
 |  SocketStream(socket: 'SocketType') -> 'None'
 |
 |  An implementation of the :class:`trio.abc.HalfCloseableStream`
 |  interface based on a raw network socket.
 |
 |  Args:
 |    socket: The Trio socket object to wrap. Must have type ``SOCK_STREAM``,
 |        and be connected.
 |
 |  By default for TCP sockets, :class:`SocketStream` enables ``TCP_NODELAY``,
 |  and (on platforms where it's supported) enables ``TCP_NOTSENT_LOWAT`` with
 |  a reasonable buffer size (currently 16 KiB) – see `issue #72
 |  <https://github.com/python-trio/trio/issues/72>`__ for discussion. You can
 |  of course override these defaults by calling :meth:`setsockopt`.
 |
 |  Once a :class:`SocketStream` object is constructed, it implements the full
 |  :class:`trio.abc.HalfCloseableStream` interface. In addition, it provides
 |  a few extra features:
 |
 |  .. attribute:: socket
 |
 |     The Trio socket object that this stream wraps.
 |
 |  Method resolution order:
 |      SocketStream
 |      trio.abc.HalfCloseableStream
 |      trio.abc.Stream
 |      trio.abc.SendStream
 |      trio.abc.ReceiveStream
 |      trio.abc.AsyncResource
 |      abc.ABC
 |      builtins.object
 |
 |  Methods defined here:
 |
 |  __init__(self, socket: 'SocketType') -> 'None'
 |      Initialize self.  See help(type(self)) for accurate signature.
 |
 |  async aclose(self) -> 'None'
 |      Close this resource, possibly blocking.
 |
 |      IMPORTANT: This method may block in order to perform a "graceful"
 |      shutdown. But, if this fails, then it still *must* close any
 |      underlying resources before returning. An error from this method
 |      indicates a failure to achieve grace, *not* a failure to close the
 |      connection.
 |
 |      For example, suppose we call :meth:`aclose` on a TLS-encrypted
 |      connection. This requires sending a "goodbye" message; but if the peer
 |      has become non-responsive, then our attempt to send this message might
 |      block forever, and eventually time out and be cancelled. In this case
 |      the :meth:`aclose` method on :class:`~trio.SSLStream` will
 |      immediately close the underlying transport stream using
 |      :func:`trio.aclose_forcefully` before raising :exc:`~trio.Cancelled`.
 |
 |      If the resource is already closed, then this method should silently
 |      succeed.
 |
 |      Once this method completes, any other pending or future operations on
 |      this resource should generally raise :exc:`~trio.ClosedResourceError`,
 |      unless there's a good reason to do otherwise.
 |
 |      See also: :func:`trio.aclose_forcefully`.
 |
 |  getsockopt(self, level: 'int', option: 'int', buffersize: 'int' = 0) -> 'int | bytes'
 |      Check the current value of an option on the underlying socket.
 |
 |      See :meth:`socket.socket.getsockopt` for details.
 |
 |  async receive_some(self, max_bytes: 'int | None' = None) -> 'bytes'
 |      Wait until there is data available on this stream, and then return
 |      some of it.
 |
 |      A return value of ``b""`` (an empty bytestring) indicates that the
 |      stream has reached end-of-file. Implementations should be careful that
 |      they return ``b""`` if, and only if, the stream has reached
 |      end-of-file!
 |
 |      Args:
 |        max_bytes (int): The maximum number of bytes to return. Must be
 |            greater than zero. Optional; if omitted, then the stream object
 |            is free to pick a reasonable default.
 |
 |      Returns:
 |        bytes or bytearray: The data received.
 |
 |      Raises:
 |        trio.BusyResourceError: if two tasks attempt to call
 |            :meth:`receive_some` on the same stream at the same time.
 |        trio.BrokenResourceError: if something has gone wrong, and the stream
 |            is broken.
 |        trio.ClosedResourceError: if you previously closed this stream
 |            object, or if another task closes this stream object while
 |            :meth:`receive_some` is running.
 |
 |  async send_all(self, data: 'bytes | bytearray | memoryview') -> 'None'
 |      Sends the given data through the stream, blocking if necessary.
 |
 |      Args:
 |        data (bytes, bytearray, or memoryview): The data to send.
 |
 |      Raises:
 |        trio.BusyResourceError: if another task is already executing a
 |            :meth:`send_all`, :meth:`wait_send_all_might_not_block`, or
 |            :meth:`HalfCloseableStream.send_eof` on this stream.
 |        trio.BrokenResourceError: if something has gone wrong, and the stream
 |            is broken.
 |        trio.ClosedResourceError: if you previously closed this stream
 |            object, or if another task closes this stream object while
 |            :meth:`send_all` is running.
 |
 |      Most low-level operations in Trio provide a guarantee: if they raise
 |      :exc:`trio.Cancelled`, this means that they had no effect, so the
 |      system remains in a known state. This is **not true** for
 |      :meth:`send_all`. If this operation raises :exc:`trio.Cancelled` (or
 |      any other exception for that matter), then it may have sent some, all,
 |      or none of the requested data, and there is no way to know which.
 |
 |  async send_eof(self) -> 'None'
 |      Send an end-of-file indication on this stream, if possible.
 |
 |      The difference between :meth:`send_eof` and
 |      :meth:`~AsyncResource.aclose` is that :meth:`send_eof` is a
 |      *unidirectional* end-of-file indication. After you call this method,
 |      you shouldn't try sending any more data on this stream, and your
 |      remote peer should receive an end-of-file indication (eventually,
 |      after receiving all the data you sent before that). But, they may
 |      continue to send data to you, and you can continue to receive it by
 |      calling :meth:`~ReceiveStream.receive_some`. You can think of it as
 |      calling :meth:`~AsyncResource.aclose` on just the
 |      :class:`SendStream` "half" of the stream object (and in fact that's
 |      literally how :class:`trio.StapledStream` implements it).
 |
 |      Examples:
 |
 |      * On a socket, this corresponds to ``shutdown(..., SHUT_WR)`` (`man
 |        page <https://linux.die.net/man/2/shutdown>`__).
 |
 |      * The SSH protocol provides the ability to multiplex bidirectional
 |        "channels" on top of a single encrypted connection. A Trio
 |        implementation of SSH could expose these channels as
 |        :class:`HalfCloseableStream` objects, and calling :meth:`send_eof`
 |        would send an ``SSH_MSG_CHANNEL_EOF`` request (see `RFC 4254 §5.3
 |        <https://tools.ietf.org/html/rfc4254#section-5.3>`__).
 |
 |      * On an SSL/TLS-encrypted connection, the protocol doesn't provide any
 |        way to do a unidirectional shutdown without closing the connection
 |        entirely, so :class:`~trio.SSLStream` implements
 |        :class:`Stream`, not :class:`HalfCloseableStream`.
 |
 |      If an EOF has already been sent, then this method should silently
 |      succeed.
 |
 |      Raises:
 |        trio.BusyResourceError: if another task is already executing a
 |            :meth:`~SendStream.send_all`,
 |            :meth:`~SendStream.wait_send_all_might_not_block`, or
 |            :meth:`send_eof` on this stream.
 |        trio.BrokenResourceError: if something has gone wrong, and the stream
 |            is broken.
 |        trio.ClosedResourceError: if you previously closed this stream
 |            object, or if another task closes this stream object while
 |            :meth:`send_eof` is running.
 |
 |  setsockopt(self, level: 'int', option: 'int', value: 'int | Buffer | None', length: 'int | None' = None) -> 'None'
 |      Set an option on the underlying socket.
 |
 |      See :meth:`socket.socket.setsockopt` for details.
 |
 |  async wait_send_all_might_not_block(self) -> 'None'
 |      Block until it's possible that :meth:`send_all` might not block.
 |
 |      This method may return early: it's possible that after it returns,
 |      :meth:`send_all` will still block. (In the worst case, if no better
 |      implementation is available, then it might always return immediately
 |      without blocking. It's nice to do better than that when possible,
 |      though.)
 |
 |      This method **must not** return *late*: if it's possible for
 |      :meth:`send_all` to complete without blocking, then it must
 |      return. When implementing it, err on the side of returning early.
 |
 |      Raises:
 |        trio.BusyResourceError: if another task is already executing a
 |            :meth:`send_all`, :meth:`wait_send_all_might_not_block`, or
 |            :meth:`HalfCloseableStream.send_eof` on this stream.
 |        trio.BrokenResourceError: if something has gone wrong, and the stream
 |            is broken.
 |        trio.ClosedResourceError: if you previously closed this stream
 |            object, or if another task closes this stream object while
 |            :meth:`wait_send_all_might_not_block` is running.
 |
 |      Note:
 |
 |        This method is intended to aid in implementing protocols that want
 |        to delay choosing which data to send until the last moment. E.g.,
 |        suppose you're working on an implementation of a remote display server
 |        like `VNC
 |        <https://en.wikipedia.org/wiki/Virtual_Network_Computing>`__, and
 |        the network connection is currently backed up so that if you call
 |        :meth:`send_all` now then it will sit for 0.5 seconds before actually
 |        sending anything. In this case it doesn't make sense to take a
 |        screenshot, then wait 0.5 seconds, and then send it, because the
 |        screen will keep changing while you wait; it's better to wait 0.5
 |        seconds, then take the screenshot, and then send it, because this
 |        way the data you deliver will be more
 |        up-to-date. Using :meth:`wait_send_all_might_not_block` makes it
 |        possible to implement the better strategy.
 |
 |        If you use this method, you might also want to read up on
 |        ``TCP_NOTSENT_LOWAT``.
 |
 |        Further reading:
 |
 |        * `Prioritization Only Works When There's Pending Data to Prioritize
 |          <https://insouciant.org/tech/prioritization-only-works-when-theres-pending-data-to-prioritize/>`__
 |
 |        * WWDC 2015: Your App and Next Generation Networks: `slides
 |          <http://devstreaming.apple.com/videos/wwdc/2015/719ui2k57m/719/719_your_app_and_next_generation_networks.pdf?dl=1>`__,
 |          `video and transcript
 |          <https://developer.apple.com/videos/play/wwdc2015/719/>`__
 |
 |  ----------------------------------------------------------------------
 |  Class methods defined here:
 |
 |  __init_subclass__ = _init_final_cls() -> 'NoReturn' from trio._util
 |      Raises an exception when a final class is subclassed.
 |
 |  ----------------------------------------------------------------------
 |  Data descriptors defined here:
 |
 |  __dict__
 |      dictionary for instance variables
 |
 |  __weakref__
 |      list of weak references to the object
 |
 |  ----------------------------------------------------------------------
 |  Data and other attributes defined here:
 |
 |  __abstractmethods__ = frozenset()
 |
 |  __annotations__ = {}
 |
 |  __final__ = True
 |
 |  ----------------------------------------------------------------------
 |  Methods inherited from trio.abc.ReceiveStream:
 |
 |  __aiter__(self) -> 'Self'
 |
 |  async __anext__(self) -> 'bytes | bytearray'
 |
 |  ----------------------------------------------------------------------
 |  Methods inherited from trio.abc.AsyncResource:
 |
 |  async __aenter__(self) -> 'Self'
 |
 |  async __aexit__(self, exc_type: 'type[BaseException] | None', exc_value: 'BaseException | None', traceback: 'TracebackType | None') -> 'None'
trio.StapledStream
Python Library Documentation: class StapledStream in module trio

class StapledStream(trio.abc.HalfCloseableStream, typing.Generic)
 |  StapledStream(send_stream: 'SendStreamT', receive_stream: 'ReceiveStreamT') -> None
 |
 |  This class `staples <https://en.wikipedia.org/wiki/Staple_(fastener)>`__
 |  together two unidirectional streams to make single bidirectional stream.
 |
 |  Args:
 |    send_stream (~trio.abc.SendStream): The stream to use for sending.
 |    receive_stream (~trio.abc.ReceiveStream): The stream to use for
 |        receiving.
 |
 |  Example:
 |
 |     A silly way to make a stream that echoes back whatever you write to
 |     it::
 |
 |        left, right = trio.testing.memory_stream_pair()
 |        echo_stream = StapledStream(SocketStream(left), SocketStream(right))
 |        await echo_stream.send_all(b"x")
 |        assert await echo_stream.receive_some() == b"x"
 |
 |  :class:`StapledStream` objects implement the methods in the
 |  :class:`~trio.abc.HalfCloseableStream` interface. They also have two
 |  additional public attributes:
 |
 |  .. attribute:: send_stream
 |
 |     The underlying :class:`~trio.abc.SendStream`. :meth:`send_all` and
 |     :meth:`wait_send_all_might_not_block` are delegated to this object.
 |
 |  .. attribute:: receive_stream
 |
 |     The underlying :class:`~trio.abc.ReceiveStream`. :meth:`receive_some`
 |     is delegated to this object.
 |
 |  Method resolution order:
 |      StapledStream
 |      trio.abc.HalfCloseableStream
 |      trio.abc.Stream
 |      trio.abc.SendStream
 |      trio.abc.ReceiveStream
 |      trio.abc.AsyncResource
 |      abc.ABC
 |      typing.Generic
 |      builtins.object
 |
 |  Methods defined here:
 |
 |  __init__(self, send_stream: 'SendStreamT', receive_stream: 'ReceiveStreamT') -> None
 |      Method generated by attrs for class StapledStream.
 |
 |  __repr__(self)
 |      Method generated by attrs for class StapledStream.
 |
 |  async aclose(self) -> 'None'
 |      Calls ``aclose`` on both underlying streams.
 |
 |  async receive_some(self, max_bytes: 'int | None' = None) -> 'bytes'
 |      Calls ``self.receive_stream.receive_some``.
 |
 |  async send_all(self, data: 'bytes | bytearray | memoryview') -> 'None'
 |      Calls ``self.send_stream.send_all``.
 |
 |  async send_eof(self) -> 'None'
 |      Shuts down the send side of the stream.
 |
 |      If :meth:`self.send_stream.send_eof() <trio.abc.HalfCloseableStream.send_eof>` exists,
 |      then this calls it. Otherwise, this calls
 |      :meth:`self.send_stream.aclose() <trio.abc.AsyncResource.aclose>`.
 |
 |  async wait_send_all_might_not_block(self) -> 'None'
 |      Calls ``self.send_stream.wait_send_all_might_not_block``.
 |
 |  ----------------------------------------------------------------------
 |  Class methods defined here:
 |
 |  __init_subclass__ = _init_final_cls() -> 'NoReturn' from trio._util
 |      Raises an exception when a final class is subclassed.
 |
 |  ----------------------------------------------------------------------
 |  Data descriptors defined here:
 |
 |  __dict__
 |      dictionary for instance variables
 |
 |  __weakref__
 |      list of weak references to the object
 |
 |  ----------------------------------------------------------------------
 |  Data and other attributes defined here:
 |
 |  __abstractmethods__ = frozenset()
 |
 |  __annotations__ = {'receive_stream': 'ReceiveStreamT', 'send_stream': ...
 |
 |  __attrs_attrs__ = (Attribute(name='send_stream', default=NOTHING, ...=...
 |
 |  __final__ = True
 |
 |  __match_args__ = ('send_stream', 'receive_stream')
 |
 |  __orig_bases__ = (<class 'trio.abc.HalfCloseableStream'>, typing.Gener...
 |
 |  __parameters__ = (~SendStreamT, ~ReceiveStreamT)
 |
 |  ----------------------------------------------------------------------
 |  Methods inherited from trio.abc.ReceiveStream:
 |
 |  __aiter__(self) -> 'Self'
 |
 |  async __anext__(self) -> 'bytes | bytearray'
 |
 |  ----------------------------------------------------------------------
 |  Methods inherited from trio.abc.AsyncResource:
 |
 |  async __aenter__(self) -> 'Self'
 |
 |  async __aexit__(self, exc_type: 'type[BaseException] | None', exc_value: 'BaseException | None', traceback: 'TracebackType | None') -> 'None'
 |
 |  ----------------------------------------------------------------------
 |  Class methods inherited from typing.Generic:
 |
 |  __class_getitem__(...)
 |      Parameterizes a generic class.
 |
 |      At least, parameterizing a generic class is the *main* thing this
 |      method does. For example, for some generic class `Foo`, this is called
 |      when we do `Foo[int]` - there, with `cls=Foo` and `params=int`.
 |
 |      However, note that this method is also called when defining generic
 |      classes in the first place with `class Foo[T]: ...`.
trio.StrictFIFOLock
Python Library Documentation: class StrictFIFOLock in module trio

class StrictFIFOLock(trio._sync._LockImpl)
 |  StrictFIFOLock() -> None
 |
 |  A variant of :class:`Lock` where tasks are guaranteed to acquire the
 |  lock in strict first-come-first-served order.
 |
 |  An example of when this is useful is if you're implementing something like
 |  :class:`trio.SSLStream` or an HTTP/2 server using `h2
 |  <https://hyper-h2.readthedocs.io/>`__, where you have multiple concurrent
 |  tasks that are interacting with a shared state machine, and at
 |  unpredictable moments the state machine requests that a chunk of data be
 |  sent over the network. (For example, when using h2 simply reading incoming
 |  data can occasionally `create outgoing data to send
 |  <https://http2.github.io/http2-spec/#PING>`__.) The challenge is to make
 |  sure that these chunks are sent in the correct order, without being
 |  garbled.
 |
 |  One option would be to use a regular :class:`Lock`, and wrap it around
 |  every interaction with the state machine::
 |
 |      # This approach is sometimes workable but often sub-optimal; see below
 |      async with lock:
 |          state_machine.do_something()
 |          if state_machine.has_data_to_send():
 |              await conn.sendall(state_machine.get_data_to_send())
 |
 |  But this can be problematic. If you're using h2 then *usually* reading
 |  incoming data doesn't create the need to send any data, so we don't want
 |  to force every task that tries to read from the network to sit and wait
 |  a potentially long time for ``sendall`` to finish. And in some situations
 |  this could even potentially cause a deadlock, if the remote peer is
 |  waiting for you to read some data before it accepts the data you're
 |  sending.
 |
 |  :class:`StrictFIFOLock` provides an alternative. We can rewrite our
 |  example like::
 |
 |      # Note: no awaits between when we start using the state machine and
 |      # when we block to take the lock!
 |      state_machine.do_something()
 |      if state_machine.has_data_to_send():
 |          # Notice that we fetch the data to send out of the state machine
 |          # *before* sleeping, so that other tasks won't see it.
 |          chunk = state_machine.get_data_to_send()
 |          async with strict_fifo_lock:
 |              await conn.sendall(chunk)
 |
 |  First we do all our interaction with the state machine in a single
 |  scheduling quantum (notice there are no ``await``\s in there), so it's
 |  automatically atomic with respect to other tasks. And then if and only if
 |  we have data to send, we get in line to send it – and
 |  :class:`StrictFIFOLock` guarantees that each task will send its data in
 |  the same order that the state machine generated it.
 |
 |  Currently, :class:`StrictFIFOLock` is identical to :class:`Lock`,
 |  but (a) this may not always be true in the future, especially if Trio ever
 |  implements `more sophisticated scheduling policies
 |  <https://github.com/python-trio/trio/issues/32>`__, and (b) the above code
 |  is relying on a pretty subtle property of its lock. Using a
 |  :class:`StrictFIFOLock` acts as an executable reminder that you're relying
 |  on this property.
 |
 |  Method resolution order:
 |      StrictFIFOLock
 |      trio._sync._LockImpl
 |      trio._sync.AsyncContextManagerMixin
 |      builtins.object
 |
 |  Class methods defined here:
 |
 |  __init_subclass__ = _init_final_cls() -> 'NoReturn' from trio._util
 |      Raises an exception when a final class is subclassed.
 |
 |  ----------------------------------------------------------------------
 |  Data and other attributes defined here:
 |
 |  __annotations__ = {}
 |
 |  __final__ = True
 |
 |  ----------------------------------------------------------------------
 |  Methods inherited from trio._sync._LockImpl:
 |
 |  __init__(self) -> None
 |      Method generated by attrs for class _LockImpl.
 |
 |  __repr__(self) -> 'str'
 |      Return repr(self).
 |
 |  async acquire(self) -> 'None'
 |      Acquire the lock, blocking if necessary.
 |
 |      Raises:
 |        BrokenResourceError: if the owner of the lock exits without releasing.
 |
 |  acquire_nowait(self) -> 'None'
 |      Attempt to acquire the lock, without blocking.
 |
 |      Raises:
 |        WouldBlock: if the lock is held.
 |
 |  locked(self) -> 'bool'
 |      Check whether the lock is currently held.
 |
 |      Returns:
 |        bool: True if the lock is held, False otherwise.
 |
 |  release(self) -> 'None'
 |      Release the lock.
 |
 |      Raises:
 |        RuntimeError: if the calling task does not hold the lock.
 |
 |  statistics(self) -> 'LockStatistics'
 |      Return an object containing debugging information.
 |
 |      Currently the following fields are defined:
 |
 |      * ``locked``: boolean indicating whether the lock is held.
 |      * ``owner``: the :class:`trio.lowlevel.Task` currently holding the lock,
 |        or None if the lock is not held.
 |      * ``tasks_waiting``: The number of tasks blocked on this lock's
 |        :meth:`acquire` method.
 |
 |  ----------------------------------------------------------------------
 |  Data and other attributes inherited from trio._sync._LockImpl:
 |
 |  __attrs_attrs__ = (Attribute(name='_lot', default=Factory(factory=...i...
 |
 |  __match_args__ = ()
 |
 |  ----------------------------------------------------------------------
 |  Methods inherited from trio._sync.AsyncContextManagerMixin:
 |
 |  async __aenter__(self: '_HasAcquireRelease') -> 'None'
 |
 |  async __aexit__(self: '_HasAcquireRelease', exc_type: 'type[BaseException] | None', exc_value: 'BaseException | None', traceback: 'TracebackType | None') -> 'None'
 |
 |  ----------------------------------------------------------------------
 |  Data descriptors inherited from trio._sync.AsyncContextManagerMixin:
 |
 |  __dict__
 |      dictionary for instance variables
 |
 |  __weakref__
 |      list of weak references to the object
trio.TASK_STATUS_IGNORED
Python Library Documentation: _TaskStatusIgnored in module trio object

class _TaskStatusIgnored(trio.TaskStatus)
 |  Method resolution order:
 |      _TaskStatusIgnored
 |      trio.TaskStatus
 |      typing.Protocol
 |      typing.Generic
 |      builtins.object
 |
 |  Methods defined here:
 |
 |  __init__(self, /, *args, **kwargs) from builtins.object
 |      Initialize self.  See help(type(self)) for accurate signature.
 |
 |  __repr__(self) -> 'str'
 |      Return repr(self).
 |
 |  started(self, value: 'object' = None) -> 'None'
 |      Tasks call this method to indicate that they have initialized.
 |
 |      See `nursery.start() <trio.Nursery.start>` for more information.
 |
 |  ----------------------------------------------------------------------
 |  Class methods defined here:
 |
 |  __subclasshook__ = _proto_hook(other) from typing
 |
 |  ----------------------------------------------------------------------
 |  Data and other attributes defined here:
 |
 |  __abstractmethods__ = frozenset()
 |
 |  __annotations__ = {}
 |
 |  __orig_bases__ = (trio.TaskStatus[object],)
 |
 |  __parameters__ = ()
 |
 |  ----------------------------------------------------------------------
 |  Data descriptors inherited from trio.TaskStatus:
 |
 |  __dict__
 |      dictionary for instance variables
 |
 |  __weakref__
 |      list of weak references to the object
 |
 |  ----------------------------------------------------------------------
 |  Data and other attributes inherited from trio.TaskStatus:
 |
 |  __protocol_attrs__ = {'started'}
 |
 |  ----------------------------------------------------------------------
 |  Class methods inherited from typing.Protocol:
 |
 |  __init_subclass__(*args, **kwargs)
 |      Function to initialize subclasses.
 |
 |  ----------------------------------------------------------------------
 |  Class methods inherited from typing.Generic:
 |
 |  __class_getitem__(...)
 |      Parameterizes a generic class.
 |
 |      At least, parameterizing a generic class is the *main* thing this
 |      method does. For example, for some generic class `Foo`, this is called
 |      when we do `Foo[int]` - there, with `cls=Foo` and `params=int`.
 |
 |      However, note that this method is also called when defining generic
 |      classes in the first place with `class Foo[T]: ...`.
trio.TaskStatus
Python Library Documentation: class TaskStatus in module trio

class TaskStatus(typing.Protocol)
 |  TaskStatus(*args, **kwargs)
 |
 |  The interface provided by :meth:`Nursery.start()` to the spawned task.
 |
 |  This is provided via the ``task_status`` keyword-only parameter.
 |
 |  Method resolution order:
 |      TaskStatus
 |      typing.Protocol
 |      typing.Generic
 |      builtins.object
 |
 |  Methods defined here:
 |
 |  __init__ = _no_init_or_replace_init(self, *args, **kwargs) from typing
 |
 |  started(self, value: 'StatusT_contra | None' = None) -> 'None'
 |      Tasks call this method to indicate that they have initialized.
 |
 |      See `nursery.start() <trio.Nursery.start>` for more information.
 |
 |  ----------------------------------------------------------------------
 |  Class methods defined here:
 |
 |  __subclasshook__ = _proto_hook(other) from typing
 |
 |  ----------------------------------------------------------------------
 |  Data descriptors defined here:
 |
 |  __dict__
 |      dictionary for instance variables
 |
 |  __weakref__
 |      list of weak references to the object
 |
 |  ----------------------------------------------------------------------
 |  Data and other attributes defined here:
 |
 |  __abstractmethods__ = frozenset()
 |
 |  __annotations__ = {}
 |
 |  __orig_bases__ = (typing.Protocol[-StatusT_contra],)
 |
 |  __parameters__ = (-StatusT_contra,)
 |
 |  __protocol_attrs__ = {'started'}
 |
 |  ----------------------------------------------------------------------
 |  Class methods inherited from typing.Protocol:
 |
 |  __init_subclass__(*args, **kwargs)
 |      Function to initialize subclasses.
 |
 |  ----------------------------------------------------------------------
 |  Class methods inherited from typing.Generic:
 |
 |  __class_getitem__(...)
 |      Parameterizes a generic class.
 |
 |      At least, parameterizing a generic class is the *main* thing this
 |      method does. For example, for some generic class `Foo`, this is called
 |      when we do `Foo[int]` - there, with `cls=Foo` and `params=int`.
 |
 |      However, note that this method is also called when defining generic
 |      classes in the first place with `class Foo[T]: ...`.
trio.TooSlowError
Python Library Documentation: class TooSlowError in module trio

class TooSlowError(builtins.Exception)
 |  Raised by :func:`fail_after` and :func:`fail_at` if the timeout
 |  expires.
 |
 |  Method resolution order:
 |      TooSlowError
 |      builtins.Exception
 |      builtins.BaseException
 |      builtins.object
 |
 |  Data descriptors defined here:
 |
 |  __weakref__
 |      list of weak references to the object
 |
 |  ----------------------------------------------------------------------
 |  Methods inherited from builtins.Exception:
 |
 |  __init__(self, /, *args, **kwargs)
 |      Initialize self.  See help(type(self)) for accurate signature.
 |
 |  ----------------------------------------------------------------------
 |  Static methods inherited from builtins.Exception:
 |
 |  __new__(*args, **kwargs) class method of builtins.Exception
 |      Create and return a new object.  See help(type) for accurate signature.
 |
 |  ----------------------------------------------------------------------
 |  Methods inherited from builtins.BaseException:
 |
 |  __getattribute__(self, name, /)
 |      Return getattr(self, name).
 |
 |  __reduce__(...)
 |      Helper for pickle.
 |
 |  __repr__(self, /)
 |      Return repr(self).
 |
 |  __setstate__(...)
 |
 |  __str__(self, /)
 |      Return str(self).
 |
 |  add_note(...)
 |      Exception.add_note(note) --
 |      add a note to the exception
 |
 |  with_traceback(...)
 |      Exception.with_traceback(tb) --
 |      set self.__traceback__ to tb and return self.
 |
 |  ----------------------------------------------------------------------
 |  Data descriptors inherited from builtins.BaseException:
 |
 |  __cause__
 |      exception cause
 |
 |  __context__
 |      exception context
 |
 |  __dict__
 |
 |  __suppress_context__
 |
 |  __traceback__
 |
 |  args
trio.TrioDeprecationWarning
Python Library Documentation: class TrioDeprecationWarning in module trio

class TrioDeprecationWarning(builtins.FutureWarning)
 |  Warning emitted if you use deprecated Trio functionality.
 |
 |  While a relatively mature project, Trio remains committed to refining its
 |  design and improving usability. As part of this, we occasionally deprecate
 |  or remove functionality that proves suboptimal. If you use Trio, we
 |  recommend `subscribing to issue #1
 |  <https://github.com/python-trio/trio/issues/1>`__ to get information about
 |  upcoming deprecations and other backwards compatibility breaking changes.
 |
 |  Despite the name, this class currently inherits from
 |  :class:`FutureWarning`, not :class:`DeprecationWarning`, because until a
 |  1.0 release, we want these warnings to be visible by default. You can hide
 |  them by installing a filter or with the ``-W`` switch: see the
 |  :mod:`warnings` documentation for details.
 |
 |  Method resolution order:
 |      TrioDeprecationWarning
 |      builtins.FutureWarning
 |      builtins.Warning
 |      builtins.Exception
 |      builtins.BaseException
 |      builtins.object
 |
 |  Data descriptors defined here:
 |
 |  __weakref__
 |      list of weak references to the object
 |
 |  ----------------------------------------------------------------------
 |  Methods inherited from builtins.FutureWarning:
 |
 |  __init__(self, /, *args, **kwargs)
 |      Initialize self.  See help(type(self)) for accurate signature.
 |
 |  ----------------------------------------------------------------------
 |  Static methods inherited from builtins.FutureWarning:
 |
 |  __new__(*args, **kwargs) class method of builtins.FutureWarning
 |      Create and return a new object.  See help(type) for accurate signature.
 |
 |  ----------------------------------------------------------------------
 |  Methods inherited from builtins.BaseException:
 |
 |  __getattribute__(self, name, /)
 |      Return getattr(self, name).
 |
 |  __reduce__(...)
 |      Helper for pickle.
 |
 |  __repr__(self, /)
 |      Return repr(self).
 |
 |  __setstate__(...)
 |
 |  __str__(self, /)
 |      Return str(self).
 |
 |  add_note(...)
 |      Exception.add_note(note) --
 |      add a note to the exception
 |
 |  with_traceback(...)
 |      Exception.with_traceback(tb) --
 |      set self.__traceback__ to tb and return self.
 |
 |  ----------------------------------------------------------------------
 |  Data descriptors inherited from builtins.BaseException:
 |
 |  __cause__
 |      exception cause
 |
 |  __context__
 |      exception context
 |
 |  __dict__
 |
 |  __suppress_context__
 |
 |  __traceback__
 |
 |  args
trio.TrioInternalError
Python Library Documentation: class TrioInternalError in module trio

class TrioInternalError(builtins.Exception)
 |  Raised by :func:`run` if we encounter a bug in Trio, or (possibly) a
 |  misuse of one of the low-level :mod:`trio.lowlevel` APIs.
 |
 |  This should never happen! If you get this error, please file a bug.
 |
 |  Unfortunately, if you get this error it also means that all bets are off –
 |  Trio doesn't know what is going on and its normal invariants may be void.
 |  (For example, we might have "lost track" of a task. Or lost track of all
 |  tasks.) Again, though, this shouldn't happen.
 |
 |  Method resolution order:
 |      TrioInternalError
 |      builtins.Exception
 |      builtins.BaseException
 |      builtins.object
 |
 |  Data descriptors defined here:
 |
 |  __weakref__
 |      list of weak references to the object
 |
 |  ----------------------------------------------------------------------
 |  Methods inherited from builtins.Exception:
 |
 |  __init__(self, /, *args, **kwargs)
 |      Initialize self.  See help(type(self)) for accurate signature.
 |
 |  ----------------------------------------------------------------------
 |  Static methods inherited from builtins.Exception:
 |
 |  __new__(*args, **kwargs) class method of builtins.Exception
 |      Create and return a new object.  See help(type) for accurate signature.
 |
 |  ----------------------------------------------------------------------
 |  Methods inherited from builtins.BaseException:
 |
 |  __getattribute__(self, name, /)
 |      Return getattr(self, name).
 |
 |  __reduce__(...)
 |      Helper for pickle.
 |
 |  __repr__(self, /)
 |      Return repr(self).
 |
 |  __setstate__(...)
 |
 |  __str__(self, /)
 |      Return str(self).
 |
 |  add_note(...)
 |      Exception.add_note(note) --
 |      add a note to the exception
 |
 |  with_traceback(...)
 |      Exception.with_traceback(tb) --
 |      set self.__traceback__ to tb and return self.
 |
 |  ----------------------------------------------------------------------
 |  Data descriptors inherited from builtins.BaseException:
 |
 |  __cause__
 |      exception cause
 |
 |  __context__
 |      exception context
 |
 |  __dict__
 |
 |  __suppress_context__
 |
 |  __traceback__
 |
 |  args
trio.WindowsPath
Python Library Documentation: class WindowsPath in module trio

class WindowsPath(Path, pathlib.PureWindowsPath)
 |  WindowsPath(*args: 'str | os.PathLike[str]') -> 'Self'
 |
 |  An async :class:`pathlib.WindowsPath` that executes blocking methods in :meth:`trio.to_thread.run_sync`.
 |
 |  Method resolution order:
 |      WindowsPath
 |      Path
 |      pathlib.PureWindowsPath
 |      pathlib.PurePath
 |      builtins.object
 |
 |  Class methods defined here:
 |
 |  __init_subclass__ = _init_final_cls() -> 'NoReturn' from trio._util
 |      Raises an exception when a final class is subclassed.
 |
 |  ----------------------------------------------------------------------
 |  Data and other attributes defined here:
 |
 |  __annotations__ = {'_wrapped_cls': 'ClassVar[type[pathlib.Path]]'}
 |
 |  __final__ = True
 |
 |  ----------------------------------------------------------------------
 |  Methods inherited from Path:
 |
 |  __repr__(self) -> 'str'
 |      Return repr(self).
 |
 |  async absolute(self) from pathlib.Path
 |      Like :meth:`~pathlib.Path.absolute`, but async.
 |
 |      Return an absolute version of this path by prepending the current
 |      working directory. No normalization or symlink resolution is performed.
 |
 |      Use resolve() to get the canonical path to a file.
 |
 |  as_uri(self) -> 'str'
 |      Return the path as a 'file' URI.
 |
 |  async chmod(self, mode, *, follow_symlinks=True) from pathlib.Path
 |      Like :meth:`~pathlib.Path.chmod`, but async.
 |
 |      Change the permissions of the path, like os.chmod().
 |
 |  async exists(self, *, follow_symlinks=True) from pathlib.Path
 |      Like :meth:`~pathlib.Path.exists`, but async.
 |
 |      Whether this path exists.
 |
 |      This method normally follows symlinks; to check whether a symlink exists,
 |      add the argument follow_symlinks=False.
 |
 |  async expanduser(self) from pathlib.Path
 |      Like :meth:`~pathlib.Path.expanduser`, but async.
 |
 |      Return a new path with expanded ~ and ~user constructs
 |      (as returned by os.path.expanduser)
 |
 |  async glob(self, pattern, *, case_sensitive=None) from pathlib.Path
 |      Like :meth:`~pathlib.Path.glob`, but async.
 |
 |      Iterate over this subtree and yield all existing files (of any
 |      kind, including directories) matching the given relative pattern.
 |
 |      This is an async method that returns a synchronous iterator, so you
 |      use it like:
 |
 |      .. code:: python
 |
 |          for subpath in await mypath.glob():
 |              ...
 |
 |      .. note::
 |
 |          The iterator is loaded into memory immediately during the initial
 |          call (see `issue #501
 |          <https://github.com/python-trio/trio/issues/501>`__ for discussion).
 |
 |  async hardlink_to(self, target) from pathlib.Path
 |      Like :meth:`~pathlib.Path.hardlink_to`, but async.
 |
 |      Make this path a hard link pointing to the same file as *target*.
 |
 |      Note the order of arguments (self, target) is the reverse of os.link's.
 |
 |  async is_block_device(self) from pathlib.Path
 |      Like :meth:`~pathlib.Path.is_block_device`, but async.
 |
 |      Whether this path is a block device.
 |
 |  async is_char_device(self) from pathlib.Path
 |      Like :meth:`~pathlib.Path.is_char_device`, but async.
 |
 |      Whether this path is a character device.
 |
 |  async is_dir(self) from pathlib.Path
 |      Like :meth:`~pathlib.Path.is_dir`, but async.
 |
 |      Whether this path is a directory.
 |
 |  async is_fifo(self) from pathlib.Path
 |      Like :meth:`~pathlib.Path.is_fifo`, but async.
 |
 |      Whether this path is a FIFO.
 |
 |  async is_file(self) from pathlib.Path
 |      Like :meth:`~pathlib.Path.is_file`, but async.
 |
 |      Whether this path is a regular file (also True for symlinks pointing
 |      to regular files).
 |
 |  async is_junction(self) from pathlib.Path
 |      Like :meth:`~pathlib.Path.is_junction`, but async.
 |
 |      Whether this path is a junction.
 |
 |  async is_mount(self) from pathlib.Path
 |      Like :meth:`~pathlib.Path.is_mount`, but async.
 |
 |      Check if this path is a mount point
 |
 |  async is_socket(self) from pathlib.Path
 |      Like :meth:`~pathlib.Path.is_socket`, but async.
 |
 |      Whether this path is a socket.
 |
 |  async is_symlink(self) from pathlib.Path
 |      Like :meth:`~pathlib.Path.is_symlink`, but async.
 |
 |      Whether this path is a symbolic link.
 |
 |  async iterdir(self) from pathlib.Path
 |      Like :meth:`~pathlib.Path.iterdir`, but async.
 |
 |      Yield path objects of the directory contents.
 |
 |      The children are yielded in arbitrary order, and the
 |      special entries '.' and '..' are not included.
 |
 |      This is an async method that returns a synchronous iterator, so you
 |      use it like:
 |
 |      .. code:: python
 |
 |          for subpath in await mypath.iterdir():
 |              ...
 |
 |      .. note::
 |
 |          The iterator is loaded into memory immediately during the initial
 |          call (see `issue #501
 |          <https://github.com/python-trio/trio/issues/501>`__ for discussion).
 |
 |  async lchmod(self, mode) from pathlib.Path
 |      Like :meth:`~pathlib.Path.lchmod`, but async.
 |
 |      Like chmod(), except if the path points to a symlink, the symlink's
 |      permissions are changed, rather than its target's.
 |
 |  async lstat(self) from pathlib.Path
 |      Like :meth:`~pathlib.Path.lstat`, but async.
 |
 |      Like stat(), except if the path points to a symlink, the symlink's
 |      status information is returned, rather than its target's.
 |
 |  async mkdir(self, mode=511, parents=False, exist_ok=False) from pathlib.Path
 |      Like :meth:`~pathlib.Path.mkdir`, but async.
 |
 |      Create a new directory at this given path.
 |
 |  async open(self, mode='r', buffering=-1, encoding=None, errors=None, newline=None) from pathlib.Path
 |      Like :meth:`~pathlib.Path.open`, but async.
 |
 |      Open the file pointed to by this path and return a file object, as
 |      the built-in open() function does.
 |
 |  async read_bytes(self) from pathlib.Path
 |      Like :meth:`~pathlib.Path.read_bytes`, but async.
 |
 |      Open the file in bytes mode, read it, and close the file.
 |
 |  async read_text(self, encoding=None, errors=None) from pathlib.Path
 |      Like :meth:`~pathlib.Path.read_text`, but async.
 |
 |      Open the file in text mode, read it, and close the file.
 |
 |  async readlink(self) from pathlib.Path
 |      Like :meth:`~pathlib.Path.readlink`, but async.
 |
 |      Return the path to which the symbolic link points.
 |
 |  async rename(self, target) from pathlib.Path
 |      Like :meth:`~pathlib.Path.rename`, but async.
 |
 |      Rename this path to the target path.
 |
 |      The target path may be absolute or relative. Relative paths are
 |      interpreted relative to the current working directory, *not* the
 |      directory of the Path object.
 |
 |      Returns the new Path instance pointing to the target path.
 |
 |  async replace(self, target) from pathlib.Path
 |      Like :meth:`~pathlib.Path.replace`, but async.
 |
 |      Rename this path to the target path, overwriting if that path exists.
 |
 |      The target path may be absolute or relative. Relative paths are
 |      interpreted relative to the current working directory, *not* the
 |      directory of the Path object.
 |
 |      Returns the new Path instance pointing to the target path.
 |
 |  async resolve(self, strict=False) from pathlib.Path
 |      Like :meth:`~pathlib.Path.resolve`, but async.
 |
 |      Make the path absolute, resolving all symlinks on the way and also
 |      normalizing it.
 |
 |  async rglob(self, pattern, *, case_sensitive=None) from pathlib.Path
 |      Like :meth:`~pathlib.Path.rglob`, but async.
 |
 |      Recursively yield all existing files (of any kind, including
 |      directories) matching the given relative pattern, anywhere in
 |      this subtree.
 |
 |      This is an async method that returns a synchronous iterator, so you
 |      use it like:
 |
 |      .. code:: python
 |
 |          for subpath in await mypath.rglob():
 |              ...
 |
 |      .. note::
 |
 |          The iterator is loaded into memory immediately during the initial
 |          call (see `issue #501
 |          <https://github.com/python-trio/trio/issues/501>`__ for discussion).
 |
 |  async rmdir(self) from pathlib.Path
 |      Like :meth:`~pathlib.Path.rmdir`, but async.
 |
 |      Remove this directory.  The directory must be empty.
 |
 |  async samefile(self, other_path) from pathlib.Path
 |      Like :meth:`~pathlib.Path.samefile`, but async.
 |
 |      Return whether other_path is the same or not as this file
 |      (as returned by os.path.samefile()).
 |
 |  async stat(self, *, follow_symlinks=True) from pathlib.Path
 |      Like :meth:`~pathlib.Path.stat`, but async.
 |
 |      Return the result of the stat() system call on this path, like
 |      os.stat() does.
 |
 |  async symlink_to(self, target, target_is_directory=False) from pathlib.Path
 |      Like :meth:`~pathlib.Path.symlink_to`, but async.
 |
 |      Make this path a symlink pointing to the target path.
 |      Note the order of arguments (link, target) is the reverse of os.symlink.
 |
 |  async touch(self, mode=438, exist_ok=True) from pathlib.Path
 |      Like :meth:`~pathlib.Path.touch`, but async.
 |
 |      Create this file with the given access mode, if it doesn't exist.
 |
 |  async unlink(self, missing_ok=False) from pathlib.Path
 |      Like :meth:`~pathlib.Path.unlink`, but async.
 |
 |      Remove this file or link.
 |      If the path is a directory, use rmdir() instead.
 |
 |  async write_bytes(self, data) from pathlib.Path
 |      Like :meth:`~pathlib.Path.write_bytes`, but async.
 |
 |      Open the file in bytes mode, write to it, and close the file.
 |
 |  async write_text(self, data, encoding=None, errors=None, newline=None) from pathlib.Path
 |      Like :meth:`~pathlib.Path.write_text`, but async.
 |
 |      Open the file in text mode, write to it, and close the file.
 |
 |  ----------------------------------------------------------------------
 |  Class methods inherited from Path:
 |
 |  async cwd(...) from pathlib.Path
 |      Like :meth:`~pathlib.Path.cwd`, but async.
 |
 |      Return a new path pointing to the current working directory.
 |
 |  async home(...) from pathlib.Path
 |      Like :meth:`~pathlib.Path.home`, but async.
 |
 |      Return a new path pointing to the user's home directory (as
 |      returned by os.path.expanduser('~')).
 |
 |  ----------------------------------------------------------------------
 |  Static methods inherited from Path:
 |
 |  __new__(cls, *args: 'str | os.PathLike[str]') -> 'Self' from trio._path.Path
 |      Construct a PurePath from one or several strings and or existing
 |      PurePath objects.  The strings and path objects are combined so as
 |      to yield a canonicalized path, which is incorporated into the
 |      new PurePath object.
 |
 |  ----------------------------------------------------------------------
 |  Methods inherited from pathlib.PurePath:
 |
 |  __bytes__(self)
 |      Return the bytes representation of the path.  This is only
 |      recommended to use under Unix.
 |
 |  __eq__(self, other)
 |      Return self==value.
 |
 |  __fspath__(self)
 |
 |  __ge__(self, other)
 |      Return self>=value.
 |
 |  __gt__(self, other)
 |      Return self>value.
 |
 |  __hash__(self)
 |      Return hash(self).
 |
 |  __init__(self, *args)
 |      Initialize self.  See help(type(self)) for accurate signature.
 |
 |  __le__(self, other)
 |      Return self<=value.
 |
 |  __lt__(self, other)
 |      Return self<value.
 |
 |  __reduce__(self)
 |      Helper for pickle.
 |
 |  __rtruediv__(self, key)
 |
 |  __str__(self)
 |      Return the string representation of the path, suitable for
 |      passing to system calls.
 |
 |  __truediv__(self, key)
 |
 |  as_posix(self)
 |      Return the string representation of the path with forward (/)
 |      slashes.
 |
 |  is_absolute(self)
 |      True if the path is absolute (has both a root and, if applicable,
 |      a drive).
 |
 |  is_relative_to(self, other, /, *_deprecated)
 |      Return True if the path is relative to another path or False.
 |
 |  is_reserved(self)
 |      Return True if the path contains one of the special names reserved
 |      by the system, if any.
 |
 |  joinpath(self, *pathsegments)
 |      Combine this path with one or several arguments, and return a
 |      new path representing either a subpath (if all arguments are relative
 |      paths) or a totally different path (if one of the arguments is
 |      anchored).
 |
 |  match(self, path_pattern, *, case_sensitive=None)
 |      Return True if this path matches the given pattern.
 |
 |  relative_to(self, other, /, *_deprecated, walk_up=False)
 |      Return the relative path to another path identified by the passed
 |      arguments.  If the operation is not possible (because this is not
 |      related to the other path), raise ValueError.
 |
 |      The *walk_up* parameter controls whether ``..`` may be used to resolve
 |      the path.
 |
 |  with_name(self, name)
 |      Return a new path with the file name changed.
 |
 |  with_segments(self, *pathsegments)
 |      Construct a new path object from any number of path-like objects.
 |      Subclasses may override this method to customize how new path objects
 |      are created from methods like `iterdir()`.
 |
 |  with_stem(self, stem)
 |      Return a new path with the stem changed.
 |
 |  with_suffix(self, suffix)
 |      Return a new path with the file suffix changed.  If the path
 |      has no suffix, add given suffix.  If the given suffix is an empty
 |      string, remove the suffix from the path.
 |
 |  ----------------------------------------------------------------------
 |  Readonly properties inherited from pathlib.PurePath:
 |
 |  anchor
 |      The concatenation of the drive and root, or ''.
 |
 |  drive
 |      The drive prefix (letter or UNC path), if any.
 |
 |  name
 |      The final path component, if any.
 |
 |  parent
 |      The logical parent of the path.
 |
 |  parents
 |      A sequence of this path's logical parents.
 |
 |  parts
 |      An object providing sequence-like access to the
 |      components in the filesystem path.
 |
 |  root
 |      The root of the path, if any.
 |
 |  stem
 |      The final path component, minus its last suffix.
 |
 |  suffix
 |      The final component's last suffix, if any.
 |
 |      This includes the leading period. For example: '.txt'
 |
 |  suffixes
 |      A list of the final component's suffixes, if any.
 |
 |      These include the leading periods. For example: ['.tar', '.gz']
trio.WouldBlock
Python Library Documentation: class WouldBlock in module trio

class WouldBlock(builtins.Exception)
 |  Raised by ``X_nowait`` functions if ``X`` would block.
 |
 |  Method resolution order:
 |      WouldBlock
 |      builtins.Exception
 |      builtins.BaseException
 |      builtins.object
 |
 |  Data descriptors defined here:
 |
 |  __weakref__
 |      list of weak references to the object
 |
 |  ----------------------------------------------------------------------
 |  Methods inherited from builtins.Exception:
 |
 |  __init__(self, /, *args, **kwargs)
 |      Initialize self.  See help(type(self)) for accurate signature.
 |
 |  ----------------------------------------------------------------------
 |  Static methods inherited from builtins.Exception:
 |
 |  __new__(*args, **kwargs) class method of builtins.Exception
 |      Create and return a new object.  See help(type) for accurate signature.
 |
 |  ----------------------------------------------------------------------
 |  Methods inherited from builtins.BaseException:
 |
 |  __getattribute__(self, name, /)
 |      Return getattr(self, name).
 |
 |  __reduce__(...)
 |      Helper for pickle.
 |
 |  __repr__(self, /)
 |      Return repr(self).
 |
 |  __setstate__(...)
 |
 |  __str__(self, /)
 |      Return str(self).
 |
 |  add_note(...)
 |      Exception.add_note(note) --
 |      add a note to the exception
 |
 |  with_traceback(...)
 |      Exception.with_traceback(tb) --
 |      set self.__traceback__ to tb and return self.
 |
 |  ----------------------------------------------------------------------
 |  Data descriptors inherited from builtins.BaseException:
 |
 |  __cause__
 |      exception cause
 |
 |  __context__
 |      exception context
 |
 |  __dict__
 |
 |  __suppress_context__
 |
 |  __traceback__
 |
 |  args
trio.aclose_forcefully
Python Library Documentation: function aclose_forcefully in module trio

async aclose_forcefully(resource: 'AsyncResource') -> 'None'
    Close an async resource or async generator immediately, without
    blocking to do any graceful cleanup.

    :class:`~trio.abc.AsyncResource` objects guarantee that if their
    :meth:`~trio.abc.AsyncResource.aclose` method is cancelled, then they will
    still close the resource (albeit in a potentially ungraceful
    fashion). :func:`aclose_forcefully` is a convenience function that
    exploits this behavior to let you force a resource to be closed without
    blocking: it works by calling ``await resource.aclose()`` and then
    cancelling it immediately.

    Most users won't need this, but it may be useful on cleanup paths where
    you can't afford to block, or if you want to close a resource and don't
    care about handling it gracefully. For example, if
    :class:`~trio.SSLStream` encounters an error and cannot perform its
    own graceful close, then there's no point in waiting to gracefully shut
    down the underlying transport either, so it calls ``await
    aclose_forcefully(self.transport_stream)``.

    Note that this function is async, and that it acts as a checkpoint, but
    unlike most async functions it cannot block indefinitely (at least,
    assuming the underlying resource object is correctly implemented).
trio.annotations
Python Library Documentation: _Feature in module __future__ object

class _Feature(builtins.object)
 |  _Feature(optionalRelease, mandatoryRelease, compiler_flag)
 |
 |  Methods defined here:
 |
 |  __init__(self, optionalRelease, mandatoryRelease, compiler_flag)
 |      Initialize self.  See help(type(self)) for accurate signature.
 |
 |  __repr__(self)
 |      Return repr(self).
 |
 |  getMandatoryRelease(self)
 |      Return release in which this feature will become mandatory.
 |
 |      This is a 5-tuple, of the same form as sys.version_info, or, if
 |      the feature was dropped, or the release date is undetermined, is None.
 |
 |  getOptionalRelease(self)
 |      Return first release in which this feature was recognized.
 |
 |      This is a 5-tuple, of the same form as sys.version_info.
 |
 |  ----------------------------------------------------------------------
 |  Data descriptors defined here:
 |
 |  __dict__
 |      dictionary for instance variables
 |
 |  __weakref__
 |      list of weak references to the object
trio.as_safe_channel
Python Library Documentation: function as_safe_channel in module trio

as_safe_channel(fn: 'Callable[P, AsyncGenerator[T, None]]') -> 'Callable[P, AbstractAsyncContextManager[ReceiveChannel[T]]]'
    Decorate an async generator function to make it cancellation-safe.

    The ``yield`` keyword offers a very convenient way to write iterators...
    which makes it really unfortunate that async generators are so difficult
    to call correctly.  Yielding from the inside of a cancel scope or a nursery
    to the outside `violates structured concurrency <https://xkcd.com/292/>`_
    with consequences explained in :pep:`789`.  Even then, resource cleanup
    errors remain common (:pep:`533`) unless you wrap every call in
    :func:`~contextlib.aclosing`.

    This decorator gives you the best of both worlds: with careful exception
    handling and a background task we preserve structured concurrency by
    offering only the safe interface, and you can still write your iterables
    with the convenience of ``yield``.  For example::

        @as_safe_channel
        async def my_async_iterable(arg, *, kwarg=True):
            while ...:
                item = await ...
                yield item

        async with my_async_iterable(...) as recv_chan:
            async for item in recv_chan:
                ...

    While the combined async-with-async-for can be inconvenient at first,
    the context manager is indispensable for both correctness and for prompt
    cleanup of resources.
trio.current_effective_deadline
Python Library Documentation: function current_effective_deadline in module trio

current_effective_deadline() -> 'float'
    Returns the current effective deadline for the current task.

    This function examines all the cancellation scopes that are currently in
    effect (taking into account shielding), and returns the deadline that will
    expire first.

    One example of where this might be is useful is if your code is trying to
    decide whether to begin an expensive operation like an RPC call, but wants
    to skip it if it knows that it can't possibly complete in the available
    time. Another example would be if you're using a protocol like gRPC that
    `propagates timeout information to the remote peer
    <http://www.grpc.io/docs/guides/concepts.html#deadlines>`__; this function
    gives a way to fetch that information so you can send it along.

    If this is called in a context where a cancellation is currently active
    (i.e., a blocking call will immediately raise :exc:`Cancelled`), then
    returned deadline is ``-inf``. If it is called in a context where no
    scopes have a deadline set, it returns ``inf``.

    Returns:
        float: the effective deadline, as an absolute time.
trio.current_time
Python Library Documentation: function current_time in module trio

current_time() -> 'float'
    Returns the current time according to Trio's internal clock.

    Returns:
        float: The current time.

    Raises:
        RuntimeError: if not inside a call to :func:`trio.run`.
trio.fail_after
Python Library Documentation: function fail_after in module trio

fail_after(seconds: 'float', *, shield: 'bool' = False) -> 'Generator[trio.CancelScope, None, None]'
    Creates a cancel scope with the given timeout, and raises an error if
    it is actually cancelled.

    This function and :func:`move_on_after` are similar in that both create a
    cancel scope with a given timeout, and if the timeout expires then both
    will cause :exc:`Cancelled` to be raised within the scope. The difference
    is that when the :exc:`Cancelled` exception reaches :func:`move_on_after`,
    it's caught and discarded. When it reaches :func:`fail_after`, then it's
    caught and :exc:`TooSlowError` is raised in its place.

    The deadline of the cancel scope is calculated upon entering.

    Args:
      seconds (float): The timeout.
      shield (bool): Initial value for the `~trio.CancelScope.shield` attribute
          of the newly created cancel scope.

    Raises:
      TooSlowError: if a :exc:`Cancelled` exception is raised in this scope
        and caught by the context manager.
      ValueError: if *seconds* is less than zero or NaN.
trio.fail_at
Python Library Documentation: function fail_at in module trio

fail_at(deadline: 'float', *, shield: 'bool' = False) -> 'Generator[trio.CancelScope, None, None]'
    Creates a cancel scope with the given deadline, and raises an error if it
    is actually cancelled.

    This function and :func:`move_on_at` are similar in that both create a
    cancel scope with a given absolute deadline, and if the deadline expires
    then both will cause :exc:`Cancelled` to be raised within the scope. The
    difference is that when the :exc:`Cancelled` exception reaches
    :func:`move_on_at`, it's caught and discarded. When it reaches
    :func:`fail_at`, then it's caught and :exc:`TooSlowError` is raised in its
    place.

    Args:
      deadline (float): The deadline.
      shield (bool): Initial value for the `~trio.CancelScope.shield` attribute
          of the newly created cancel scope.

    Raises:
      TooSlowError: if a :exc:`Cancelled` exception is raised in this scope
        and caught by the context manager.
      ValueError: if deadline is NaN.
trio.move_on_after
Python Library Documentation: function move_on_after in module trio

move_on_after(seconds: 'float', *, shield: 'bool' = False) -> 'trio.CancelScope'
    Use as a context manager to create a cancel scope whose deadline is
    set to now + *seconds*.

    The deadline of the cancel scope is calculated upon entering.

    Args:
      seconds (float): The timeout.
      shield (bool): Initial value for the `~trio.CancelScope.shield` attribute
          of the newly created cancel scope.

    Raises:
      ValueError: if ``seconds`` is less than zero or NaN.
trio.move_on_at
Python Library Documentation: function move_on_at in module trio

move_on_at(deadline: 'float', *, shield: 'bool' = False) -> 'trio.CancelScope'
    Use as a context manager to create a cancel scope with the given
    absolute deadline.

    Args:
      deadline (float): The deadline.
      shield (bool): Initial value for the `~trio.CancelScope.shield` attribute
          of the newly created cancel scope.

    Raises:
      ValueError: if deadline is NaN.
trio.open_file
Python Library Documentation: function open_file in module trio

async open_file(file: '_OpenFile', mode: 'str' = 'r', buffering: 'int' = -1, encoding: 'str | None' = None, errors: 'str | None' = None, newline: 'str | None' = None, closefd: 'bool' = True, opener: '_Opener | None' = None) -> 'AsyncIOWrapper[object]'
    Asynchronous version of :func:`open`.

    Returns:
        An :term:`asynchronous file object`

    Example::

        async with await trio.open_file(filename) as f:
            async for line in f:
                pass

        assert f.closed

    See also:
      :func:`trio.Path.open`
trio.open_memory_channel
Python Library Documentation: class open_memory_channel in module trio

class open_memory_channel(builtins.tuple)
 |  open_memory_channel(max_buffer_size: 'int | float') -> 'tuple[MemorySendChannel[T], MemoryReceiveChannel[T]]'
 |
 |  Open a channel for passing objects between tasks within a process.
 |
 |  Memory channels are lightweight, cheap to allocate, and entirely
 |  in-memory. They don't involve any operating-system resources, or any kind
 |  of serialization. They just pass Python objects directly between tasks
 |  (with a possible stop in an internal buffer along the way).
 |
 |  Channel objects can be closed by calling `~trio.abc.AsyncResource.aclose`
 |  or using ``async with``. They are *not* automatically closed when garbage
 |  collected. Closing memory channels isn't mandatory, but it is generally a
 |  good idea, because it helps avoid situations where tasks get stuck waiting
 |  on a channel when there's no-one on the other side. See
 |  :ref:`channel-shutdown` for details.
 |
 |  Memory channel operations are all atomic with respect to
 |  cancellation, either `~trio.abc.ReceiveChannel.receive` will
 |  successfully return an object, or it will raise :exc:`Cancelled`
 |  while leaving the channel unchanged.
 |
 |  Args:
 |    max_buffer_size (int or math.inf): The maximum number of items that can
 |      be buffered in the channel before :meth:`~trio.abc.SendChannel.send`
 |      blocks. Choosing a sensible value here is important to ensure that
 |      backpressure is communicated promptly and avoid unnecessary latency;
 |      see :ref:`channel-buffering` for more details. If in doubt, use 0.
 |
 |  Returns:
 |    A pair ``(send_channel, receive_channel)``. If you have
 |    trouble remembering which order these go in, remember: data
 |    flows from left → right.
 |
 |  In addition to the standard channel methods, all memory channel objects
 |  provide a ``statistics()`` method, which returns an object with the
 |  following fields:
 |
 |  * ``current_buffer_used``: The number of items currently stored in the
 |    channel buffer.
 |  * ``max_buffer_size``: The maximum number of items allowed in the buffer,
 |    as passed to :func:`open_memory_channel`.
 |  * ``open_send_channels``: The number of open
 |    :class:`MemorySendChannel` endpoints pointing to this channel.
 |    Initially 1, but can be increased by
 |    :meth:`MemorySendChannel.clone`.
 |  * ``open_receive_channels``: Likewise, but for open
 |    :class:`MemoryReceiveChannel` endpoints.
 |  * ``tasks_waiting_send``: The number of tasks blocked in ``send`` on this
 |    channel (summing over all clones).
 |  * ``tasks_waiting_receive``: The number of tasks blocked in ``receive`` on
 |    this channel (summing over all clones).
 |
 |  Method resolution order:
 |      open_memory_channel
 |      builtins.tuple
 |      builtins.object
 |
 |  Methods defined here:
 |
 |  __init__(self, max_buffer_size: 'int | float') -> 'None'
 |      Initialize self.  See help(type(self)) for accurate signature.
 |
 |  ----------------------------------------------------------------------
 |  Class methods defined here:
 |
 |  __init_subclass__ = _init_final_cls() -> 'NoReturn' from trio._util
 |      Raises an exception when a final class is subclassed.
 |
 |  ----------------------------------------------------------------------
 |  Static methods defined here:
 |
 |  __new__(cls, max_buffer_size: 'int | float') -> 'tuple[MemorySendChannel[T], MemoryReceiveChannel[T]]' from trio._channel.open_memory_channel
 |      Create and return a new object.  See help(type) for accurate signature.
 |
 |  ----------------------------------------------------------------------
 |  Data descriptors defined here:
 |
 |  __dict__
 |      dictionary for instance variables
 |
 |  ----------------------------------------------------------------------
 |  Data and other attributes defined here:
 |
 |  __final__ = True
 |
 |  __orig_bases__ = (tuple['MemorySendChannel[T]', 'MemoryReceiveChannel[...
 |
 |  ----------------------------------------------------------------------
 |  Methods inherited from builtins.tuple:
 |
 |  __add__(self, value, /)
 |      Return self+value.
 |
 |  __contains__(self, key, /)
 |      Return bool(key in self).
 |
 |  __eq__(self, value, /)
 |      Return self==value.
 |
 |  __ge__(self, value, /)
 |      Return self>=value.
 |
 |  __getattribute__(self, name, /)
 |      Return getattr(self, name).
 |
 |  __getitem__(self, key, /)
 |      Return self[key].
 |
 |  __getnewargs__(self, /)
 |
 |  __gt__(self, value, /)
 |      Return self>value.
 |
 |  __hash__(self, /)
 |      Return hash(self).
 |
 |  __iter__(self, /)
 |      Implement iter(self).
 |
 |  __le__(self, value, /)
 |      Return self<=value.
 |
 |  __len__(self, /)
 |      Return len(self).
 |
 |  __lt__(self, value, /)
 |      Return self<value.
 |
 |  __mul__(self, value, /)
 |      Return self*value.
 |
 |  __ne__(self, value, /)
 |      Return self!=value.
 |
 |  __repr__(self, /)
 |      Return repr(self).
 |
 |  __rmul__(self, value, /)
 |      Return value*self.
 |
 |  count(self, value, /)
 |      Return number of occurrences of value.
 |
 |  index(self, value, start=0, stop=9223372036854775807, /)
 |      Return first index of value.
 |
 |      Raises ValueError if the value is not present.
 |
 |  ----------------------------------------------------------------------
 |  Class methods inherited from builtins.tuple:
 |
 |  __class_getitem__(...)
 |      See PEP 585
trio.open_nursery
Python Library Documentation: function open_nursery in module trio

open_nursery(strict_exception_groups: 'bool | None' = None) -> 'AbstractAsyncContextManager[Nursery]'
    Returns an async context manager which must be used to create a
    new `Nursery`.

    It does not block on entry; on exit it blocks until all child tasks
    have exited. If no child tasks are running on exit, it will insert a
    schedule point (but no cancellation point) - equivalent to
    :func:`trio.lowlevel.cancel_shielded_checkpoint`. This means a nursery
    is never the source of a cancellation exception, it only propagates it
    from sub-tasks.

    Args:
      strict_exception_groups (bool): Unless set to False, even a single raised exception
          will be wrapped in an exception group. If not specified, uses the value passed
          to :func:`run`, which defaults to true. Setting it to False will be deprecated
          and ultimately removed in a future version of Trio.
trio.open_signal_receiver
Python Library Documentation: function open_signal_receiver in module trio

open_signal_receiver(*signals: 'signal.Signals | int') -> 'Generator[AsyncIterator[int], None, None]'
    A context manager for catching signals.

    Entering this context manager starts listening for the given signals and
    returns an async iterator; exiting the context manager stops listening.

    The async iterator blocks until a signal arrives, and then yields it.

    Note that if you leave the ``with`` block while the iterator has
    unextracted signals still pending inside it, then they will be
    re-delivered using Python's regular signal handling logic. This avoids a
    race condition when signals arrives just before we exit the ``with``
    block.

    Args:
      signals: the signals to listen for.

    Raises:
      TypeError: if no signals were provided.

      RuntimeError: if you try to use this anywhere except Python's main
          thread. (This is a Python limitation.)

    Example:

      A common convention for Unix daemons is that they should reload their
      configuration when they receive a ``SIGHUP``. Here's a sketch of what
      that might look like using :func:`open_signal_receiver`::

         with trio.open_signal_receiver(signal.SIGHUP) as signal_aiter:
             async for signum in signal_aiter:
                 assert signum == signal.SIGHUP
                 reload_configuration()
trio.open_ssl_over_tcp_listeners
Python Library Documentation: function open_ssl_over_tcp_listeners in module trio

async open_ssl_over_tcp_listeners(port: 'int', ssl_context: 'ssl.SSLContext', *, host: 'str | bytes | None' = None, https_compatible: 'bool' = False, backlog: 'int | None' = None) -> 'list[trio.SSLListener[SocketStream]]'
    Start listening for SSL/TLS-encrypted TCP connections to the given port.

    Args:
      port (int): The port to listen on. See :func:`open_tcp_listeners`.
      ssl_context (~ssl.SSLContext): The SSL context to use for all incoming
          connections.
      host (str, bytes, or None): The address to bind to; use ``None`` to bind
          to the wildcard address. See :func:`open_tcp_listeners`.
      https_compatible (bool): See :class:`~trio.SSLStream` for details.
      backlog (int or None): See :func:`open_tcp_listeners` for details.
trio.open_ssl_over_tcp_stream
Python Library Documentation: function open_ssl_over_tcp_stream in module trio

async open_ssl_over_tcp_stream(host: 'str | bytes', port: 'int', *, https_compatible: 'bool' = False, ssl_context: 'ssl.SSLContext | None' = None, happy_eyeballs_delay: 'float | None' = 0.25) -> 'trio.SSLStream[SocketStream]'
    Make a TLS-encrypted Connection to the given host and port over TCP.

    This is a convenience wrapper that calls :func:`open_tcp_stream` and
    wraps the result in an :class:`~trio.SSLStream`.

    This function does not perform the TLS handshake; you can do it
    manually by calling :meth:`~trio.SSLStream.do_handshake`, or else
    it will be performed automatically the first time you send or receive
    data.

    Args:
      host (bytes or str): The host to connect to. We require the server
          to have a TLS certificate valid for this hostname.
      port (int): The port to connect to.
      https_compatible (bool): Set this to True if you're connecting to a web
          server. See :class:`~trio.SSLStream` for details. Default:
          False.
      ssl_context (:class:`~ssl.SSLContext` or None): The SSL context to
          use. If None (the default), :func:`ssl.create_default_context`
          will be called to create a context.
      happy_eyeballs_delay (float): See :func:`open_tcp_stream`.

    Returns:
      trio.SSLStream: the encrypted connection to the server.
trio.open_tcp_listeners
Python Library Documentation: function open_tcp_listeners in module trio

async open_tcp_listeners(port: 'int', *, host: 'str | bytes | None' = None, backlog: 'int | None' = None) -> 'list[trio.SocketListener]'
    Create :class:`SocketListener` objects to listen for TCP connections.

    Args:

      port (int): The port to listen on.

          If you use 0 as your port, then the kernel will automatically pick
          an arbitrary open port. But be careful: if you use this feature when
          binding to multiple IP addresses, then each IP address will get its
          own random port, and the returned listeners will probably be
          listening on different ports. In particular, this will happen if you
          use ``host=None`` – which is the default – because in this case
          :func:`open_tcp_listeners` will bind to both the IPv4 wildcard
          address (``0.0.0.0``) and also the IPv6 wildcard address (``::``).

      host (str, bytes, or None): The local interface to bind to. This is
          passed to :func:`~socket.getaddrinfo` with the ``AI_PASSIVE`` flag
          set.

          If you want to bind to the wildcard address on both IPv4 and IPv6,
          in order to accept connections on all available interfaces, then
          pass ``None``. This is the default.

          If you have a specific interface you want to bind to, pass its IP
          address or hostname here. If a hostname resolves to multiple IP
          addresses, this function will open one listener on each of them.

          If you want to use only IPv4, or only IPv6, but want to accept on
          all interfaces, pass the family-specific wildcard address:
          ``"0.0.0.0"`` for IPv4-only and ``"::"`` for IPv6-only.

      backlog (int or None): The listen backlog to use. If you leave this as
          ``None`` then Trio will pick a good default. (Currently: whatever
          your system has configured as the maximum backlog.)

    Returns:
      list of :class:`SocketListener`

    Raises:
      :class:`TypeError` if invalid arguments.
trio.open_tcp_stream
Python Library Documentation: function open_tcp_stream in module trio

async open_tcp_stream(host: 'str | bytes', port: 'int', *, happy_eyeballs_delay: 'float | None' = 0.25, local_address: 'str | None' = None) -> 'trio.SocketStream'
    Connect to the given host and port over TCP.

    If the given ``host`` has multiple IP addresses associated with it, then
    we have a problem: which one do we use?

    One approach would be to attempt to connect to the first one, and then if
    that fails, attempt to connect to the second one ... until we've tried all
    of them. But the problem with this is that if the first IP address is
    unreachable (for example, because it's an IPv6 address and our network
    discards IPv6 packets), then we might end up waiting tens of seconds for
    the first connection attempt to timeout before we try the second address.

    Another approach would be to attempt to connect to all of the addresses at
    the same time, in parallel, and then use whichever connection succeeds
    first, abandoning the others. This would be fast, but create a lot of
    unnecessary load on the network and the remote server.

    This function strikes a balance between these two extremes: it works its
    way through the available addresses one at a time, like the first
    approach; but, if ``happy_eyeballs_delay`` seconds have passed and it's
    still waiting for an attempt to succeed or fail, then it gets impatient
    and starts the next connection attempt in parallel. As soon as any one
    connection attempt succeeds, all the other attempts are cancelled. This
    avoids unnecessary load because most connections will succeed after just
    one or two attempts, but if one of the addresses is unreachable then it
    doesn't slow us down too much.

    This is known as a "happy eyeballs" algorithm, and our particular variant
    is modelled after how Chrome connects to webservers; see `RFC 6555
    <https://tools.ietf.org/html/rfc6555>`__ for more details.

    Args:
      host (str or bytes): The host to connect to. Can be an IPv4 address,
          IPv6 address, or a hostname.

      port (int): The port to connect to.

      happy_eyeballs_delay (float or None): How many seconds to wait for each
          connection attempt to succeed or fail before getting impatient and
          starting another one in parallel. Set to `None` if you want
          to limit to only one connection attempt at a time (like
          :func:`socket.create_connection`). Default: 0.25 (250 ms).

      local_address (None or str): The local IP address or hostname to use as
          the source for outgoing connections. If ``None``, we let the OS pick
          the source IP.

          This is useful in some exotic networking configurations where your
          host has multiple IP addresses, and you want to force the use of a
          specific one.

          Note that if you pass an IPv4 ``local_address``, then you won't be
          able to connect to IPv6 hosts, and vice-versa. If you want to take
          advantage of this to force the use of IPv4 or IPv6 without
          specifying an exact source address, you can use the IPv4 wildcard
          address ``local_address="0.0.0.0"``, or the IPv6 wildcard address
          ``local_address="::"``.

    Returns:
      SocketStream: a :class:`~trio.abc.Stream` connected to the given server.

    Raises:
      OSError: if the connection fails.

    See also:
      open_ssl_over_tcp_stream
trio.open_unix_socket
Python Library Documentation: function open_unix_socket in module trio

async open_unix_socket(filename: 'str | bytes | os.PathLike[str] | os.PathLike[bytes]') -> 'trio.SocketStream'
    Opens a connection to the specified
    `Unix domain socket <https://en.wikipedia.org/wiki/Unix_domain_socket>`__.

    You must have read/write permission on the specified file to connect.

    Args:
      filename (str or bytes): The filename to open the connection to.

    Returns:
      SocketStream: a :class:`~trio.abc.Stream` connected to the given file.

    Raises:
      OSError: If the socket file could not be connected to.
      RuntimeError: If AF_UNIX sockets are not supported.
trio.run
Python Library Documentation: function run in module trio

run(async_fn: 'Callable[[Unpack[PosArgT]], Awaitable[RetT]]', *args: 'Unpack[PosArgT]', clock: 'Clock | None' = None, instruments: 'Sequence[Instrument]' = (), restrict_keyboard_interrupt_to_checkpoints: 'bool' = False, strict_exception_groups: 'bool' = True) -> 'RetT'
    Run a Trio-flavored async function, and return the result.

    Calling::

       run(async_fn, *args)

    is the equivalent of::

       await async_fn(*args)

    except that :func:`run` can (and must) be called from a synchronous
    context.

    This is Trio's main entry point. Almost every other function in Trio
    requires that you be inside a call to :func:`run`.

    Args:
      async_fn: An async function.

      args: Positional arguments to be passed to *async_fn*. If you need to
          pass keyword arguments, then use :func:`functools.partial`.

      clock: ``None`` to use the default system-specific monotonic clock;
          otherwise, an object implementing the :class:`trio.abc.Clock`
          interface, like (for example) a :class:`trio.testing.MockClock`
          instance.

      instruments (list of :class:`trio.abc.Instrument` objects): Any
          instrumentation you want to apply to this run. This can also be
          modified during the run; see :ref:`instrumentation`.

      restrict_keyboard_interrupt_to_checkpoints (bool): What happens if the
          user hits control-C while :func:`run` is running? If this argument
          is False (the default), then you get the standard Python behavior: a
          :exc:`KeyboardInterrupt` exception will immediately interrupt
          whatever task is running (or if no task is running, then Trio will
          wake up a task to be interrupted). Alternatively, if you set this
          argument to True, then :exc:`KeyboardInterrupt` delivery will be
          delayed: it will be *only* be raised at :ref:`checkpoints
          <checkpoints>`, like a :exc:`Cancelled` exception.

          The default behavior is nice because it means that even if you
          accidentally write an infinite loop that never executes any
          checkpoints, then you can still break out of it using control-C.
          The alternative behavior is nice if you're paranoid about a
          :exc:`KeyboardInterrupt` at just the wrong place leaving your
          program in an inconsistent state, because it means that you only
          have to worry about :exc:`KeyboardInterrupt` at the exact same
          places where you already have to worry about :exc:`Cancelled`.

          This setting has no effect if your program has registered a custom
          SIGINT handler, or if :func:`run` is called from anywhere but the
          main thread (this is a Python limitation), or if you use
          :func:`open_signal_receiver` to catch SIGINT.

      strict_exception_groups (bool): Unless set to False, nurseries will always wrap
          even a single raised exception in an exception group. This can be overridden
          on the level of individual nurseries. Setting it to False will be deprecated
          and ultimately removed in a future version of Trio.

    Returns:
      Whatever ``async_fn`` returns.

    Raises:
      TrioInternalError: if an unexpected error is encountered inside Trio's
          internal machinery. This is a bug and you should `let us know
          <https://github.com/python-trio/trio/issues>`__.

      Anything else: if ``async_fn`` raises an exception, then :func:`run`
          propagates it.
trio.run_process
Python Library Documentation: function run_process in module trio

async run_process(command: 'StrOrBytesPath | Sequence[StrOrBytesPath]', *, stdin: 'bytes | bytearray | memoryview | int | HasFileno | None' = b'', capture_stdout: 'bool' = False, capture_stderr: 'bool' = False, check: 'bool' = True, deliver_cancel: 'Callable[[Process], Awaitable[object]] | None' = None, task_status: 'TaskStatus[Process]' = TASK_STATUS_IGNORED, **options: 'object') -> 'subprocess.CompletedProcess[bytes]'
    Run ``command`` in a subprocess and wait for it to complete.

    This function can be called in two different ways.

    One option is a direct call, like::

        completed_process_info = await trio.run_process(...)

    In this case, it returns a :class:`subprocess.CompletedProcess` instance
    describing the results. Use this if you want to treat a process like a
    function call.

    The other option is to run it as a task using `Nursery.start` – the enhanced version
    of `~Nursery.start_soon` that lets a task pass back a value during startup::

        process = await nursery.start(trio.run_process, ...)

    In this case, `~Nursery.start` returns a `Process` object that you can use
    to interact with the process while it's running. Use this if you want to
    treat a process like a background task.

    Either way, `run_process` makes sure that the process has exited before
    returning, handles cancellation, optionally checks for errors, and
    provides some convenient shorthands for dealing with the child's
    input/output.

    **Input:** `run_process` supports all the same ``stdin=`` arguments as
    `subprocess.Popen`. In addition, if you simply want to pass in some fixed
    data, you can pass a plain `bytes` object, and `run_process` will take
    care of setting up a pipe, feeding in the data you gave, and then sending
    end-of-file. The default is ``b""``, which means that the child will receive
    an empty stdin. If you want the child to instead read from the parent's
    stdin, use ``stdin=None``.

    **Output:** By default, any output produced by the subprocess is
    passed through to the standard output and error streams of the
    parent Trio process.

    When calling `run_process` directly, you can capture the subprocess's output by
    passing ``capture_stdout=True`` to capture the subprocess's standard output, and/or
    ``capture_stderr=True`` to capture its standard error. Captured data is collected up
    by Trio into an in-memory buffer, and then provided as the
    :attr:`~subprocess.CompletedProcess.stdout` and/or
    :attr:`~subprocess.CompletedProcess.stderr` attributes of the returned
    :class:`~subprocess.CompletedProcess` object. The value for any stream that was not
    captured will be ``None``.

    If you want to capture both stdout and stderr while keeping them
    separate, pass ``capture_stdout=True, capture_stderr=True``.

    If you want to capture both stdout and stderr but mixed together
    in the order they were printed, use: ``capture_stdout=True, stderr=subprocess.STDOUT``.
    This directs the child's stderr into its stdout, so the combined
    output will be available in the `~subprocess.CompletedProcess.stdout`
    attribute.

    If you're using ``await nursery.start(trio.run_process, ...)`` and want to capture
    the subprocess's output for further processing, then use ``stdout=subprocess.PIPE``
    and then make sure to read the data out of the `Process.stdout` stream. If you want
    to capture stderr separately, use ``stderr=subprocess.PIPE``. If you want to capture
    both, but mixed together in the correct order, use ``stdout=subprocess.PIPE,
    stderr=subprocess.STDOUT``.

    **Error checking:** If the subprocess exits with a nonzero status
    code, indicating failure, :func:`run_process` raises a
    :exc:`subprocess.CalledProcessError` exception rather than
    returning normally. The captured outputs are still available as
    the :attr:`~subprocess.CalledProcessError.stdout` and
    :attr:`~subprocess.CalledProcessError.stderr` attributes of that
    exception.  To disable this behavior, so that :func:`run_process`
    returns normally even if the subprocess exits abnormally, pass ``check=False``.

    Note that this can make the ``capture_stdout`` and ``capture_stderr``
    arguments useful even when starting `run_process` as a task: if you only
    care about the output if the process fails, then you can enable capturing
    and then read the output off of the `~subprocess.CalledProcessError`.

    **Cancellation:** If cancelled, `run_process` sends a termination
    request to the subprocess, then waits for it to fully exit. The
    ``deliver_cancel`` argument lets you control how the process is terminated.

    .. note:: `run_process` is intentionally similar to the standard library
       `subprocess.run`, but some of the defaults are different. Specifically, we
       default to:

       - ``check=True``, because `"errors should never pass silently / unless
         explicitly silenced" <https://www.python.org/dev/peps/pep-0020/>`__.

       - ``stdin=b""``, because it produces less-confusing results if a subprocess
         unexpectedly tries to read from stdin.

       To get the `subprocess.run` semantics, use ``check=False, stdin=None``.

    Args:
      command (list or str): The command to run. Typically this is a
          sequence of strings such as ``['ls', '-l', 'directory with spaces']``,
          where the first element names the executable to invoke and the other
          elements specify its arguments. With ``shell=True`` in the
          ``**options``, or on Windows, ``command`` may alternatively
          be a string, which will be parsed following platform-dependent
          :ref:`quoting rules <subprocess-quoting>`.

      stdin (:obj:`bytes`, subprocess.PIPE, file descriptor, or None): The
          bytes to provide to the subprocess on its standard input stream, or
          ``None`` if the subprocess's standard input should come from the
          same place as the parent Trio process's standard input. As is the
          case with the :mod:`subprocess` module, you can also pass a file
          descriptor or an object with a ``fileno()`` method, in which case
          the subprocess's standard input will come from that file.

          When starting `run_process` as a background task, you can also use
          ``stdin=subprocess.PIPE``, in which case `Process.stdin` will be a
          `~trio.abc.SendStream` that you can use to send data to the child.

      capture_stdout (bool): If true, capture the bytes that the subprocess
          writes to its standard output stream and return them in the
          `~subprocess.CompletedProcess.stdout` attribute of the returned
          `subprocess.CompletedProcess` or `subprocess.CalledProcessError`.

      capture_stderr (bool): If true, capture the bytes that the subprocess
          writes to its standard error stream and return them in the
          `~subprocess.CompletedProcess.stderr` attribute of the returned
          `~subprocess.CompletedProcess` or `subprocess.CalledProcessError`.

      check (bool): If false, don't validate that the subprocess exits
          successfully. You should be sure to check the
          ``returncode`` attribute of the returned object if you pass
          ``check=False``, so that errors don't pass silently.

      deliver_cancel (async function or None): If `run_process` is cancelled,
          then it needs to kill the child process. There are multiple ways to
          do this, so we let you customize it.

          If you pass None (the default), then the behavior depends on the
          platform:

          - On Windows, Trio calls ``TerminateProcess``, which should kill the
            process immediately.

          - On Unix-likes, the default behavior is to send a ``SIGTERM``, wait
            5 seconds, and send a ``SIGKILL``.

          Alternatively, you can customize this behavior by passing in an
          arbitrary async function, which will be called with the `Process`
          object as an argument. For example, the default Unix behavior could
          be implemented like this::

             async def my_deliver_cancel(process):
                 process.send_signal(signal.SIGTERM)
                 await trio.sleep(5)
                 process.send_signal(signal.SIGKILL)

          When the process actually exits, the ``deliver_cancel`` function
          will automatically be cancelled – so if the process exits after
          ``SIGTERM``, then we'll never reach the ``SIGKILL``.

          In any case, `run_process` will always wait for the child process to
          exit before raising `Cancelled`.

      **options: :func:`run_process` also accepts any :ref:`general subprocess
          options <subprocess-options>` and passes them on to the
          :class:`~trio.Process` constructor. This includes the
          ``stdout`` and ``stderr`` options, which provide additional
          redirection possibilities such as ``stderr=subprocess.STDOUT``,
          ``stdout=subprocess.DEVNULL``, or file descriptors.

    Returns:

      When called normally – a `subprocess.CompletedProcess` instance
      describing the return code and outputs.

      When called via `Nursery.start` – a `trio.Process` instance.

    Raises:
      UnicodeError: if ``stdin`` is specified as a Unicode string, rather
          than bytes
      ValueError: if multiple redirections are specified for the same
          stream, e.g., both ``capture_stdout=True`` and
          ``stdout=subprocess.DEVNULL``
      subprocess.CalledProcessError: if ``check=False`` is not passed
          and the process exits with a nonzero exit status
      OSError: if an error is encountered starting or communicating with
          the process
      ExceptionGroup: if exceptions occur in ``deliver_cancel``,
          or when exceptions occur when communicating with the subprocess.
          If strict_exception_groups is set to false in the global context,
          which is deprecated, then single exceptions will be collapsed.

    .. note:: The child process runs in the same process group as the parent
       Trio process, so a Ctrl+C will be delivered simultaneously to both
       parent and child. If you don't want this behavior, consult your
       platform's documentation for starting child processes in a different
       process group.
trio.serve_listeners
Python Library Documentation: function serve_listeners in module trio

async serve_listeners(handler: 'Handler[StreamT]', listeners: 'list[ListenerT]', *, handler_nursery: 'trio.Nursery | None' = None, task_status: 'trio.TaskStatus[list[ListenerT]]' = TASK_STATUS_IGNORED) -> 'NoReturn'
    Listen for incoming connections on ``listeners``, and for each one
    start a task running ``handler(stream)``.

    .. warning::

       If ``handler`` raises an exception, then this function doesn't do
       anything special to catch it – so by default the exception will
       propagate out and crash your server. If you don't want this, then catch
       exceptions inside your ``handler``, or use a ``handler_nursery`` object
       that responds to exceptions in some other way.

    Args:

      handler: An async callable, that will be invoked like
          ``handler_nursery.start_soon(handler, stream)`` for each incoming
          connection.

      listeners: A list of :class:`~trio.abc.Listener` objects.
          :func:`serve_listeners` takes responsibility for closing them.

      handler_nursery: The nursery used to start handlers, or any object with
          a ``start_soon`` method. If ``None`` (the default), then
          :func:`serve_listeners` will create a new nursery internally and use
          that.

      task_status: This function can be used with ``nursery.start``, which
          will return ``listeners``.

    Returns:

      This function never returns unless cancelled.

    Resource handling:

      If ``handler`` neglects to close the ``stream``, then it will be closed
      using :func:`trio.aclose_forcefully`.

    Error handling:

      Most errors coming from :meth:`~trio.abc.Listener.accept` are allowed to
      propagate out (crashing the server in the process). However, some errors –
      those which indicate that the server is temporarily overloaded – are
      handled specially. These are :class:`OSError`\s with one of the following
      errnos:

      * ``EMFILE``: process is out of file descriptors
      * ``ENFILE``: system is out of file descriptors
      * ``ENOBUFS``, ``ENOMEM``: the kernel hit some sort of memory limitation
        when trying to create a socket object

      When :func:`serve_listeners` gets one of these errors, then it:

      * Logs the error to the standard library logger ``trio.serve_listeners``
        (level = ERROR, with exception information included). By default this
        causes it to be printed to stderr.
      * Waits 100 ms before calling ``accept`` again, in hopes that the
        system will recover.
trio.serve_ssl_over_tcp
Python Library Documentation: function serve_ssl_over_tcp in module trio

async serve_ssl_over_tcp(handler: 'Callable[[trio.SSLStream[SocketStream]], Awaitable[object]]', port: 'int', ssl_context: 'ssl.SSLContext', *, host: 'str | bytes | None' = None, https_compatible: 'bool' = False, backlog: 'int | None' = None, handler_nursery: 'trio.Nursery | None' = None, task_status: 'trio.TaskStatus[list[trio.SSLListener[SocketStream]]]' = TASK_STATUS_IGNORED) -> 'NoReturn'
    Listen for incoming TCP connections, and for each one start a task
    running ``handler(stream)``.

    This is a thin convenience wrapper around
    :func:`open_ssl_over_tcp_listeners` and :func:`serve_listeners` – see them
    for full details.

    .. warning::

       If ``handler`` raises an exception, then this function doesn't do
       anything special to catch it – so by default the exception will
       propagate out and crash your server. If you don't want this, then catch
       exceptions inside your ``handler``, or use a ``handler_nursery`` object
       that responds to exceptions in some other way.

    When used with ``nursery.start`` you get back the newly opened listeners.
    See the documentation for :func:`serve_tcp` for an example where this is
    useful.

    Args:
      handler: The handler to start for each incoming connection. Passed to
          :func:`serve_listeners`.

      port (int): The port to listen on. Use 0 to let the kernel pick
          an open port. Ultimately passed to :func:`open_tcp_listeners`.

      ssl_context (~ssl.SSLContext): The SSL context to use for all incoming
          connections. Passed to :func:`open_ssl_over_tcp_listeners`.

      host (str, bytes, or None): The address to bind to; use ``None`` to bind
          to the wildcard address. Ultimately passed to
          :func:`open_tcp_listeners`.

      https_compatible (bool): Set this to True if you want to use
          "HTTPS-style" TLS. See :class:`~trio.SSLStream` for details.

      backlog (int or None): See :class:`~trio.SSLStream` for details.

      handler_nursery: The nursery to start handlers in, or None to use an
          internal nursery. Passed to :func:`serve_listeners`.

      task_status: This function can be used with ``nursery.start``.

    Returns:
      This function only returns when cancelled.
trio.serve_tcp
Python Library Documentation: function serve_tcp in module trio

async serve_tcp(handler: 'Callable[[trio.SocketStream], Awaitable[object]]', port: 'int', *, host: 'str | bytes | None' = None, backlog: 'int | None' = None, handler_nursery: 'trio.Nursery | None' = None, task_status: 'TaskStatus[list[trio.SocketListener]]' = TASK_STATUS_IGNORED) -> 'None'
    Listen for incoming TCP connections, and for each one start a task
    running ``handler(stream)``.

    This is a thin convenience wrapper around :func:`open_tcp_listeners` and
    :func:`serve_listeners` – see them for full details.

    .. warning::

       If ``handler`` raises an exception, then this function doesn't do
       anything special to catch it – so by default the exception will
       propagate out and crash your server. If you don't want this, then catch
       exceptions inside your ``handler``, or use a ``handler_nursery`` object
       that responds to exceptions in some other way.

    When used with ``nursery.start`` you get back the newly opened listeners.
    So, for example, if you want to start a server in your test suite and then
    connect to it to check that it's working properly, you can use something
    like::

        from trio import SocketListener, SocketStream
        from trio.testing import open_stream_to_socket_listener

        async with trio.open_nursery() as nursery:
            listeners: list[SocketListener] = await nursery.start(serve_tcp, handler, 0)
            client_stream: SocketStream = await open_stream_to_socket_listener(listeners[0])

            # Then send and receive data on 'client_stream', for example:
            await client_stream.send_all(b"GET / HTTP/1.0\r\n\r\n")

    This avoids several common pitfalls:

    1. It lets the kernel pick a random open port, so your test suite doesn't
       depend on any particular port being open.

    2. It waits for the server to be accepting connections on that port before
       ``start`` returns, so there's no race condition where the incoming
       connection arrives before the server is ready.

    3. It uses the Listener object to find out which port was picked, so it
       can connect to the right place.

    Args:
      handler: The handler to start for each incoming connection. Passed to
          :func:`serve_listeners`.

      port: The port to listen on. Use 0 to let the kernel pick an open port.
          Passed to :func:`open_tcp_listeners`.

      host (str, bytes, or None): The host interface to listen on; use
          ``None`` to bind to the wildcard address. Passed to
          :func:`open_tcp_listeners`.

      backlog: The listen backlog, or None to have a good default picked.
          Passed to :func:`open_tcp_listeners`.

      handler_nursery: The nursery to start handlers in, or None to use an
          internal nursery. Passed to :func:`serve_listeners`.

      task_status: This function can be used with ``nursery.start``.

    Returns:
      This function only returns when cancelled.
trio.sleep
Python Library Documentation: function sleep in module trio

async sleep(seconds: 'float') -> 'None'
    Pause execution of the current task for the given number of seconds.

    Args:
        seconds (float): The number of seconds to sleep. May be zero to
            insert a checkpoint without actually blocking.

    Raises:
        ValueError: if *seconds* is negative or NaN.
trio.sleep_forever
Python Library Documentation: function sleep_forever in module trio

async sleep_forever() -> 'NoReturn'
    Pause execution of the current task forever (or until cancelled).

    Equivalent to calling ``await sleep(math.inf)``, except that if manually
    rescheduled this will raise a `RuntimeError`.

    Raises:
      RuntimeError: if rescheduled
trio.sleep_until
Python Library Documentation: function sleep_until in module trio

async sleep_until(deadline: 'float') -> 'None'
    Pause execution of the current task until the given time.

    The difference between :func:`sleep` and :func:`sleep_until` is that the
    former takes a relative time and the latter takes an absolute time
    according to Trio's internal clock (as returned by :func:`current_time`).

    Args:
        deadline (float): The time at which we should wake up again. May be in
            the past, in which case this function executes a checkpoint but
            does not block.

    Raises:
      ValueError: if deadline is NaN.
trio.wrap_file
Python Library Documentation: function wrap_file in module trio

wrap_file(file: 'FileT') -> 'AsyncIOWrapper[FileT]'
    This wraps any file object in a wrapper that provides an asynchronous
    file object interface.

    Args:
        file: a :term:`file object`

    Returns:
        An :term:`asynchronous file object` that wraps ``file``

    Example::

        async_file = trio.wrap_file(StringIO('asdf'))

        assert await async_file.read() == 'asdf'
trio.lowlevel.Abort
Python Library Documentation: class Abort in module trio.lowlevel

class Abort(enum.Enum)
 |  Abort(*values)
 |
 |  :class:`enum.Enum` used as the return value from abort functions.
 |
 |  See :func:`wait_task_rescheduled` for details.
 |
 |  .. data:: SUCCEEDED
 |            FAILED
 |
 |  Method resolution order:
 |      Abort
 |      enum.Enum
 |      builtins.object
 |
 |  Data and other attributes defined here:
 |
 |  FAILED = <Abort.FAILED: 2>
 |
 |  SUCCEEDED = <Abort.SUCCEEDED: 1>
 |
 |  ----------------------------------------------------------------------
 |  Data descriptors inherited from enum.Enum:
 |
 |  name
 |      The name of the Enum member.
 |
 |  value
 |      The value of the Enum member.
 |
 |  ----------------------------------------------------------------------
 |  Static methods inherited from enum.EnumType:
 |
 |  __contains__(value)
 |      Return True if `value` is in `cls`.
 |
 |      `value` is in `cls` if:
 |      1) `value` is a member of `cls`, or
 |      2) `value` is the value of one of the `cls`'s members.
 |
 |  __getitem__(name)
 |      Return the member matching `name`.
 |
 |  __iter__()
 |      Return members in definition order.
 |
 |  __len__()
 |      Return the number of members (no aliases)
 |
 |  ----------------------------------------------------------------------
 |  Readonly properties inherited from enum.EnumType:
 |
 |  __members__
 |      Returns a mapping of member name->value.
 |
 |      This mapping lists all enum members, including aliases. Note that this
 |      is a read-only view of the internal mapping.
trio.lowlevel.ParkingLot
Python Library Documentation: class ParkingLot in module trio.lowlevel

class ParkingLot(builtins.object)
 |  ParkingLot() -> None
 |
 |  A fair wait queue with cancellation and requeuing.
 |
 |  This class encapsulates the tricky parts of implementing a wait
 |  queue. It's useful for implementing higher-level synchronization
 |  primitives like queues and locks.
 |
 |  In addition to the methods below, you can use ``len(parking_lot)`` to get
 |  the number of parked tasks, and ``if parking_lot: ...`` to check whether
 |  there are any parked tasks.
 |
 |  Methods defined here:
 |
 |  __bool__(self) -> 'bool'
 |      True if there are parked tasks, False otherwise.
 |
 |  __getstate__ = slots_getstate(self) from attr._make._ClassBuilder._make_getstate_setstate.<locals>
 |      Automatically created by attrs.
 |
 |  __init__(self) -> None
 |      Method generated by attrs for class ParkingLot.
 |
 |  __len__(self) -> 'int'
 |      Returns the number of parked tasks.
 |
 |  __repr__(self)
 |      Method generated by attrs for class ParkingLot.
 |
 |  __setstate__ = slots_setstate(self, state) from attr._make._ClassBuilder._make_getstate_setstate.<locals>
 |      Automatically created by attrs.
 |
 |  break_lot(self, task: 'Task | None' = None) -> 'None'
 |      Break this lot, with ``task`` noted as the task that broke it.
 |
 |      This causes all parked tasks to raise an error, and any
 |      future tasks attempting to park to error. Unpark & repark become no-ops as the
 |      parking lot is empty.
 |
 |      The error raised contains a reference to the task sent as a parameter. The task
 |      is also saved in the parking lot in the ``broken_by`` attribute.
 |
 |  async park(self) -> 'None'
 |      Park the current task until woken by a call to :meth:`unpark` or
 |      :meth:`unpark_all`.
 |
 |      Raises:
 |        BrokenResourceError: if attempting to park in a broken lot, or the lot
 |          breaks before we get to unpark.
 |
 |  repark(self, new_lot: 'ParkingLot', *, count: 'int | float' = 1) -> 'None'
 |      Move parked tasks from one :class:`ParkingLot` object to another.
 |
 |      This dequeues ``count`` tasks from one lot, and requeues them on
 |      another, preserving order. For example::
 |
 |         async def parker(lot):
 |             print("sleeping")
 |             await lot.park()
 |             print("woken")
 |
 |         async def main():
 |             lot1 = trio.lowlevel.ParkingLot()
 |             lot2 = trio.lowlevel.ParkingLot()
 |             async with trio.open_nursery() as nursery:
 |                 nursery.start_soon(parker, lot1)
 |                 await trio.testing.wait_all_tasks_blocked()
 |                 assert len(lot1) == 1
 |                 assert len(lot2) == 0
 |                 lot1.repark(lot2)
 |                 assert len(lot1) == 0
 |                 assert len(lot2) == 1
 |                 # This wakes up the task that was originally parked in lot1
 |                 lot2.unpark()
 |
 |      If there are fewer than ``count`` tasks parked, then reparks as many
 |      tasks as are available and then returns successfully.
 |
 |      Args:
 |        new_lot (ParkingLot): the parking lot to move tasks to.
 |        count (int|math.inf): the number of tasks to move.
 |
 |  repark_all(self, new_lot: 'ParkingLot') -> 'None'
 |      Move all parked tasks from one :class:`ParkingLot` object to
 |      another.
 |
 |      See :meth:`repark` for details.
 |
 |  statistics(self) -> 'ParkingLotStatistics'
 |      Return an object containing debugging information.
 |
 |      Currently the following fields are defined:
 |
 |      * ``tasks_waiting``: The number of tasks blocked on this lot's
 |        :meth:`park` method.
 |
 |  unpark(self, *, count: 'int | float' = 1) -> 'list[Task]'
 |      Unpark one or more tasks.
 |
 |      This wakes up ``count`` tasks that are blocked in :meth:`park`. If
 |      there are fewer than ``count`` tasks parked, then wakes as many tasks
 |      are available and then returns successfully.
 |
 |      Args:
 |        count (int | math.inf): the number of tasks to unpark.
 |
 |  unpark_all(self) -> 'list[Task]'
 |      Unpark all parked tasks.
 |
 |  ----------------------------------------------------------------------
 |  Class methods defined here:
 |
 |  __init_subclass__ = _init_final_cls() -> 'NoReturn' from trio._util
 |      Raises an exception when a final class is subclassed.
 |
 |  ----------------------------------------------------------------------
 |  Data descriptors defined here:
 |
 |  __weakref__
 |      list of weak references to the object
 |
 |  broken_by
 |
 |  ----------------------------------------------------------------------
 |  Data and other attributes defined here:
 |
 |  __annotations__ = {'_parked': 'OrderedDict[Task, None]', 'broken_by': ...
 |
 |  __attrs_attrs__ = (Attribute(name='_parked', default=Factory(facto...r...
 |
 |  __attrs_own_setattr__ = False
 |
 |  __final__ = True
 |
 |  __match_args__ = ()
trio.lowlevel.ParkingLotStatistics
Python Library Documentation: class ParkingLotStatistics in module trio.lowlevel

class ParkingLotStatistics(builtins.object)
 |  ParkingLotStatistics(tasks_waiting: 'int') -> None
 |
 |  An object containing debugging information for a ParkingLot.
 |
 |  Currently, the following fields are defined:
 |
 |  * ``tasks_waiting`` (int): The number of tasks blocked on this lot's
 |    :meth:`trio.lowlevel.ParkingLot.park` method.
 |
 |  Methods defined here:
 |
 |  __delattr__ = _frozen_delattrs(self, name) from attr._make
 |      Attached to frozen classes as __delattr__.
 |
 |  __eq__(self, other)
 |      Method generated by attrs for class ParkingLotStatistics.
 |
 |  __getstate__ = slots_getstate(self) from attr._make._ClassBuilder._make_getstate_setstate.<locals>
 |      Automatically created by attrs.
 |
 |  __hash__(self)
 |      Method generated by attrs for class ParkingLotStatistics.
 |
 |  __init__(self, tasks_waiting: 'int') -> None
 |      Method generated by attrs for class ParkingLotStatistics.
 |
 |  __ne__(self, other)
 |      Method generated by attrs for class ParkingLotStatistics.
 |
 |  __repr__(self)
 |      Method generated by attrs for class ParkingLotStatistics.
 |
 |  __setattr__ = _frozen_setattrs(self, name, value) from attr._make
 |      Attached to frozen classes as __setattr__.
 |
 |  __setstate__ = slots_setstate(self, state) from attr._make._ClassBuilder._make_getstate_setstate.<locals>
 |      Automatically created by attrs.
 |
 |  ----------------------------------------------------------------------
 |  Data descriptors defined here:
 |
 |  __weakref__
 |      list of weak references to the object
 |
 |  tasks_waiting
 |
 |  ----------------------------------------------------------------------
 |  Data and other attributes defined here:
 |
 |  __annotations__ = {'tasks_waiting': 'int'}
 |
 |  __attrs_attrs__ = (Attribute(name='tasks_waiting', default=NOTHING...=...
 |
 |  __match_args__ = ('tasks_waiting',)
trio.lowlevel.RaiseCancelT
Python Library Documentation: _CallableGenericAlias in module typing

class Callable(builtins.object)
 |  Methods defined here:
 |
 |  __call__(self, *args, **kwds)
 |      Call self as a function.
 |
 |  ----------------------------------------------------------------------
 |  Class methods defined here:
 |
 |  __class_getitem__ = _CallableGenericAlias(args)
 |      Represent `Callable[argtypes, resulttype]`.
 |
 |      This sets ``__args__`` to a tuple containing the flattened ``argtypes``
 |      followed by ``resulttype``.
 |
 |      Example: ``Callable[[int, str], float]`` sets ``__args__`` to
 |      ``(int, str, float)``.
 |
 |  __subclasshook__(C)
 |      Abstract classes can override this to customize issubclass().
 |
 |      This is invoked early on by abc.ABCMeta.__subclasscheck__().
 |      It should return True, False or NotImplemented.  If it returns
 |      NotImplemented, the normal algorithm is used.  Otherwise, it
 |      overrides the normal algorithm (and the outcome is cached).
 |
 |  ----------------------------------------------------------------------
 |  Data and other attributes defined here:
 |
 |  __abstractmethods__ = frozenset({'__call__'})
trio.lowlevel.RunStatistics
Python Library Documentation: class RunStatistics in module trio.lowlevel

class RunStatistics(builtins.object)
 |  RunStatistics(tasks_living: 'int', tasks_runnable: 'int', seconds_to_next_deadline: 'float', io_statistics: 'IOStatistics', run_sync_soon_queue_size: 'int') -> None
 |
 |  An object containing run-loop-level debugging information.
 |
 |  Currently, the following fields are defined:
 |
 |  * ``tasks_living`` (int): The number of tasks that have been spawned
 |    and not yet exited.
 |  * ``tasks_runnable`` (int): The number of tasks that are currently
 |    queued on the run queue (as opposed to blocked waiting for something
 |    to happen).
 |  * ``seconds_to_next_deadline`` (float): The time until the next
 |    pending cancel scope deadline. May be negative if the deadline has
 |    expired but we haven't yet processed cancellations. May be
 |    :data:`~math.inf` if there are no pending deadlines.
 |  * ``run_sync_soon_queue_size`` (int): The number of
 |    unprocessed callbacks queued via
 |    :meth:`trio.lowlevel.TrioToken.run_sync_soon`.
 |  * ``io_statistics`` (object): Some statistics from Trio's I/O
 |    backend. This always has an attribute ``backend`` which is a string
 |    naming which operating-system-specific I/O backend is in use; the
 |    other attributes vary between backends.
 |
 |  Methods defined here:
 |
 |  __delattr__ = _frozen_delattrs(self, name) from attr._make
 |      Attached to frozen classes as __delattr__.
 |
 |  __eq__(self, other)
 |      Method generated by attrs for class RunStatistics.
 |
 |  __getstate__ = slots_getstate(self) from attr._make._ClassBuilder._make_getstate_setstate.<locals>
 |      Automatically created by attrs.
 |
 |  __hash__(self)
 |      Method generated by attrs for class RunStatistics.
 |
 |  __init__(self, tasks_living: 'int', tasks_runnable: 'int', seconds_to_next_deadline: 'float', io_statistics: 'IOStatistics', run_sync_soon_queue_size: 'int') -> None
 |      Method generated by attrs for class RunStatistics.
 |
 |  __ne__(self, other)
 |      Method generated by attrs for class RunStatistics.
 |
 |  __repr__(self)
 |      Method generated by attrs for class RunStatistics.
 |
 |  __setattr__ = _frozen_setattrs(self, name, value) from attr._make
 |      Attached to frozen classes as __setattr__.
 |
 |  __setstate__ = slots_setstate(self, state) from attr._make._ClassBuilder._make_getstate_setstate.<locals>
 |      Automatically created by attrs.
 |
 |  ----------------------------------------------------------------------
 |  Data descriptors defined here:
 |
 |  __weakref__
 |      list of weak references to the object
 |
 |  io_statistics
 |
 |  run_sync_soon_queue_size
 |
 |  seconds_to_next_deadline
 |
 |  tasks_living
 |
 |  tasks_runnable
 |
 |  ----------------------------------------------------------------------
 |  Data and other attributes defined here:
 |
 |  __annotations__ = {'io_statistics': 'IOStatistics', 'run_sync_soon_que...
 |
 |  __attrs_attrs__ = (Attribute(name='tasks_living', default=NOTHING,..._...
 |
 |  __match_args__ = ('tasks_living', 'tasks_runnable', 'seconds_to_next_d...
trio.lowlevel.RunVar
Python Library Documentation: class RunVar in module trio.lowlevel

class RunVar(typing.Generic)
 |  RunVar(name: 'str', default: 'T | type[_NoValue]' = <class 'trio._core._local._NoValue'>) -> None
 |
 |  The run-local variant of a context variable.
 |
 |  :class:`RunVar` objects are similar to context variable objects,
 |  except that they are shared across a single call to :func:`trio.run`
 |  rather than a single task.
 |
 |  Method resolution order:
 |      RunVar
 |      typing.Generic
 |      builtins.object
 |
 |  Methods defined here:
 |
 |  __getstate__ = slots_getstate(self) from attr._make._ClassBuilder._make_getstate_setstate.<locals>
 |      Automatically created by attrs.
 |
 |  __init__(self, name: 'str', default: 'T | type[_NoValue]' = <class 'trio._core._local._NoValue'>) -> None
 |      Method generated by attrs for class RunVar.
 |
 |  __repr__(self) -> 'str'
 |      Return repr(self).
 |
 |  __setstate__ = slots_setstate(self, state) from attr._make._ClassBuilder._make_getstate_setstate.<locals>
 |      Automatically created by attrs.
 |
 |  get(self, default: 'T | type[_NoValue]' = <class 'trio._core._local._NoValue'>) -> 'T'
 |      Gets the value of this :class:`RunVar` for the current run call.
 |
 |  reset(self, token: 'RunVarToken[T]') -> 'None'
 |      Resets the value of this :class:`RunVar` to what it was
 |      previously specified by the token.
 |
 |  set(self, value: 'T') -> 'RunVarToken[T]'
 |      Sets the value of this :class:`RunVar` for this current run
 |      call.
 |
 |  ----------------------------------------------------------------------
 |  Class methods defined here:
 |
 |  __init_subclass__ = _init_final_cls() -> 'NoReturn' from trio._util
 |      Raises an exception when a final class is subclassed.
 |
 |  ----------------------------------------------------------------------
 |  Data descriptors defined here:
 |
 |  __weakref__
 |      list of weak references to the object
 |
 |  ----------------------------------------------------------------------
 |  Data and other attributes defined here:
 |
 |  __annotations__ = {'_default': 'T | type[_NoValue]', '_name': 'str'}
 |
 |  __attrs_attrs__ = (Attribute(name='_name', default=NOTHING, valida...h...
 |
 |  __attrs_own_setattr__ = False
 |
 |  __final__ = True
 |
 |  __match_args__ = ('_name', '_default')
 |
 |  __orig_bases__ = (typing.Generic[~T],)
 |
 |  __parameters__ = (~T,)
 |
 |  ----------------------------------------------------------------------
 |  Class methods inherited from typing.Generic:
 |
 |  __class_getitem__(...)
 |      Parameterizes a generic class.
 |
 |      At least, parameterizing a generic class is the *main* thing this
 |      method does. For example, for some generic class `Foo`, this is called
 |      when we do `Foo[int]` - there, with `cls=Foo` and `params=int`.
 |
 |      However, note that this method is also called when defining generic
 |      classes in the first place with `class Foo[T]: ...`.
trio.lowlevel.RunVarToken
Python Library Documentation: class RunVarToken in module trio.lowlevel

class RunVarToken(typing.Generic)
 |  RunVarToken(*args: 'object', **kwargs: 'object') -> 'None'
 |
 |  Method resolution order:
 |      RunVarToken
 |      typing.Generic
 |      builtins.object
 |
 |  Methods defined here:
 |
 |  __getstate__ = slots_getstate(self) from attr._make._ClassBuilder._make_getstate_setstate.<locals>
 |      Automatically created by attrs.
 |
 |  __init__(self, var: 'RunVar[T]', previous_value: 'T | type[_NoValue]' = <class 'trio._core._local._NoValue'>) -> None
 |      Method generated by attrs for class RunVarToken.
 |
 |  __repr__(self)
 |      Method generated by attrs for class RunVarToken.
 |
 |  __setstate__ = slots_setstate(self, state) from attr._make._ClassBuilder._make_getstate_setstate.<locals>
 |      Automatically created by attrs.
 |
 |  ----------------------------------------------------------------------
 |  Class methods defined here:
 |
 |  __init_subclass__ = _init_final_cls() -> 'NoReturn' from trio._util
 |      Raises an exception when a final class is subclassed.
 |
 |  ----------------------------------------------------------------------
 |  Data descriptors defined here:
 |
 |  __weakref__
 |      list of weak references to the object
 |
 |  previous_value
 |
 |  redeemed
 |
 |  ----------------------------------------------------------------------
 |  Data and other attributes defined here:
 |
 |  __abstractmethods__ = frozenset()
 |
 |  __annotations__ = {'_var': 'RunVar[T]', 'previous_value': 'T | type[_N...
 |
 |  __attrs_attrs__ = (Attribute(name='_var', default=NOTHING, validat...e...
 |
 |  __attrs_own_setattr__ = False
 |
 |  __final__ = True
 |
 |  __match_args__ = ('_var', 'previous_value')
 |
 |  __orig_bases__ = (typing.Generic[~T],)
 |
 |  __parameters__ = (~T,)
 |
 |  ----------------------------------------------------------------------
 |  Class methods inherited from typing.Generic:
 |
 |  __class_getitem__(...)
 |      Parameterizes a generic class.
 |
 |      At least, parameterizing a generic class is the *main* thing this
 |      method does. For example, for some generic class `Foo`, this is called
 |      when we do `Foo[int]` - there, with `cls=Foo` and `params=int`.
 |
 |      However, note that this method is also called when defining generic
 |      classes in the first place with `class Foo[T]: ...`.
trio.lowlevel.Task
Python Library Documentation: class Task in module trio.lowlevel

class Task(builtins.object)
 |  Task(*args: 'object', **kwargs: 'object') -> 'None'
 |
 |  Methods defined here:
 |
 |  __getstate__ = slots_getstate(self) from attr._make._ClassBuilder._make_getstate_setstate.<locals>
 |      Automatically created by attrs.
 |
 |  __init__(self, parent_nursery: 'Nursery | None', coro: 'types.CoroutineType[Any, Outcome[object], Any]', runner: 'Runner', name: 'str', context: 'contextvars.Context', ki_protected: 'bool', next_send_fn: 'Callable[[Any], object] | None' = None, next_send: 'Outcome[Any] | BaseException | None' = None, abort_func: 'Callable[[_core.RaiseCancelT], Abort] | None' = None, custom_sleep_data: 'Any' = None, child_nurseries: 'list[Nursery]' = NOTHING, eventual_parent_nursery: 'Nursery | None' = None, cancel_points: 'int' = 0, schedule_points: 'int' = 0, cancel_status: 'CancelStatus' = None) -> None
 |      Method generated by attrs for class Task.
 |
 |  __repr__(self) -> 'str'
 |      Return repr(self).
 |
 |  __setstate__ = slots_setstate(self, state) from attr._make._ClassBuilder._make_getstate_setstate.<locals>
 |      Automatically created by attrs.
 |
 |  iter_await_frames(self) -> 'Iterator[tuple[types.FrameType, int]]'
 |      Iterates recursively over the coroutine-like objects this
 |      task is waiting on, yielding the frame and line number at each
 |      frame.
 |
 |      This is similar to `traceback.walk_stack` in a synchronous
 |      context. Note that `traceback.walk_stack` returns frames from
 |      the bottom of the call stack to the top, while this function
 |      starts from `Task.coro <trio.lowlevel.Task.coro>` and works it
 |      way down.
 |
 |      Example usage: extracting a stack trace::
 |
 |          import traceback
 |
 |          def print_stack_for_task(task):
 |              ss = traceback.StackSummary.extract(task.iter_await_frames())
 |              print("".join(ss.format()))
 |
 |  ----------------------------------------------------------------------
 |  Class methods defined here:
 |
 |  __init_subclass__ = _init_final_cls() -> 'NoReturn' from trio._util
 |      Raises an exception when a final class is subclassed.
 |
 |  ----------------------------------------------------------------------
 |  Readonly properties defined here:
 |
 |  child_nurseries
 |      The nurseries this task contains.
 |
 |      This is a list, with outer nurseries before inner nurseries.
 |
 |  eventual_parent_nursery
 |      The nursery this task will be inside after it calls
 |      ``task_status.started()``.
 |
 |      If this task has already called ``started()``, or if it was not
 |      spawned using `nursery.start() <trio.Nursery.start>`, then
 |      its `eventual_parent_nursery` is ``None``.
 |
 |  parent_nursery
 |      The nursery this task is inside (or None if this is the "init"
 |      task).
 |
 |      Example use case: drawing a visualization of the task tree in a
 |      debugger.
 |
 |  ----------------------------------------------------------------------
 |  Data descriptors defined here:
 |
 |  __weakref__
 |      list of weak references to the object
 |
 |  context
 |
 |  coro
 |
 |  custom_sleep_data
 |
 |  name
 |
 |  ----------------------------------------------------------------------
 |  Data and other attributes defined here:
 |
 |  __abstractmethods__ = frozenset()
 |
 |  __annotations__ = {'_abort_func': 'Callable[[_core.RaiseCancelT], Abor...
 |
 |  __attrs_attrs__ = (Attribute(name='_parent_nursery', default=NOTHI...d...
 |
 |  __attrs_own_setattr__ = False
 |
 |  __final__ = True
 |
 |  __match_args__ = ('_parent_nursery', 'coro', '_runner', 'name', 'conte...
trio.lowlevel.TrioToken
Python Library Documentation: class TrioToken in module trio.lowlevel

class TrioToken(builtins.object)
 |  TrioToken(*args: 'object', **kwargs: 'object') -> 'None'
 |
 |  An opaque object representing a single call to :func:`trio.run`.
 |
 |  It has no public constructor; instead, see :func:`current_trio_token`.
 |
 |  This object has two uses:
 |
 |  1. It lets you re-enter the Trio run loop from external threads or signal
 |     handlers. This is the low-level primitive that :func:`trio.to_thread`
 |     and `trio.from_thread` use to communicate with worker threads, that
 |     `trio.open_signal_receiver` uses to receive notifications about
 |     signals, and so forth.
 |
 |  2. Each call to :func:`trio.run` has exactly one associated
 |     :class:`TrioToken` object, so you can use it to identify a particular
 |     call.
 |
 |  Methods defined here:
 |
 |  __getstate__ = slots_getstate(self) from attr._make._ClassBuilder._make_getstate_setstate.<locals>
 |      Automatically created by attrs.
 |
 |  __init__(self, reentry_queue: 'EntryQueue') -> None
 |      Method generated by attrs for class TrioToken.
 |
 |  __repr__(self)
 |      Method generated by attrs for class TrioToken.
 |
 |  __setstate__ = slots_setstate(self, state) from attr._make._ClassBuilder._make_getstate_setstate.<locals>
 |      Automatically created by attrs.
 |
 |  run_sync_soon(self, sync_fn: 'Callable[[Unpack[PosArgsT]], object]', *args: 'Unpack[PosArgsT]', idempotent: 'bool' = False) -> 'None'
 |      Schedule a call to ``sync_fn(*args)`` to occur in the context of a
 |      Trio task.
 |
 |      This is safe to call from the main thread, from other threads, and
 |      from signal handlers. This is the fundamental primitive used to
 |      re-enter the Trio run loop from outside of it.
 |
 |      The call will happen "soon", but there's no guarantee about exactly
 |      when, and no mechanism provided for finding out when it's happened.
 |      If you need this, you'll have to build your own.
 |
 |      The call is effectively run as part of a system task (see
 |      :func:`~trio.lowlevel.spawn_system_task`). In particular this means
 |      that:
 |
 |      * :exc:`KeyboardInterrupt` protection is *enabled* by default; if
 |        you want ``sync_fn`` to be interruptible by control-C, then you
 |        need to use :func:`~trio.lowlevel.disable_ki_protection`
 |        explicitly.
 |
 |      * If ``sync_fn`` raises an exception, then it's converted into a
 |        :exc:`~trio.TrioInternalError` and *all* tasks are cancelled. You
 |        should be careful that ``sync_fn`` doesn't crash.
 |
 |      All calls with ``idempotent=False`` are processed in strict
 |      first-in first-out order.
 |
 |      If ``idempotent=True``, then ``sync_fn`` and ``args`` must be
 |      hashable, and Trio will make a best-effort attempt to discard any
 |      call submission which is equal to an already-pending call. Trio
 |      will process these in first-in first-out order.
 |
 |      Any ordering guarantees apply separately to ``idempotent=False``
 |      and ``idempotent=True`` calls; there's no rule for how calls in the
 |      different categories are ordered with respect to each other.
 |
 |      :raises trio.RunFinishedError:
 |            if the associated call to :func:`trio.run`
 |            has already exited. (Any call that *doesn't* raise this error
 |            is guaranteed to be fully processed before :func:`trio.run`
 |            exits.)
 |
 |  ----------------------------------------------------------------------
 |  Class methods defined here:
 |
 |  __init_subclass__ = _init_final_cls() -> 'NoReturn' from trio._util
 |      Raises an exception when a final class is subclassed.
 |
 |  ----------------------------------------------------------------------
 |  Data descriptors defined here:
 |
 |  __weakref__
 |      list of weak references to the object
 |
 |  ----------------------------------------------------------------------
 |  Data and other attributes defined here:
 |
 |  __abstractmethods__ = frozenset()
 |
 |  __annotations__ = {'_reentry_queue': 'EntryQueue'}
 |
 |  __attrs_attrs__ = (Attribute(name='_reentry_queue', default=NOTHIN...=...
 |
 |  __attrs_own_setattr__ = False
 |
 |  __final__ = True
 |
 |  __match_args__ = ('_reentry_queue',)
trio.lowlevel.UnboundedQueue
Python Library Documentation: class UnboundedQueue in module trio.lowlevel

class UnboundedQueue(typing.Generic)
 |  UnboundedQueue() -> 'None'
 |
 |  An unbounded queue suitable for certain unusual forms of inter-task
 |  communication.
 |
 |  This class is designed for use as a queue in cases where the producer for
 |  some reason cannot be subjected to back-pressure, i.e., :meth:`put_nowait`
 |  has to always succeed. In order to prevent the queue backlog from actually
 |  growing without bound, the consumer API is modified to dequeue items in
 |  "batches". If a consumer task processes each batch without yielding, then
 |  this helps achieve (but does not guarantee) an effective bound on the
 |  queue's memory use, at the cost of potentially increasing system latencies
 |  in general. You should generally prefer to use a memory channel
 |  instead if you can.
 |
 |  Currently each batch completely empties the queue, but `this may change in
 |  the future <https://github.com/python-trio/trio/issues/51>`__.
 |
 |  A :class:`UnboundedQueue` object can be used as an asynchronous iterator,
 |  where each iteration returns a new batch of items. I.e., these two loops
 |  are equivalent::
 |
 |     async for batch in queue:
 |         ...
 |
 |     while True:
 |         obj = await queue.get_batch()
 |         ...
 |
 |  Method resolution order:
 |      UnboundedQueue
 |      typing.Generic
 |      builtins.object
 |
 |  Methods defined here:
 |
 |  __aiter__(self) -> 'Self'
 |
 |  async __anext__(self) -> 'list[T]'
 |
 |  __init__(self) -> 'None'
 |      Initialize self.  See help(type(self)) for accurate signature.
 |
 |  __repr__(self) -> 'str'
 |      Return repr(self).
 |
 |  empty(self) -> 'bool'
 |      Returns True if the queue is empty, False otherwise.
 |
 |      There is some subtlety to interpreting this method's return value: see
 |      `issue #63 <https://github.com/python-trio/trio/issues/63>`__.
 |
 |  async get_batch(self) -> 'list[T]'
 |      Get the next batch from the queue, blocking as necessary.
 |
 |      Returns:
 |        list: A list of dequeued items, in order. This list is always
 |            non-empty.
 |
 |  get_batch_nowait(self) -> 'list[T]'
 |      Attempt to get the next batch from the queue, without blocking.
 |
 |      Returns:
 |        list: A list of dequeued items, in order. On a successful call this
 |            list is always non-empty; if it would be empty we raise
 |            :exc:`~trio.WouldBlock` instead.
 |
 |      Raises:
 |        ~trio.WouldBlock: if the queue is empty.
 |
 |  put_nowait(self, obj: 'T') -> 'None'
 |      Put an object into the queue, without blocking.
 |
 |      This always succeeds, because the queue is unbounded. We don't provide
 |      a blocking ``put`` method, because it would never need to block.
 |
 |      Args:
 |        obj (object): The object to enqueue.
 |
 |  qsize(self) -> 'int'
 |      Returns the number of items currently in the queue.
 |
 |  statistics(self) -> 'UnboundedQueueStatistics'
 |      Return an :class:`UnboundedQueueStatistics` object containing debugging information.
 |
 |  ----------------------------------------------------------------------
 |  Class methods defined here:
 |
 |  __init_subclass__ = _init_final_cls() -> 'NoReturn' from trio._util
 |      Raises an exception when a final class is subclassed.
 |
 |  ----------------------------------------------------------------------
 |  Data descriptors defined here:
 |
 |  __dict__
 |      dictionary for instance variables
 |
 |  __weakref__
 |      list of weak references to the object
 |
 |  ----------------------------------------------------------------------
 |  Data and other attributes defined here:
 |
 |  __annotations__ = {}
 |
 |  __final__ = True
 |
 |  __orig_bases__ = (typing.Generic[~T],)
 |
 |  __parameters__ = (~T,)
 |
 |  ----------------------------------------------------------------------
 |  Class methods inherited from typing.Generic:
 |
 |  __class_getitem__(...)
 |      Parameterizes a generic class.
 |
 |      At least, parameterizing a generic class is the *main* thing this
 |      method does. For example, for some generic class `Foo`, this is called
 |      when we do `Foo[int]` - there, with `cls=Foo` and `params=int`.
 |
 |      However, note that this method is also called when defining generic
 |      classes in the first place with `class Foo[T]: ...`.
trio.lowlevel.UnboundedQueueStatistics
Python Library Documentation: class UnboundedQueueStatistics in module trio.lowlevel

class UnboundedQueueStatistics(builtins.object)
 |  UnboundedQueueStatistics(qsize: 'int', tasks_waiting: 'int') -> None
 |
 |  An object containing debugging information.
 |
 |  Currently, the following fields are defined:
 |
 |  * ``qsize``: The number of items currently in the queue.
 |  * ``tasks_waiting``: The number of tasks blocked on this queue's
 |    :meth:`get_batch` method.
 |
 |  Methods defined here:
 |
 |  __delattr__ = _frozen_delattrs(self, name) from attr._make
 |      Attached to frozen classes as __delattr__.
 |
 |  __eq__(self, other)
 |      Method generated by attrs for class UnboundedQueueStatistics.
 |
 |  __getstate__ = slots_getstate(self) from attr._make._ClassBuilder._make_getstate_setstate.<locals>
 |      Automatically created by attrs.
 |
 |  __hash__(self)
 |      Method generated by attrs for class UnboundedQueueStatistics.
 |
 |  __init__(self, qsize: 'int', tasks_waiting: 'int') -> None
 |      Method generated by attrs for class UnboundedQueueStatistics.
 |
 |  __ne__(self, other)
 |      Method generated by attrs for class UnboundedQueueStatistics.
 |
 |  __repr__(self)
 |      Method generated by attrs for class UnboundedQueueStatistics.
 |
 |  __setattr__ = _frozen_setattrs(self, name, value) from attr._make
 |      Attached to frozen classes as __setattr__.
 |
 |  __setstate__ = slots_setstate(self, state) from attr._make._ClassBuilder._make_getstate_setstate.<locals>
 |      Automatically created by attrs.
 |
 |  ----------------------------------------------------------------------
 |  Data descriptors defined here:
 |
 |  __weakref__
 |      list of weak references to the object
 |
 |  qsize
 |
 |  tasks_waiting
 |
 |  ----------------------------------------------------------------------
 |  Data and other attributes defined here:
 |
 |  __annotations__ = {'qsize': 'int', 'tasks_waiting': 'int'}
 |
 |  __attrs_attrs__ = (Attribute(name='qsize', default=NOTHING, valida...d...
 |
 |  __match_args__ = ('qsize', 'tasks_waiting')
trio.lowlevel.WaitForSingleObject
Python Library Documentation: function WaitForSingleObject in module trio.lowlevel

async WaitForSingleObject(obj: 'int | CData') -> 'None'
    Async and cancellable variant of WaitForSingleObject. Windows only.

    Args:
      handle: A Win32 handle, as a Python integer.

    Raises:
      OSError: If the handle is invalid, e.g. when it is already closed.
trio.lowlevel.add_instrument
Python Library Documentation: function add_instrument in module trio.lowlevel

add_instrument(instrument: 'Instrument') -> 'None'
    Start instrumenting the current run loop with the given instrument.

    Args:
      instrument (trio.abc.Instrument): The instrument to activate.

    If ``instrument`` is already active, does nothing.
trio.lowlevel.add_parking_lot_breaker
Python Library Documentation: function add_parking_lot_breaker in module trio.lowlevel

add_parking_lot_breaker(task: 'Task', lot: 'ParkingLot') -> 'None'
    Register a task as a breaker for a lot. See :meth:`ParkingLot.break_lot`.

    raises:
      trio.BrokenResourceError: if the task has already exited.
trio.lowlevel.cancel_shielded_checkpoint
Python Library Documentation: function cancel_shielded_checkpoint in module trio.lowlevel

async cancel_shielded_checkpoint() -> 'None'
    Introduce a schedule point, but not a cancel point.

    This is *not* a :ref:`checkpoint <checkpoints>`, but it is half of a
    checkpoint, and when combined with :func:`checkpoint_if_cancelled` it can
    make a full checkpoint.

    Equivalent to (but potentially more efficient than)::

        with trio.CancelScope(shield=True):
            await trio.lowlevel.checkpoint()
trio.lowlevel.checkpoint
Python Library Documentation: function checkpoint in module trio.lowlevel

async checkpoint() -> 'None'
    A pure :ref:`checkpoint <checkpoints>`.

    This checks for cancellation and allows other tasks to be scheduled,
    without otherwise blocking.

    Note that the scheduler has the option of ignoring this and continuing to
    run the current task if it decides this is appropriate (e.g. for increased
    efficiency).

    Equivalent to ``await trio.sleep(0)`` (which is implemented by calling
    :func:`checkpoint`.)
trio.lowlevel.checkpoint_if_cancelled
Python Library Documentation: function checkpoint_if_cancelled in module trio.lowlevel

async checkpoint_if_cancelled() -> 'None'
    Issue a :ref:`checkpoint <checkpoints>` if the calling context has been
    cancelled.

    Equivalent to (but potentially more efficient than)::

        if trio.current_effective_deadline() == -inf:
            await trio.lowlevel.checkpoint()

    This is either a no-op, or else it allow other tasks to be scheduled and
    then raises :exc:`trio.Cancelled`.

    Typically used together with :func:`cancel_shielded_checkpoint`.
trio.lowlevel.current_clock
Python Library Documentation: function current_clock in module trio.lowlevel

current_clock() -> 'Clock'
    Returns the current :class:`~trio.abc.Clock`.
trio.lowlevel.current_iocp
Python Library Documentation: function current_iocp in module trio.lowlevel

current_iocp() -> 'int'
    TODO: these are implemented, but are currently more of a sketch than
    anything real. See `#26
    <https://github.com/python-trio/trio/issues/26>`__ and `#52
    <https://github.com/python-trio/trio/issues/52>`__.
trio.lowlevel.current_root_task
Python Library Documentation: function current_root_task in module trio.lowlevel

current_root_task() -> 'Task | None'
    Returns the current root :class:`Task`.

    This is the task that is the ultimate parent of all other tasks.
trio.lowlevel.current_statistics
Python Library Documentation: function current_statistics in module trio.lowlevel

current_statistics() -> 'RunStatistics'
    Returns ``RunStatistics``, which contains run-loop-level debugging information.

    Currently, the following fields are defined:

    * ``tasks_living`` (int): The number of tasks that have been spawned
      and not yet exited.
    * ``tasks_runnable`` (int): The number of tasks that are currently
      queued on the run queue (as opposed to blocked waiting for something
      to happen).
    * ``seconds_to_next_deadline`` (float): The time until the next
      pending cancel scope deadline. May be negative if the deadline has
      expired but we haven't yet processed cancellations. May be
      :data:`~math.inf` if there are no pending deadlines.
    * ``run_sync_soon_queue_size`` (int): The number of
      unprocessed callbacks queued via
      :meth:`trio.lowlevel.TrioToken.run_sync_soon`.
    * ``io_statistics`` (object): Some statistics from Trio's I/O
      backend. This always has an attribute ``backend`` which is a string
      naming which operating-system-specific I/O backend is in use; the
      other attributes vary between backends.
trio.lowlevel.current_task
Python Library Documentation: function current_task in module trio.lowlevel

current_task() -> 'Task'
    Return the :class:`Task` object representing the current task.

    Returns:
      Task: the :class:`Task` that called :func:`current_task`.
trio.lowlevel.current_trio_token
Python Library Documentation: function current_trio_token in module trio.lowlevel

current_trio_token() -> 'TrioToken'
    Retrieve the :class:`TrioToken` for the current call to
    :func:`trio.run`.
trio.lowlevel.currently_ki_protected
Python Library Documentation: function currently_ki_protected in module trio.lowlevel

currently_ki_protected() -> 'bool'
    Check whether the calling code has :exc:`KeyboardInterrupt` protection
    enabled.

    It's surprisingly easy to think that one's :exc:`KeyboardInterrupt`
    protection is enabled when it isn't, or vice-versa. This function tells
    you what Trio thinks of the matter, which makes it useful for ``assert``\s
    and unit tests.

    Returns:
      bool: True if protection is enabled, and False otherwise.
trio.lowlevel.disable_ki_protection
Python Library Documentation: function disable_ki_protection in module trio.lowlevel

disable_ki_protection(f: '_T_supports_code', /) -> '_T_supports_code'
    Decorator to disable KI protection.
trio.lowlevel.enable_ki_protection
Python Library Documentation: function enable_ki_protection in module trio.lowlevel

enable_ki_protection(f: '_T_supports_code', /) -> '_T_supports_code'
    Decorator to enable KI protection.
trio.lowlevel.in_trio_run
Python Library Documentation: function in_trio_run in module trio.lowlevel

in_trio_run() -> 'bool'
    Check whether we are in a Trio run.
    This returns `True` if and only if :func:`~trio.current_time` will succeed.

    See also the discussion of differing ways of :ref:`detecting Trio <trio_contexts>`.
trio.lowlevel.in_trio_task
Python Library Documentation: function in_trio_task in module trio.lowlevel

in_trio_task() -> 'bool'
    Check whether we are in a Trio task.
    This returns `True` if and only if :func:`~trio.lowlevel.current_task` will succeed.

    See also the discussion of differing ways of :ref:`detecting Trio <trio_contexts>`.
trio.lowlevel.monitor_completion_key
Python Library Documentation: function monitor_completion_key in module trio.lowlevel

monitor_completion_key() -> 'AbstractContextManager[tuple[int, UnboundedQueue[object]]]'
    TODO: these are implemented, but are currently more of a sketch than
    anything real. See `#26
    <https://github.com/python-trio/trio/issues/26>`__ and `#52
    <https://github.com/python-trio/trio/issues/52>`__.
trio.lowlevel.notify_closing
Python Library Documentation: function notify_closing in module trio.lowlevel

notify_closing(handle: 'Handle | int | _HasFileNo') -> 'None'
    Notify waiters of the given object that it will be closed.

    Call this before closing a file descriptor (on Unix) or socket (on
    Windows). This will cause any `wait_readable` or `wait_writable`
    calls on the given object to immediately wake up and raise
    `~trio.ClosedResourceError`.

    This doesn't actually close the object – you still have to do that
    yourself afterwards. Also, you want to be careful to make sure no
    new tasks start waiting on the object in between when you call this
    and when it's actually closed. So to close something properly, you
    usually want to do these steps in order:

    1. Explicitly mark the object as closed, so that any new attempts
       to use it will abort before they start.
    2. Call `notify_closing` to wake up any already-existing users.
    3. Actually close the object.

    It's also possible to do them in a different order if that's more
    convenient, *but only if* you make sure not to have any checkpoints in
    between the steps. This way they all happen in a single atomic
    step, so other tasks won't be able to tell what order they happened
    in anyway.
trio.lowlevel.open_process
Python Library Documentation: function open_process in module trio.lowlevel

async open_process(command: 'StrOrBytesPath | Sequence[StrOrBytesPath]', *, stdin: 'int | HasFileno | None' = None, stdout: 'int | HasFileno | None' = None, stderr: 'int | HasFileno | None' = None, **options: 'object') -> 'Process'
    Execute a child program in a new process.

    After construction, you can interact with the child process by writing data to its
    `~trio.Process.stdin` stream (a `~trio.abc.SendStream`), reading data from its
    `~trio.Process.stdout` and/or `~trio.Process.stderr` streams (both
    `~trio.abc.ReceiveStream`\s), sending it signals using `~trio.Process.terminate`,
    `~trio.Process.kill`, or `~trio.Process.send_signal`, and waiting for it to exit
    using `~trio.Process.wait`. See `trio.Process` for details.

    Each standard stream is only available if you specify that a pipe should be created
    for it. For example, if you pass ``stdin=subprocess.PIPE``, you can write to the
    `~trio.Process.stdin` stream, else `~trio.Process.stdin` will be ``None``.

    Unlike `trio.run_process`, this function doesn't do any kind of automatic
    management of the child process. It's up to you to implement whatever semantics you
    want.

    Args:
      command: The command to run. Typically this is a sequence of strings or
          bytes such as ``['ls', '-l', 'directory with spaces']``, where the
          first element names the executable to invoke and the other elements
          specify its arguments. With ``shell=True`` in the ``**options``, or on
          Windows, ``command`` can be a string or bytes, which will be parsed
          following platform-dependent :ref:`quoting rules
          <subprocess-quoting>`. In all cases ``command`` can be a path or a
          sequence of paths.
      stdin: Specifies what the child process's standard input
          stream should connect to: output written by the parent
          (``subprocess.PIPE``), nothing (``subprocess.DEVNULL``),
          or an open file (pass a file descriptor or something whose
          ``fileno`` method returns one). If ``stdin`` is unspecified,
          the child process will have the same standard input stream
          as its parent.
      stdout: Like ``stdin``, but for the child process's standard output
          stream.
      stderr: Like ``stdin``, but for the child process's standard error
          stream. An additional value ``subprocess.STDOUT`` is supported,
          which causes the child's standard output and standard error
          messages to be intermixed on a single standard output stream,
          attached to whatever the ``stdout`` option says to attach it to.
      **options: Other :ref:`general subprocess options <subprocess-options>`
          are also accepted.

    Returns:
      A new `trio.Process` object.

    Raises:
      OSError: if the process spawning fails, for example because the
         specified command could not be found.
trio.lowlevel.permanently_detach_coroutine_object
Python Library Documentation: function permanently_detach_coroutine_object in module trio.lowlevel

async permanently_detach_coroutine_object(final_outcome: 'outcome.Outcome[object]') -> 'object'
    Permanently detach the current task from the Trio scheduler.

    Normally, a Trio task doesn't exit until its coroutine object exits. When
    you call this function, Trio acts like the coroutine object just exited
    and the task terminates with the given outcome. This is useful if you want
    to permanently switch the coroutine object over to a different coroutine
    runner.

    When the calling coroutine enters this function it's running under Trio,
    and when the function returns it's running under the foreign coroutine
    runner.

    You should make sure that the coroutine object has released any
    Trio-specific resources it has acquired (e.g. nurseries).

    Args:
      final_outcome (outcome.Outcome): Trio acts as if the current task exited
          with the given return value or exception.

    Returns or raises whatever value or exception the new coroutine runner
    uses to resume the coroutine.
trio.lowlevel.readinto_overlapped
Python Library Documentation: function readinto_overlapped in module trio.lowlevel

async readinto_overlapped(handle: 'int | CData', buffer: 'Buffer', file_offset: 'int' = 0) -> 'int'
    TODO: these are implemented, but are currently more of a sketch than
    anything real. See `#26
    <https://github.com/python-trio/trio/issues/26>`__ and `#52
    <https://github.com/python-trio/trio/issues/52>`__.
trio.lowlevel.reattach_detached_coroutine_object
Python Library Documentation: function reattach_detached_coroutine_object in module trio.lowlevel

async reattach_detached_coroutine_object(task: 'Task', yield_value: 'object') -> 'None'
    Reattach a coroutine object that was detached using
    :func:`temporarily_detach_coroutine_object`.

    When the calling coroutine enters this function it's running under the
    foreign coroutine runner, and when the function returns it's running under
    Trio.

    This must be called from inside the coroutine being resumed, and yields
    whatever value you pass in. (Presumably you'll pass a value that will
    cause the current coroutine runner to stop scheduling this task.) Then the
    coroutine is resumed by the Trio scheduler at the next opportunity.

    Args:
      task (Task): The Trio task object that the current coroutine was
          detached from.
      yield_value (object): The object to yield to the current coroutine
          runner.
trio.lowlevel.register_with_iocp
Python Library Documentation: function register_with_iocp in module trio.lowlevel

register_with_iocp(handle: 'int | CData') -> 'None'
    TODO: these are implemented, but are currently more of a sketch than
    anything real. See `#26
    <https://github.com/python-trio/trio/issues/26>`__ and `#52
    <https://github.com/python-trio/trio/issues/52>`__.
trio.lowlevel.remove_instrument
Python Library Documentation: function remove_instrument in module trio.lowlevel

remove_instrument(instrument: 'Instrument') -> 'None'
    Stop instrumenting the current run loop with the given instrument.

    Args:
      instrument (trio.abc.Instrument): The instrument to de-activate.

    Raises:
      KeyError: if the instrument is not currently active. This could
          occur either because you never added it, or because you added it
          and then it raised an unhandled exception and was automatically
          deactivated.
trio.lowlevel.remove_parking_lot_breaker
Python Library Documentation: function remove_parking_lot_breaker in module trio.lowlevel

remove_parking_lot_breaker(task: 'Task', lot: 'ParkingLot') -> 'None'
    Deregister a task as a breaker for a lot. See :meth:`ParkingLot.break_lot`
trio.lowlevel.reschedule
Python Library Documentation: function reschedule in module trio.lowlevel

reschedule(task: 'Task', next_send: 'outcome.Outcome[object]' = <object object at 0x000001F2E1FB8D60>) -> 'None'
    Reschedule the given task with the given
    :class:`outcome.Outcome`.

    See :func:`wait_task_rescheduled` for the gory details.

    There must be exactly one call to :func:`reschedule` for every call to
    :func:`wait_task_rescheduled`. (And when counting, keep in mind that
    returning :data:`Abort.SUCCEEDED` from an abort callback is equivalent
    to calling :func:`reschedule` once.)

    Args:
      task (trio.lowlevel.Task): the task to be rescheduled. Must be blocked
          in a call to :func:`wait_task_rescheduled`.
      next_send (outcome.Outcome): the value (or error) to return (or
          raise) from :func:`wait_task_rescheduled`.
trio.lowlevel.spawn_system_task
Python Library Documentation: function spawn_system_task in module trio.lowlevel

spawn_system_task(async_fn: 'Callable[[Unpack[PosArgT]], Awaitable[object]]', *args: 'Unpack[PosArgT]', name: 'object' = None, context: 'contextvars.Context | None' = None) -> 'Task'
    Spawn a "system" task.

    System tasks have a few differences from regular tasks:

    * They don't need an explicit nursery; instead they go into the
      internal "system nursery".

    * If a system task raises an exception, then it's converted into a
      :exc:`~trio.TrioInternalError` and *all* tasks are cancelled. If you
      write a system task, you should be careful to make sure it doesn't
      crash.

    * System tasks are automatically cancelled when the main task exits.

    * By default, system tasks have :exc:`KeyboardInterrupt` protection
      *enabled*. If you want your task to be interruptible by control-C,
      then you need to use :func:`disable_ki_protection` explicitly (and
      come up with some plan for what to do with a
      :exc:`KeyboardInterrupt`, given that system tasks aren't allowed to
      raise exceptions).

    * System tasks do not inherit context variables from their creator.

    Towards the end of a call to :meth:`trio.run`, after the main
    task and all system tasks have exited, the system nursery
    becomes closed. At this point, new calls to
    :func:`spawn_system_task` will raise ``RuntimeError("Nursery
    is closed to new arrivals")`` instead of creating a system
    task. It's possible to encounter this state either in
    a ``finally`` block in an async generator, or in a callback
    passed to :meth:`TrioToken.run_sync_soon` at the right moment.

    Args:
      async_fn: An async callable.
      args: Positional arguments for ``async_fn``. If you want to pass
          keyword arguments, use :func:`functools.partial`.
      name: The name for this task. Only used for debugging/introspection
          (e.g. ``repr(task_obj)``). If this isn't a string,
          :func:`spawn_system_task` will try to make it one. A common use
          case is if you're wrapping a function before spawning a new
          task, you might pass the original function as the ``name=`` to
          make debugging easier.
      context: An optional ``contextvars.Context`` object with context variables
          to use for this task. You would normally get a copy of the current
          context with ``context = contextvars.copy_context()`` and then you would
          pass that ``context`` object here.

    Returns:
      Task: the newly spawned task
trio.lowlevel.start_guest_run
Python Library Documentation: function start_guest_run in module trio.lowlevel

start_guest_run(async_fn: 'Callable[..., Awaitable[RetT]]', *args: 'object', run_sync_soon_threadsafe: 'Callable[[Callable[[], object]], object]', done_callback: 'Callable[[outcome.Outcome[RetT]], object]', run_sync_soon_not_threadsafe: 'Callable[[Callable[[], object]], object] | None' = None, host_uses_signal_set_wakeup_fd: 'bool' = False, clock: 'Clock | None' = None, instruments: 'Sequence[Instrument]' = (), restrict_keyboard_interrupt_to_checkpoints: 'bool' = False, strict_exception_groups: 'bool' = True) -> 'None'
    Start a "guest" run of Trio on top of some other "host" event loop.

    Each host loop can only have one guest run at a time.

    You should always let the Trio run finish before stopping the host loop;
    if not, it may leave Trio's internal data structures in an inconsistent
    state. You might be able to get away with it if you immediately exit the
    program, but it's safest not to go there in the first place.

    Generally, the best way to do this is wrap this in a function that starts
    the host loop and then immediately starts the guest run, and then shuts
    down the host when the guest run completes.

    Once :func:`start_guest_run` returns successfully, the guest run
    has been set up enough that you can invoke sync-colored Trio
    functions such as :func:`~trio.current_time`, :func:`spawn_system_task`,
    and :func:`current_trio_token`. If a `~trio.TrioInternalError` occurs
    during this early setup of the guest run, it will be raised out of
    :func:`start_guest_run`.  All other errors, including all errors
    raised by the *async_fn*, will be delivered to your
    *done_callback* at some point after :func:`start_guest_run` returns
    successfully.

    Args:

      run_sync_soon_threadsafe: An arbitrary callable, which will be passed a
         function as its sole argument::

            def my_run_sync_soon_threadsafe(fn):
                ...

         This callable should schedule ``fn()`` to be run by the host on its
         next pass through its loop. **Must support being called from
         arbitrary threads.**

      done_callback: An arbitrary callable::

            def my_done_callback(run_outcome):
                ...

         When the Trio run has finished, Trio will invoke this callback to let
         you know. The argument is an `outcome.Outcome`, reporting what would
         have been returned or raised by `trio.run`. This function can do
         anything you want, but commonly you'll want it to shut down the
         host loop, unwrap the outcome, etc.

      run_sync_soon_not_threadsafe: Like ``run_sync_soon_threadsafe``, but
         will only be called from inside the host loop's main thread.
         Optional, but if your host loop allows you to implement this more
         efficiently than ``run_sync_soon_threadsafe`` then passing it will
         make things a bit faster.

      host_uses_signal_set_wakeup_fd (bool): Pass `True` if your host loop
         uses `signal.set_wakeup_fd`, and `False` otherwise. For more details,
         see :ref:`guest-run-implementation`.

    For the meaning of other arguments, see `trio.run`.
trio.lowlevel.start_thread_soon
Python Library Documentation: function start_thread_soon in module trio.lowlevel

start_thread_soon(fn: 'Callable[[], RetT]', deliver: 'Callable[[outcome.Outcome[RetT]], object]', name: 'str | None' = None) -> 'None'
    Runs ``deliver(outcome.capture(fn))`` in a worker thread.

    Generally ``fn`` does some blocking work, and ``deliver`` delivers the
    result back to whoever is interested.

    This is a low-level, no-frills interface, very similar to using
    `threading.Thread` to spawn a thread directly. The main difference is
    that this function tries to reuse threads when possible, so it can be
    a bit faster than `threading.Thread`.

    Worker threads have the `~threading.Thread.daemon` flag set, which means
    that if your main thread exits, worker threads will automatically be
    killed. If you want to make sure that your ``fn`` runs to completion, then
    you should make sure that the main thread remains alive until ``deliver``
    is called.

    It is safe to call this function simultaneously from multiple threads.

    Args:

        fn (sync function): Performs arbitrary blocking work.

        deliver (sync function): Takes the `outcome.Outcome` of ``fn``, and
          delivers it. *Must not block.*

    Because worker threads are cached and reused for multiple calls, neither
    function should mutate thread-level state, like `threading.local` objects
    – or if they do, they should be careful to revert their changes before
    returning.

    Note:

        The split between ``fn`` and ``deliver`` serves two purposes. First,
        it's convenient, since most callers need something like this anyway.

        Second, it avoids a small race condition that could cause too many
        threads to be spawned. Consider a program that wants to run several
        jobs sequentially on a thread, so the main thread submits a job, waits
        for it to finish, submits another job, etc. In theory, this program
        should only need one worker thread. But what could happen is:

        1. Worker thread: First job finishes, and calls ``deliver``.

        2. Main thread: receives notification that the job finished, and calls
           ``start_thread_soon``.

        3. Main thread: sees that no worker threads are marked idle, so spawns
           a second worker thread.

        4. Original worker thread: marks itself as idle.

        To avoid this, threads mark themselves as idle *before* calling
        ``deliver``.

        Is this potential extra thread a major problem? Maybe not, but it's
        easy enough to avoid, and we figure that if the user is trying to
        limit how many threads they're using then it's polite to respect that.
trio.lowlevel.temporarily_detach_coroutine_object
Python Library Documentation: function temporarily_detach_coroutine_object in module trio.lowlevel

async temporarily_detach_coroutine_object(abort_func: 'Callable[[RaiseCancelT], Abort]') -> 'object'
    Temporarily detach the current coroutine object from the Trio
    scheduler.

    When the calling coroutine enters this function it's running under Trio,
    and when the function returns it's running under the foreign coroutine
    runner.

    The Trio :class:`Task` will continue to exist, but will be suspended until
    you use :func:`reattach_detached_coroutine_object` to resume it. In the
    mean time, you can use another coroutine runner to schedule the coroutine
    object. In fact, you have to – the function doesn't return until the
    coroutine is advanced from outside.

    Note that you'll need to save the current :class:`Task` object to later
    resume; you can retrieve it with :func:`current_task`. You can also use
    this :class:`Task` object to retrieve the coroutine object – see
    :data:`Task.coro`.

    Args:
      abort_func: Same as for :func:`wait_task_rescheduled`, except that it
          must return :data:`Abort.FAILED`. (If it returned
          :data:`Abort.SUCCEEDED`, then Trio would attempt to reschedule the
          detached task directly without going through
          :func:`reattach_detached_coroutine_object`, which would be bad.)
          Your ``abort_func`` should still arrange for whatever the coroutine
          object is doing to be cancelled, and then reattach to Trio and call
          the ``raise_cancel`` callback, if possible.

    Returns or raises whatever value or exception the new coroutine runner
    uses to resume the coroutine.
trio.lowlevel.wait_overlapped
Python Library Documentation: function wait_overlapped in module trio.lowlevel

async wait_overlapped(handle_: 'int | CData', lpOverlapped: 'CData | int') -> 'object'
    TODO: these are implemented, but are currently more of a sketch than
    anything real. See `#26
    <https://github.com/python-trio/trio/issues/26>`__ and `#52
    <https://github.com/python-trio/trio/issues/52>`__.
trio.lowlevel.wait_readable
Python Library Documentation: function wait_readable in module trio.lowlevel

async wait_readable(sock: '_HasFileNo | int') -> 'None'
    Block until the kernel reports that the given object is readable.

    On Unix systems, ``sock`` must either be an integer file descriptor,
    or else an object with a ``.fileno()`` method which returns an
    integer file descriptor. Any kind of file descriptor can be passed,
    though the exact semantics will depend on your kernel. For example,
    this probably won't do anything useful for on-disk files.

    On Windows systems, ``sock`` must either be an integer ``SOCKET``
    handle, or else an object with a ``.fileno()`` method which returns
    an integer ``SOCKET`` handle. File descriptors aren't supported,
    and neither are handles that refer to anything besides a
    ``SOCKET``.

    :raises trio.BusyResourceError:
        if another task is already waiting for the given socket to
        become readable.
    :raises trio.ClosedResourceError:
        if another task calls :func:`notify_closing` while this
        function is still working.
trio.lowlevel.wait_task_rescheduled
Python Library Documentation: function wait_task_rescheduled in module trio.lowlevel

async wait_task_rescheduled(abort_func: 'Callable[[RaiseCancelT], Abort]') -> 'Any'
    Put the current task to sleep, with cancellation support.

    This is the lowest-level API for blocking in Trio. Every time a
    :class:`~trio.lowlevel.Task` blocks, it does so by calling this function
    (usually indirectly via some higher-level API).

    This is a tricky interface with no guard rails. If you can use
    :class:`ParkingLot` or the built-in I/O wait functions instead, then you
    should.

    Generally the way it works is that before calling this function, you make
    arrangements for "someone" to call :func:`reschedule` on the current task
    at some later point.

    Then you call :func:`wait_task_rescheduled`, passing in ``abort_func``, an
    "abort callback".

    (Terminology: in Trio, "aborting" is the process of attempting to
    interrupt a blocked task to deliver a cancellation.)

    There are two possibilities for what happens next:

    1. "Someone" calls :func:`reschedule` on the current task, and
       :func:`wait_task_rescheduled` returns or raises whatever value or error
       was passed to :func:`reschedule`.

    2. The call's context transitions to a cancelled state (e.g. due to a
       timeout expiring). When this happens, the ``abort_func`` is called. Its
       interface looks like::

           def abort_func(raise_cancel):
               ...
               return trio.lowlevel.Abort.SUCCEEDED  # or FAILED

       It should attempt to clean up any state associated with this call, and
       in particular, arrange that :func:`reschedule` will *not* be called
       later. If (and only if!) it is successful, then it should return
       :data:`Abort.SUCCEEDED`, in which case the task will automatically be
       rescheduled with an appropriate :exc:`~trio.Cancelled` error.

       Otherwise, it should return :data:`Abort.FAILED`. This means that the
       task can't be cancelled at this time, and still has to make sure that
       "someone" eventually calls :func:`reschedule`.

       At that point there are again two possibilities. You can simply ignore
       the cancellation altogether: wait for the operation to complete and
       then reschedule and continue as normal. (For example, this is what
       :func:`trio.to_thread.run_sync` does if cancellation is disabled.)
       The other possibility is that the ``abort_func`` does succeed in
       cancelling the operation, but for some reason isn't able to report that
       right away. (Example: on Windows, it's possible to request that an
       async ("overlapped") I/O operation be cancelled, but this request is
       *also* asynchronous – you don't find out until later whether the
       operation was actually cancelled or not.)  To report a delayed
       cancellation, then you should reschedule the task yourself, and call
       the ``raise_cancel`` callback passed to ``abort_func`` to raise a
       :exc:`~trio.Cancelled` (or possibly :exc:`KeyboardInterrupt`) exception
       into this task. Either of the approaches sketched below can work::

          # Option 1:
          # Catch the exception from raise_cancel and inject it into the task.
          # (This is what Trio does automatically for you if you return
          # Abort.SUCCEEDED.)
          trio.lowlevel.reschedule(task, outcome.capture(raise_cancel))

          # Option 2:
          # wait to be woken by "someone", and then decide whether to raise
          # the error from inside the task.
          outer_raise_cancel = None
          def abort(inner_raise_cancel):
              nonlocal outer_raise_cancel
              outer_raise_cancel = inner_raise_cancel
              TRY_TO_CANCEL_OPERATION()
              return trio.lowlevel.Abort.FAILED
          await wait_task_rescheduled(abort)
          if OPERATION_WAS_SUCCESSFULLY_CANCELLED:
              # raises the error
              outer_raise_cancel()

       In any case it's guaranteed that we only call the ``abort_func`` at most
       once per call to :func:`wait_task_rescheduled`.

    Sometimes, it's useful to be able to share some mutable sleep-related data
    between the sleeping task, the abort function, and the waking task. You
    can use the sleeping task's :data:`~Task.custom_sleep_data` attribute to
    store this data, and Trio won't touch it, except to make sure that it gets
    cleared when the task is rescheduled.

    .. warning::

       If your ``abort_func`` raises an error, or returns any value other than
       :data:`Abort.SUCCEEDED` or :data:`Abort.FAILED`, then Trio will crash
       violently. Be careful! Similarly, it is entirely possible to deadlock a
       Trio program by failing to reschedule a blocked task, or cause havoc by
       calling :func:`reschedule` too many times. Remember what we said up
       above about how you should use a higher-level API if at all possible?
trio.lowlevel.wait_writable
Python Library Documentation: function wait_writable in module trio.lowlevel

async wait_writable(sock: '_HasFileNo | int') -> 'None'
    Block until the kernel reports that the given object is writable.

    See `wait_readable` for the definition of ``sock``.

    :raises trio.BusyResourceError:
        if another task is already waiting for the given socket to
        become writable.
    :raises trio.ClosedResourceError:
        if another task calls :func:`notify_closing` while this
        function is still working.
trio.lowlevel.write_overlapped
Python Library Documentation: function write_overlapped in module trio.lowlevel

async write_overlapped(handle: 'int | CData', data: 'Buffer', file_offset: 'int' = 0) -> 'int'
    TODO: these are implemented, but are currently more of a sketch than
    anything real. See `#26
    <https://github.com/python-trio/trio/issues/26>`__ and `#52
    <https://github.com/python-trio/trio/issues/52>`__.