index
int64 0
731k
| package
stringlengths 2
98
⌀ | name
stringlengths 1
76
| docstring
stringlengths 0
281k
⌀ | code
stringlengths 4
1.07M
⌀ | signature
stringlengths 2
42.8k
⌀ |
---|---|---|---|---|---|
40,220 | trio_websocket._impl | __init__ |
Constructor.
:param int code:
:param Optional[str] reason:
| def __init__(self, code, reason):
'''
Constructor.
:param int code:
:param Optional[str] reason:
'''
self._code = code
try:
self._name = wsframeproto.CloseReason(code).name
except ValueError:
if 1000 <= code <= 2999:
self._name = 'RFC_RESERVED'
elif 3000 <= code <= 3999:
self._name = 'IANA_RESERVED'
elif 4000 <= code <= 4999:
self._name = 'PRIVATE_RESERVED'
else:
self._name = 'INVALID_CODE'
self._reason = reason
| (self, code, reason) |
40,221 | trio_websocket._impl | __repr__ | Show close code, name, and reason. | def __repr__(self):
''' Show close code, name, and reason. '''
return f'{self.__class__.__name__}' \
f'<code={self.code}, name={self.name}, reason={self.reason}>'
| (self) |
40,222 | trio_websocket._impl | ConnectionClosed |
A WebSocket operation cannot be completed because the connection is closed
or in the process of closing.
| class ConnectionClosed(Exception):
'''
A WebSocket operation cannot be completed because the connection is closed
or in the process of closing.
'''
def __init__(self, reason):
'''
Constructor.
:param reason:
:type reason: CloseReason
'''
super().__init__()
self.reason = reason
def __repr__(self):
''' Return representation. '''
return f'{self.__class__.__name__}<{self.reason}>'
| (reason) |
40,223 | trio_websocket._impl | __init__ |
Constructor.
:param reason:
:type reason: CloseReason
| def __init__(self, reason):
'''
Constructor.
:param reason:
:type reason: CloseReason
'''
super().__init__()
self.reason = reason
| (self, reason) |
40,224 | trio_websocket._impl | __repr__ | Return representation. | def __repr__(self):
''' Return representation. '''
return f'{self.__class__.__name__}<{self.reason}>'
| (self) |
40,225 | trio_websocket._impl | ConnectionRejected |
A WebSocket connection could not be established because the server rejected
the connection attempt.
| class ConnectionRejected(HandshakeError):
'''
A WebSocket connection could not be established because the server rejected
the connection attempt.
'''
def __init__(self, status_code, headers, body):
'''
Constructor.
:param reason:
:type reason: CloseReason
'''
super().__init__()
#: a 3 digit HTTP status code
self.status_code = status_code
#: a tuple of 2-tuples containing header key/value pairs
self.headers = headers
#: an optional ``bytes`` response body
self.body = body
def __repr__(self):
''' Return representation. '''
return f'{self.__class__.__name__}<status_code={self.status_code}>'
| (status_code, headers, body) |
40,226 | trio_websocket._impl | __init__ |
Constructor.
:param reason:
:type reason: CloseReason
| def __init__(self, status_code, headers, body):
'''
Constructor.
:param reason:
:type reason: CloseReason
'''
super().__init__()
#: a 3 digit HTTP status code
self.status_code = status_code
#: a tuple of 2-tuples containing header key/value pairs
self.headers = headers
#: an optional ``bytes`` response body
self.body = body
| (self, status_code, headers, body) |
40,227 | trio_websocket._impl | __repr__ | Return representation. | def __repr__(self):
''' Return representation. '''
return f'{self.__class__.__name__}<status_code={self.status_code}>'
| (self) |
40,228 | trio_websocket._impl | ConnectionTimeout | There was a timeout when connecting to the websocket server. | class ConnectionTimeout(HandshakeError):
'''There was a timeout when connecting to the websocket server.'''
| null |
40,229 | trio_websocket._impl | DisconnectionTimeout | There was a timeout when disconnecting from the websocket server. | class DisconnectionTimeout(HandshakeError):
'''There was a timeout when disconnecting from the websocket server.'''
| null |
40,230 | trio_websocket._impl | Endpoint | Represents a connection endpoint. | class Endpoint:
''' Represents a connection endpoint. '''
def __init__(self, address, port, is_ssl):
#: IP address :class:`ipaddress.ip_address`
self.address = ip_address(address)
#: TCP port
self.port = port
#: Whether SSL is in use
self.is_ssl = is_ssl
@property
def url(self):
''' Return a URL representation of a TCP endpoint, e.g.
``ws://127.0.0.1:80``. '''
scheme = 'wss' if self.is_ssl else 'ws'
if (self.port == 80 and not self.is_ssl) or \
(self.port == 443 and self.is_ssl):
port_str = ''
else:
port_str = ':' + str(self.port)
if self.address.version == 4:
return f'{scheme}://{self.address}{port_str}'
return f'{scheme}://[{self.address}]{port_str}'
def __repr__(self):
''' Return endpoint info as string. '''
return f'Endpoint(address="{self.address}", port={self.port}, is_ssl={self.is_ssl})'
| (address, port, is_ssl) |
40,231 | trio_websocket._impl | __init__ | null | def __init__(self, address, port, is_ssl):
#: IP address :class:`ipaddress.ip_address`
self.address = ip_address(address)
#: TCP port
self.port = port
#: Whether SSL is in use
self.is_ssl = is_ssl
| (self, address, port, is_ssl) |
40,232 | trio_websocket._impl | __repr__ | Return endpoint info as string. | def __repr__(self):
''' Return endpoint info as string. '''
return f'Endpoint(address="{self.address}", port={self.port}, is_ssl={self.is_ssl})'
| (self) |
40,233 | trio_websocket._impl | HandshakeError |
There was an error during connection or disconnection with the websocket
server.
| class HandshakeError(Exception):
'''
There was an error during connection or disconnection with the websocket
server.
'''
| null |
40,234 | trio_websocket._impl | WebSocketConnection | A WebSocket connection. | class WebSocketConnection(trio.abc.AsyncResource):
''' A WebSocket connection. '''
CONNECTION_ID = itertools.count()
def __init__(self, stream, ws_connection, *, host=None, path=None,
client_subprotocols=None, client_extra_headers=None,
message_queue_size=MESSAGE_QUEUE_SIZE,
max_message_size=MAX_MESSAGE_SIZE):
'''
Constructor.
Generally speaking, users are discouraged from directly instantiating a
``WebSocketConnection`` and should instead use one of the convenience
functions in this module, e.g. ``open_websocket()`` or
``serve_websocket()``. This class has some tricky internal logic and
timing that depends on whether it is an instance of a client connection
or a server connection. The convenience functions handle this complexity
for you.
:param SocketStream stream:
:param ws_connection wsproto.WSConnection:
:param str host: The hostname to send in the HTTP request headers. Only
used for client connections.
:param str path: The URL path for this connection.
:param list client_subprotocols: A list of desired subprotocols. Only
used for client connections.
:param list[tuple[bytes,bytes]] client_extra_headers: Extra headers to
send with the connection request. Only used for client connections.
:param int message_queue_size: The maximum number of messages that will be
buffered in the library's internal message queue.
:param int max_message_size: The maximum message size as measured by
``len()``. If a message is received that is larger than this size,
then the connection is closed with code 1009 (Message Too Big).
'''
# NOTE: The implementation uses _close_reason for more than an advisory
# purpose. It's critical internal state, indicating when the
# connection is closed or closing.
self._close_reason: Optional[CloseReason] = None
self._id = next(self.__class__.CONNECTION_ID)
self._stream = stream
self._stream_lock = trio.StrictFIFOLock()
self._wsproto = ws_connection
self._message_size = 0
self._message_parts: List[Union[bytes, str]] = []
self._max_message_size = max_message_size
self._reader_running = True
if ws_connection.client:
self._initial_request: Optional[Request] = Request(host=host, target=path,
subprotocols=client_subprotocols,
extra_headers=client_extra_headers or [])
else:
self._initial_request = None
self._path = path
self._subprotocol: Optional[str] = None
self._handshake_headers = tuple()
self._reject_status = 0
self._reject_headers = tuple()
self._reject_body = b''
self._send_channel, self._recv_channel = trio.open_memory_channel(
message_queue_size)
self._pings = OrderedDict()
# Set when the server has received a connection request event. This
# future is never set on client connections.
self._connection_proposal = Future()
# Set once the WebSocket open handshake takes place, i.e.
# ConnectionRequested for server or ConnectedEstablished for client.
self._open_handshake = trio.Event()
# Set once a WebSocket closed handshake takes place, i.e after a close
# frame has been sent and a close frame has been received.
self._close_handshake = trio.Event()
# Set upon receiving CloseConnection from peer.
# Used to test close race conditions between client and server.
self._for_testing_peer_closed_connection = trio.Event()
@property
def closed(self):
'''
(Read-only) The reason why the connection was or is being closed,
else ``None``.
:rtype: Optional[CloseReason]
'''
return self._close_reason
@property
def is_client(self):
''' (Read-only) Is this a client instance? '''
return self._wsproto.client
@property
def is_server(self):
''' (Read-only) Is this a server instance? '''
return not self._wsproto.client
@property
def local(self):
'''
The local endpoint of the connection.
:rtype: Endpoint or str
'''
return _get_stream_endpoint(self._stream, local=True)
@property
def remote(self):
'''
The remote endpoint of the connection.
:rtype: Endpoint or str
'''
return _get_stream_endpoint(self._stream, local=False)
@property
def path(self):
'''
The requested URL path. For clients, this is set when the connection is
instantiated. For servers, it is set after the handshake completes.
:rtype: str
'''
return self._path
@property
def subprotocol(self):
'''
(Read-only) The negotiated subprotocol, or ``None`` if there is no
subprotocol.
This is only valid after the opening handshake is complete.
:rtype: str or None
'''
return self._subprotocol
@property
def handshake_headers(self):
'''
The HTTP headers that were sent by the remote during the handshake,
stored as 2-tuples containing key/value pairs. Header keys are always
lower case.
:rtype: tuple[tuple[str,str]]
'''
return self._handshake_headers
async def aclose(self, code=1000, reason=None): # pylint: disable=arguments-differ
'''
Close the WebSocket connection.
This sends a closing frame and suspends until the connection is closed.
After calling this method, any further I/O on this WebSocket (such as
``get_message()`` or ``send_message()``) will raise
``ConnectionClosed``.
This method is idempotent: it may be called multiple times on the same
connection without any errors.
:param int code: A 4-digit code number indicating the type of closure.
:param str reason: An optional string describing the closure.
'''
with _preserve_current_exception():
await self._aclose(code, reason)
async def _aclose(self, code, reason):
if self._close_reason:
# Per AsyncResource interface, calling aclose() on a closed resource
# should succeed.
return
try:
if self._wsproto.state == ConnectionState.OPEN:
# Our side is initiating the close, so send a close connection
# event to peer, while setting the local close reason to normal.
self._close_reason = CloseReason(1000, None)
await self._send(CloseConnection(code=code, reason=reason))
elif self._wsproto.state in (ConnectionState.CONNECTING,
ConnectionState.REJECTING):
self._close_handshake.set()
# TODO: shouldn't the receive channel be closed earlier, so that
# get_message() during send of the CloseConneciton event fails?
await self._recv_channel.aclose()
await self._close_handshake.wait()
except ConnectionClosed:
# If _send() raised ConnectionClosed, then we can bail out.
pass
finally:
# If cancelled during WebSocket close, make sure that the underlying
# stream is closed.
await self._close_stream()
async def get_message(self):
'''
Receive the next WebSocket message.
If no message is available immediately, then this function blocks until
a message is ready.
If the remote endpoint closes the connection, then the caller can still
get messages sent prior to closing. Once all pending messages have been
retrieved, additional calls to this method will raise
``ConnectionClosed``. If the local endpoint closes the connection, then
pending messages are discarded and calls to this method will immediately
raise ``ConnectionClosed``.
:rtype: str or bytes
:raises ConnectionClosed: if the connection is closed.
'''
try:
message = await self._recv_channel.receive()
except (trio.ClosedResourceError, trio.EndOfChannel):
raise ConnectionClosed(self._close_reason) from None
return message
async def ping(self, payload=None):
'''
Send WebSocket ping to remote endpoint and wait for a correspoding pong.
Each in-flight ping must include a unique payload. This function sends
the ping and then waits for a corresponding pong from the remote
endpoint.
*Note: If the remote endpoint recieves multiple pings, it is allowed to
send a single pong. Therefore, the order of calls to ``ping()`` is
tracked, and a pong will wake up its corresponding ping as well as all
previous in-flight pings.*
:param payload: The payload to send. If ``None`` then a random 32-bit
payload is created.
:type payload: bytes or None
:raises ConnectionClosed: if connection is closed.
:raises ValueError: if ``payload`` is identical to another in-flight
ping.
'''
if self._close_reason:
raise ConnectionClosed(self._close_reason)
if payload in self._pings:
raise ValueError(f'Payload value {payload} is already in flight.')
if payload is None:
payload = struct.pack('!I', random.getrandbits(32))
event = trio.Event()
self._pings[payload] = event
await self._send(Ping(payload=payload))
await event.wait()
async def pong(self, payload=None):
'''
Send an unsolicted pong.
:param payload: The pong's payload. If ``None``, then no payload is
sent.
:type payload: bytes or None
:raises ConnectionClosed: if connection is closed
'''
if self._close_reason:
raise ConnectionClosed(self._close_reason)
await self._send(Pong(payload=payload))
async def send_message(self, message):
'''
Send a WebSocket message.
:param message: The message to send.
:type message: str or bytes
:raises ConnectionClosed: if connection is closed, or being closed
'''
if self._close_reason:
raise ConnectionClosed(self._close_reason)
if isinstance(message, str):
event = TextMessage(data=message)
elif isinstance(message, bytes):
event = BytesMessage(data=message)
else:
raise ValueError('message must be str or bytes')
await self._send(event)
def __str__(self):
''' Connection ID and type. '''
type_ = 'client' if self.is_client else 'server'
return f'{type_}-{self._id}'
async def _accept(self, request, subprotocol, extra_headers):
'''
Accept the handshake.
This method is only applicable to server-side connections.
:param wsproto.events.Request request:
:param subprotocol:
:type subprotocol: str or None
:param list[tuple[bytes,bytes]] extra_headers: A list of 2-tuples
containing key/value pairs to send as HTTP headers.
'''
self._subprotocol = subprotocol
self._path = request.target
await self._send(AcceptConnection(subprotocol=self._subprotocol,
extra_headers=extra_headers))
self._open_handshake.set()
async def _reject(self, status_code, headers, body):
'''
Reject the handshake.
:param int status_code: The 3 digit HTTP status code. In order to be
RFC-compliant, this must not be 101, and should be an appropriate
code in the range 300-599.
:param list[tuple[bytes,bytes]] headers: A list of 2-tuples containing
key/value pairs to send as HTTP headers.
:param bytes body: An optional response body.
'''
if body:
headers.append(('Content-length', str(len(body)).encode('ascii')))
reject_conn = RejectConnection(status_code=status_code, headers=headers,
has_body=bool(body))
await self._send(reject_conn)
if body:
reject_body = RejectData(data=body)
await self._send(reject_body)
self._close_reason = CloseReason(1006, 'Rejected WebSocket handshake')
self._close_handshake.set()
async def _abort_web_socket(self):
'''
If a stream is closed outside of this class, e.g. due to network
conditions or because some other code closed our stream object, then we
cannot perform the close handshake. We just need to clean up internal
state.
'''
close_reason = wsframeproto.CloseReason.ABNORMAL_CLOSURE
if self._wsproto.state == ConnectionState.OPEN:
self._wsproto.send(CloseConnection(code=close_reason.value))
if self._close_reason is None:
await self._close_web_socket(close_reason)
self._reader_running = False
# We didn't really handshake, but we want any task waiting on this event
# (e.g. self.aclose()) to resume.
self._close_handshake.set()
async def _close_stream(self):
''' Close the TCP connection. '''
self._reader_running = False
try:
with _preserve_current_exception():
await self._stream.aclose()
except trio.BrokenResourceError:
# This means the TCP connection is already dead.
pass
async def _close_web_socket(self, code, reason=None):
'''
Mark the WebSocket as closed. Close the message channel so that if any
tasks are suspended in get_message(), they will wake up with a
ConnectionClosed exception.
'''
self._close_reason = CloseReason(code, reason)
exc = ConnectionClosed(self._close_reason)
logger.debug('%s websocket closed %r', self, exc)
await self._send_channel.aclose()
async def _get_request(self):
'''
Return a proposal for a WebSocket handshake.
This method can only be called on server connections and it may only be
called one time.
:rtype: WebSocketRequest
'''
if not self.is_server:
raise RuntimeError('This method is only valid for server connections.')
if self._connection_proposal is None:
raise RuntimeError('No proposal available. Did you call this method'
' multiple times or at the wrong time?')
proposal = await self._connection_proposal.wait_value()
self._connection_proposal = None
return proposal
async def _handle_request_event(self, event):
'''
Handle a connection request.
This method is async even though it never awaits, because the event
dispatch requires an async function.
:param event:
'''
proposal = WebSocketRequest(self, event)
self._connection_proposal.set_value(proposal)
async def _handle_accept_connection_event(self, event):
'''
Handle an AcceptConnection event.
:param wsproto.eventsAcceptConnection event:
'''
self._subprotocol = event.subprotocol
self._handshake_headers = tuple(event.extra_headers)
self._open_handshake.set()
async def _handle_reject_connection_event(self, event):
'''
Handle a RejectConnection event.
:param event:
'''
self._reject_status = event.status_code
self._reject_headers = tuple(event.headers)
if not event.has_body:
raise ConnectionRejected(self._reject_status, self._reject_headers,
body=None)
async def _handle_reject_data_event(self, event):
'''
Handle a RejectData event.
:param event:
'''
self._reject_body += event.data
if event.body_finished:
raise ConnectionRejected(self._reject_status, self._reject_headers,
body=self._reject_body)
async def _handle_close_connection_event(self, event):
'''
Handle a close event.
:param wsproto.events.CloseConnection event:
'''
if self._wsproto.state == ConnectionState.REMOTE_CLOSING:
# Set _close_reason in advance, so that send_message() will raise
# ConnectionClosed during the close handshake.
self._close_reason = CloseReason(event.code, event.reason or None)
self._for_testing_peer_closed_connection.set()
await self._send(event.response())
await self._close_web_socket(event.code, event.reason or None)
self._close_handshake.set()
# RFC: "When a server is instructed to Close the WebSocket Connection
# it SHOULD initiate a TCP Close immediately, and when a client is
# instructed to do the same, it SHOULD wait for a TCP Close from the
# server."
if self.is_server:
await self._close_stream()
async def _handle_message_event(self, event):
'''
Handle a message event.
:param event:
:type event: wsproto.events.BytesMessage or wsproto.events.TextMessage
'''
self._message_size += len(event.data)
self._message_parts.append(event.data)
if self._message_size > self._max_message_size:
err = f'Exceeded maximum message size: {self._max_message_size} bytes'
self._message_size = 0
self._message_parts = []
self._close_reason = CloseReason(1009, err)
await self._send(CloseConnection(code=1009, reason=err))
await self._recv_channel.aclose()
self._reader_running = False
elif event.message_finished:
msg = (b'' if isinstance(event, BytesMessage) else '') \
.join(self._message_parts)
self._message_size = 0
self._message_parts = []
try:
await self._send_channel.send(msg)
except (trio.ClosedResourceError, trio.BrokenResourceError):
# The receive channel is closed, probably because somebody
# called ``aclose()``. We don't want to abort the reader task,
# and there's no useful cleanup that we can do here.
pass
async def _handle_ping_event(self, event):
'''
Handle a PingReceived event.
Wsproto queues a pong frame automatically, so this handler just needs to
send it.
:param wsproto.events.Ping event:
'''
logger.debug('%s ping %r', self, event.payload)
await self._send(event.response())
async def _handle_pong_event(self, event):
'''
Handle a PongReceived event.
When a pong is received, check if we have any ping requests waiting for
this pong response. If the remote endpoint skipped any earlier pings,
then we wake up those skipped pings, too.
This function is async even though it never awaits, because the other
event handlers are async, too, and event dispatch would be more
complicated if some handlers were sync.
:param event:
'''
payload = bytes(event.payload)
try:
event = self._pings[payload]
except KeyError:
# We received a pong that doesn't match any in-flight pongs. Nothing
# we can do with it, so ignore it.
return
while self._pings:
key, event = self._pings.popitem(0)
skipped = ' [skipped] ' if payload != key else ' '
logger.debug('%s pong%s%r', self, skipped, key)
event.set()
if payload == key:
break
async def _reader_task(self):
''' A background task that reads network data and generates events. '''
handlers = {
AcceptConnection: self._handle_accept_connection_event,
BytesMessage: self._handle_message_event,
CloseConnection: self._handle_close_connection_event,
Ping: self._handle_ping_event,
Pong: self._handle_pong_event,
RejectConnection: self._handle_reject_connection_event,
RejectData: self._handle_reject_data_event,
Request: self._handle_request_event,
TextMessage: self._handle_message_event,
}
# Clients need to initiate the opening handshake.
if self._initial_request:
try:
await self._send(self._initial_request)
except ConnectionClosed:
self._reader_running = False
async with self._send_channel:
while self._reader_running:
# Process events.
for event in self._wsproto.events():
event_type = type(event)
try:
handler = handlers[event_type]
logger.debug('%s received event: %s', self,
event_type)
await handler(event)
except KeyError:
logger.warning('%s received unknown event type: "%s"', self,
event_type)
except ConnectionClosed:
self._reader_running = False
break
# Get network data.
try:
data = await self._stream.receive_some(RECEIVE_BYTES)
except (trio.BrokenResourceError, trio.ClosedResourceError):
await self._abort_web_socket()
break
if len(data) == 0:
logger.debug('%s received zero bytes (connection closed)',
self)
# If TCP closed before WebSocket, then record it as an abnormal
# closure.
if self._wsproto.state != ConnectionState.CLOSED:
await self._abort_web_socket()
break
logger.debug('%s received %d bytes', self, len(data))
if self._wsproto.state != ConnectionState.CLOSED:
try:
self._wsproto.receive_data(data)
except wsproto.utilities.RemoteProtocolError as err:
logger.debug('%s remote protocol error: %s', self, err)
if err.event_hint:
await self._send(err.event_hint)
await self._close_stream()
logger.debug('%s reader task finished', self)
async def _send(self, event):
'''
Send an event to the remote WebSocket.
The reader task and one or more writers might try to send messages at
the same time, so this method uses an internal lock to serialize
requests to send data.
:param wsproto.events.Event event:
'''
data = self._wsproto.send(event)
async with self._stream_lock:
logger.debug('%s sending %d bytes', self, len(data))
try:
await self._stream.send_all(data)
except (trio.BrokenResourceError, trio.ClosedResourceError):
await self._abort_web_socket()
raise ConnectionClosed(self._close_reason) from None
| (stream, ws_connection, *, host=None, path=None, client_subprotocols=None, client_extra_headers=None, message_queue_size=1, max_message_size=1048576) |
40,237 | trio_websocket._impl | __init__ |
Constructor.
Generally speaking, users are discouraged from directly instantiating a
``WebSocketConnection`` and should instead use one of the convenience
functions in this module, e.g. ``open_websocket()`` or
``serve_websocket()``. This class has some tricky internal logic and
timing that depends on whether it is an instance of a client connection
or a server connection. The convenience functions handle this complexity
for you.
:param SocketStream stream:
:param ws_connection wsproto.WSConnection:
:param str host: The hostname to send in the HTTP request headers. Only
used for client connections.
:param str path: The URL path for this connection.
:param list client_subprotocols: A list of desired subprotocols. Only
used for client connections.
:param list[tuple[bytes,bytes]] client_extra_headers: Extra headers to
send with the connection request. Only used for client connections.
:param int message_queue_size: The maximum number of messages that will be
buffered in the library's internal message queue.
:param int max_message_size: The maximum message size as measured by
``len()``. If a message is received that is larger than this size,
then the connection is closed with code 1009 (Message Too Big).
| def __init__(self, stream, ws_connection, *, host=None, path=None,
client_subprotocols=None, client_extra_headers=None,
message_queue_size=MESSAGE_QUEUE_SIZE,
max_message_size=MAX_MESSAGE_SIZE):
'''
Constructor.
Generally speaking, users are discouraged from directly instantiating a
``WebSocketConnection`` and should instead use one of the convenience
functions in this module, e.g. ``open_websocket()`` or
``serve_websocket()``. This class has some tricky internal logic and
timing that depends on whether it is an instance of a client connection
or a server connection. The convenience functions handle this complexity
for you.
:param SocketStream stream:
:param ws_connection wsproto.WSConnection:
:param str host: The hostname to send in the HTTP request headers. Only
used for client connections.
:param str path: The URL path for this connection.
:param list client_subprotocols: A list of desired subprotocols. Only
used for client connections.
:param list[tuple[bytes,bytes]] client_extra_headers: Extra headers to
send with the connection request. Only used for client connections.
:param int message_queue_size: The maximum number of messages that will be
buffered in the library's internal message queue.
:param int max_message_size: The maximum message size as measured by
``len()``. If a message is received that is larger than this size,
then the connection is closed with code 1009 (Message Too Big).
'''
# NOTE: The implementation uses _close_reason for more than an advisory
# purpose. It's critical internal state, indicating when the
# connection is closed or closing.
self._close_reason: Optional[CloseReason] = None
self._id = next(self.__class__.CONNECTION_ID)
self._stream = stream
self._stream_lock = trio.StrictFIFOLock()
self._wsproto = ws_connection
self._message_size = 0
self._message_parts: List[Union[bytes, str]] = []
self._max_message_size = max_message_size
self._reader_running = True
if ws_connection.client:
self._initial_request: Optional[Request] = Request(host=host, target=path,
subprotocols=client_subprotocols,
extra_headers=client_extra_headers or [])
else:
self._initial_request = None
self._path = path
self._subprotocol: Optional[str] = None
self._handshake_headers = tuple()
self._reject_status = 0
self._reject_headers = tuple()
self._reject_body = b''
self._send_channel, self._recv_channel = trio.open_memory_channel(
message_queue_size)
self._pings = OrderedDict()
# Set when the server has received a connection request event. This
# future is never set on client connections.
self._connection_proposal = Future()
# Set once the WebSocket open handshake takes place, i.e.
# ConnectionRequested for server or ConnectedEstablished for client.
self._open_handshake = trio.Event()
# Set once a WebSocket closed handshake takes place, i.e after a close
# frame has been sent and a close frame has been received.
self._close_handshake = trio.Event()
# Set upon receiving CloseConnection from peer.
# Used to test close race conditions between client and server.
self._for_testing_peer_closed_connection = trio.Event()
| (self, stream, ws_connection, *, host=None, path=None, client_subprotocols=None, client_extra_headers=None, message_queue_size=1, max_message_size=1048576) |
40,238 | trio_websocket._impl | __str__ | Connection ID and type. | def __str__(self):
''' Connection ID and type. '''
type_ = 'client' if self.is_client else 'server'
return f'{type_}-{self._id}'
| (self) |
40,239 | trio_websocket._impl | _abort_web_socket |
If a stream is closed outside of this class, e.g. due to network
conditions or because some other code closed our stream object, then we
cannot perform the close handshake. We just need to clean up internal
state.
| def __str__(self):
''' Connection ID and type. '''
type_ = 'client' if self.is_client else 'server'
return f'{type_}-{self._id}'
| (self) |
40,240 | trio_websocket._impl | _accept |
Accept the handshake.
This method is only applicable to server-side connections.
:param wsproto.events.Request request:
:param subprotocol:
:type subprotocol: str or None
:param list[tuple[bytes,bytes]] extra_headers: A list of 2-tuples
containing key/value pairs to send as HTTP headers.
| def __str__(self):
''' Connection ID and type. '''
type_ = 'client' if self.is_client else 'server'
return f'{type_}-{self._id}'
| (self, request, subprotocol, extra_headers) |
40,241 | trio_websocket._impl | _aclose | null | @property
def handshake_headers(self):
'''
The HTTP headers that were sent by the remote during the handshake,
stored as 2-tuples containing key/value pairs. Header keys are always
lower case.
:rtype: tuple[tuple[str,str]]
'''
return self._handshake_headers
| (self, code, reason) |
40,242 | trio_websocket._impl | _close_stream | Close the TCP connection. | def __str__(self):
''' Connection ID and type. '''
type_ = 'client' if self.is_client else 'server'
return f'{type_}-{self._id}'
| (self) |
40,243 | trio_websocket._impl | _close_web_socket |
Mark the WebSocket as closed. Close the message channel so that if any
tasks are suspended in get_message(), they will wake up with a
ConnectionClosed exception.
| def __str__(self):
''' Connection ID and type. '''
type_ = 'client' if self.is_client else 'server'
return f'{type_}-{self._id}'
| (self, code, reason=None) |
40,244 | trio_websocket._impl | _get_request |
Return a proposal for a WebSocket handshake.
This method can only be called on server connections and it may only be
called one time.
:rtype: WebSocketRequest
| def __str__(self):
''' Connection ID and type. '''
type_ = 'client' if self.is_client else 'server'
return f'{type_}-{self._id}'
| (self) |
40,245 | trio_websocket._impl | _handle_accept_connection_event |
Handle an AcceptConnection event.
:param wsproto.eventsAcceptConnection event:
| def __str__(self):
''' Connection ID and type. '''
type_ = 'client' if self.is_client else 'server'
return f'{type_}-{self._id}'
| (self, event) |
40,246 | trio_websocket._impl | _handle_close_connection_event |
Handle a close event.
:param wsproto.events.CloseConnection event:
| def __str__(self):
''' Connection ID and type. '''
type_ = 'client' if self.is_client else 'server'
return f'{type_}-{self._id}'
| (self, event) |
40,247 | trio_websocket._impl | _handle_message_event |
Handle a message event.
:param event:
:type event: wsproto.events.BytesMessage or wsproto.events.TextMessage
| def __str__(self):
''' Connection ID and type. '''
type_ = 'client' if self.is_client else 'server'
return f'{type_}-{self._id}'
| (self, event) |
40,248 | trio_websocket._impl | _handle_ping_event |
Handle a PingReceived event.
Wsproto queues a pong frame automatically, so this handler just needs to
send it.
:param wsproto.events.Ping event:
| def __str__(self):
''' Connection ID and type. '''
type_ = 'client' if self.is_client else 'server'
return f'{type_}-{self._id}'
| (self, event) |
40,249 | trio_websocket._impl | _handle_pong_event |
Handle a PongReceived event.
When a pong is received, check if we have any ping requests waiting for
this pong response. If the remote endpoint skipped any earlier pings,
then we wake up those skipped pings, too.
This function is async even though it never awaits, because the other
event handlers are async, too, and event dispatch would be more
complicated if some handlers were sync.
:param event:
| def __str__(self):
''' Connection ID and type. '''
type_ = 'client' if self.is_client else 'server'
return f'{type_}-{self._id}'
| (self, event) |
40,250 | trio_websocket._impl | _handle_reject_connection_event |
Handle a RejectConnection event.
:param event:
| def __str__(self):
''' Connection ID and type. '''
type_ = 'client' if self.is_client else 'server'
return f'{type_}-{self._id}'
| (self, event) |
40,251 | trio_websocket._impl | _handle_reject_data_event |
Handle a RejectData event.
:param event:
| def __str__(self):
''' Connection ID and type. '''
type_ = 'client' if self.is_client else 'server'
return f'{type_}-{self._id}'
| (self, event) |
40,252 | trio_websocket._impl | _handle_request_event |
Handle a connection request.
This method is async even though it never awaits, because the event
dispatch requires an async function.
:param event:
| def __str__(self):
''' Connection ID and type. '''
type_ = 'client' if self.is_client else 'server'
return f'{type_}-{self._id}'
| (self, event) |
40,253 | trio_websocket._impl | _reader_task | A background task that reads network data and generates events. | def __str__(self):
''' Connection ID and type. '''
type_ = 'client' if self.is_client else 'server'
return f'{type_}-{self._id}'
| (self) |
40,254 | trio_websocket._impl | _reject |
Reject the handshake.
:param int status_code: The 3 digit HTTP status code. In order to be
RFC-compliant, this must not be 101, and should be an appropriate
code in the range 300-599.
:param list[tuple[bytes,bytes]] headers: A list of 2-tuples containing
key/value pairs to send as HTTP headers.
:param bytes body: An optional response body.
| def __str__(self):
''' Connection ID and type. '''
type_ = 'client' if self.is_client else 'server'
return f'{type_}-{self._id}'
| (self, status_code, headers, body) |
40,255 | trio_websocket._impl | _send |
Send an event to the remote WebSocket.
The reader task and one or more writers might try to send messages at
the same time, so this method uses an internal lock to serialize
requests to send data.
:param wsproto.events.Event event:
| def __str__(self):
''' Connection ID and type. '''
type_ = 'client' if self.is_client else 'server'
return f'{type_}-{self._id}'
| (self, event) |
40,256 | trio_websocket._impl | aclose |
Close the WebSocket connection.
This sends a closing frame and suspends until the connection is closed.
After calling this method, any further I/O on this WebSocket (such as
``get_message()`` or ``send_message()``) will raise
``ConnectionClosed``.
This method is idempotent: it may be called multiple times on the same
connection without any errors.
:param int code: A 4-digit code number indicating the type of closure.
:param str reason: An optional string describing the closure.
| @property
def handshake_headers(self):
'''
The HTTP headers that were sent by the remote during the handshake,
stored as 2-tuples containing key/value pairs. Header keys are always
lower case.
:rtype: tuple[tuple[str,str]]
'''
return self._handshake_headers
| (self, code=1000, reason=None) |
40,257 | trio_websocket._impl | get_message |
Receive the next WebSocket message.
If no message is available immediately, then this function blocks until
a message is ready.
If the remote endpoint closes the connection, then the caller can still
get messages sent prior to closing. Once all pending messages have been
retrieved, additional calls to this method will raise
``ConnectionClosed``. If the local endpoint closes the connection, then
pending messages are discarded and calls to this method will immediately
raise ``ConnectionClosed``.
:rtype: str or bytes
:raises ConnectionClosed: if the connection is closed.
| @property
def handshake_headers(self):
'''
The HTTP headers that were sent by the remote during the handshake,
stored as 2-tuples containing key/value pairs. Header keys are always
lower case.
:rtype: tuple[tuple[str,str]]
'''
return self._handshake_headers
| (self) |
40,258 | trio_websocket._impl | ping |
Send WebSocket ping to remote endpoint and wait for a correspoding pong.
Each in-flight ping must include a unique payload. This function sends
the ping and then waits for a corresponding pong from the remote
endpoint.
*Note: If the remote endpoint recieves multiple pings, it is allowed to
send a single pong. Therefore, the order of calls to ``ping()`` is
tracked, and a pong will wake up its corresponding ping as well as all
previous in-flight pings.*
:param payload: The payload to send. If ``None`` then a random 32-bit
payload is created.
:type payload: bytes or None
:raises ConnectionClosed: if connection is closed.
:raises ValueError: if ``payload`` is identical to another in-flight
ping.
| @property
def handshake_headers(self):
'''
The HTTP headers that were sent by the remote during the handshake,
stored as 2-tuples containing key/value pairs. Header keys are always
lower case.
:rtype: tuple[tuple[str,str]]
'''
return self._handshake_headers
| (self, payload=None) |
40,259 | trio_websocket._impl | pong |
Send an unsolicted pong.
:param payload: The pong's payload. If ``None``, then no payload is
sent.
:type payload: bytes or None
:raises ConnectionClosed: if connection is closed
| @property
def handshake_headers(self):
'''
The HTTP headers that were sent by the remote during the handshake,
stored as 2-tuples containing key/value pairs. Header keys are always
lower case.
:rtype: tuple[tuple[str,str]]
'''
return self._handshake_headers
| (self, payload=None) |
40,260 | trio_websocket._impl | send_message |
Send a WebSocket message.
:param message: The message to send.
:type message: str or bytes
:raises ConnectionClosed: if connection is closed, or being closed
| @property
def handshake_headers(self):
'''
The HTTP headers that were sent by the remote during the handshake,
stored as 2-tuples containing key/value pairs. Header keys are always
lower case.
:rtype: tuple[tuple[str,str]]
'''
return self._handshake_headers
| (self, message) |
40,261 | trio_websocket._impl | WebSocketRequest |
Represents a handshake presented by a client to a server.
The server may modify the handshake or leave it as is. The server should
call ``accept()`` to finish the handshake and obtain a connection object.
| class WebSocketRequest:
'''
Represents a handshake presented by a client to a server.
The server may modify the handshake or leave it as is. The server should
call ``accept()`` to finish the handshake and obtain a connection object.
'''
def __init__(self, connection, event):
'''
Constructor.
:param WebSocketConnection connection:
:type event: wsproto.events.Request
'''
self._connection = connection
self._event = event
@property
def headers(self):
'''
HTTP headers represented as a list of (name, value) pairs.
:rtype: list[tuple]
'''
return self._event.extra_headers
@property
def path(self):
'''
The requested URL path.
:rtype: str
'''
return self._event.target
@property
def proposed_subprotocols(self):
'''
A tuple of protocols proposed by the client.
:rtype: tuple[str]
'''
return tuple(self._event.subprotocols)
@property
def local(self):
'''
The connection's local endpoint.
:rtype: Endpoint or str
'''
return self._connection.local
@property
def remote(self):
'''
The connection's remote endpoint.
:rtype: Endpoint or str
'''
return self._connection.remote
async def accept(self, *, subprotocol=None, extra_headers=None):
'''
Accept the request and return a connection object.
:param subprotocol: The selected subprotocol for this connection.
:type subprotocol: str or None
:param extra_headers: A list of 2-tuples containing key/value pairs to
send as HTTP headers.
:type extra_headers: list[tuple[bytes,bytes]] or None
:rtype: WebSocketConnection
'''
if extra_headers is None:
extra_headers = []
await self._connection._accept(self._event, subprotocol, extra_headers)
return self._connection
async def reject(self, status_code, *, extra_headers=None, body=None):
'''
Reject the handshake.
:param int status_code: The 3 digit HTTP status code. In order to be
RFC-compliant, this should NOT be 101, and would ideally be an
appropriate code in the range 300-599.
:param list[tuple[bytes,bytes]] extra_headers: A list of 2-tuples
containing key/value pairs to send as HTTP headers.
:param body: If provided, this data will be sent in the response
body, otherwise no response body will be sent.
:type body: bytes or None
'''
extra_headers = extra_headers or []
body = body or b''
await self._connection._reject(status_code, extra_headers, body)
| (connection, event) |
40,262 | trio_websocket._impl | __init__ |
Constructor.
:param WebSocketConnection connection:
:type event: wsproto.events.Request
| def __init__(self, connection, event):
'''
Constructor.
:param WebSocketConnection connection:
:type event: wsproto.events.Request
'''
self._connection = connection
self._event = event
| (self, connection, event) |
40,263 | trio_websocket._impl | accept |
Accept the request and return a connection object.
:param subprotocol: The selected subprotocol for this connection.
:type subprotocol: str or None
:param extra_headers: A list of 2-tuples containing key/value pairs to
send as HTTP headers.
:type extra_headers: list[tuple[bytes,bytes]] or None
:rtype: WebSocketConnection
| @property
def remote(self):
'''
The connection's remote endpoint.
:rtype: Endpoint or str
'''
return self._connection.remote
| (self, *, subprotocol=None, extra_headers=None) |
40,264 | trio_websocket._impl | reject |
Reject the handshake.
:param int status_code: The 3 digit HTTP status code. In order to be
RFC-compliant, this should NOT be 101, and would ideally be an
appropriate code in the range 300-599.
:param list[tuple[bytes,bytes]] extra_headers: A list of 2-tuples
containing key/value pairs to send as HTTP headers.
:param body: If provided, this data will be sent in the response
body, otherwise no response body will be sent.
:type body: bytes or None
| @property
def remote(self):
'''
The connection's remote endpoint.
:rtype: Endpoint or str
'''
return self._connection.remote
| (self, status_code, *, extra_headers=None, body=None) |
40,265 | trio_websocket._impl | WebSocketServer |
WebSocket server.
The server class handles incoming connections on one or more ``Listener``
objects. For each incoming connection, it creates a ``WebSocketConnection``
instance and starts some background tasks,
| class WebSocketServer:
'''
WebSocket server.
The server class handles incoming connections on one or more ``Listener``
objects. For each incoming connection, it creates a ``WebSocketConnection``
instance and starts some background tasks,
'''
def __init__(self, handler, listeners, *, handler_nursery=None,
message_queue_size=MESSAGE_QUEUE_SIZE,
max_message_size=MAX_MESSAGE_SIZE, connect_timeout=CONN_TIMEOUT,
disconnect_timeout=CONN_TIMEOUT):
'''
Constructor.
Note that if ``host`` is ``None`` and ``port`` is zero, then you may get
multiple listeners that have _different port numbers!_ See the
``listeners`` property.
:param handler: the async function called with a :class:`WebSocketRequest`
on each new connection. The call will be made
once the HTTP handshake completes, which notably implies that the
connection's `path` property will be valid.
:param listeners: The WebSocket will be served on each of the listeners.
:param handler_nursery: An optional nursery to spawn connection tasks
inside of. If ``None``, then a new nursery will be created
internally.
:param float connect_timeout: The number of seconds to wait for a client
to finish connection handshake before timing out.
:param float disconnect_timeout: The number of seconds to wait for a client
to finish the closing handshake before timing out.
'''
if len(listeners) == 0:
raise ValueError('Listeners must contain at least one item.')
self._handler = handler
self._handler_nursery = handler_nursery
self._listeners = listeners
self._message_queue_size = message_queue_size
self._max_message_size = max_message_size
self._connect_timeout = connect_timeout
self._disconnect_timeout = disconnect_timeout
@property
def port(self):
"""Returns the requested or kernel-assigned port number.
In the case of kernel-assigned port (requested with port=0 in the
constructor), the assigned port will be reflected after calling
starting the `listen` task. (Technically, once listen reaches the
"started" state.)
This property only works if you have a single listener, and that
listener must be socket-based.
"""
if len(self._listeners) > 1:
raise RuntimeError('Cannot get port because this server has'
' more than 1 listeners.')
listener = self.listeners[0]
try:
return listener.port
except AttributeError:
raise RuntimeError(f'This socket does not have a port: {repr(listener)}') from None
@property
def listeners(self):
'''
Return a list of listener metadata. Each TCP listener is represented as
an ``Endpoint`` instance. Other listener types are represented by their
``repr()``.
:returns: Listeners
:rtype list[Endpoint or str]:
'''
listeners = []
for listener in self._listeners:
socket, is_ssl = None, False
if isinstance(listener, trio.SocketListener):
socket = listener.socket
elif isinstance(listener, trio.SSLListener):
socket = listener.transport_listener.socket
is_ssl = True
if socket:
sockname = socket.getsockname()
listeners.append(Endpoint(sockname[0], sockname[1], is_ssl))
else:
listeners.append(repr(listener))
return listeners
async def run(self, *, task_status=trio.TASK_STATUS_IGNORED):
'''
Start serving incoming connections requests.
This method supports the Trio nursery start protocol: ``server = await
nursery.start(server.run, …)``. It will block until the server is
accepting connections and then return a :class:`WebSocketServer` object.
:param task_status: Part of the Trio nursery start protocol.
:returns: This method never returns unless cancelled.
'''
async with trio.open_nursery() as nursery:
serve_listeners = partial(trio.serve_listeners,
self._handle_connection, self._listeners,
handler_nursery=self._handler_nursery)
await nursery.start(serve_listeners)
logger.debug('Listening on %s',
','.join([str(l) for l in self.listeners]))
task_status.started(self)
await trio.sleep_forever()
async def _handle_connection(self, stream):
'''
Handle an incoming connection by spawning a connection background task
and a handler task inside a new nursery.
:param stream:
:type stream: trio.abc.Stream
'''
async with trio.open_nursery() as nursery:
connection = WebSocketConnection(stream,
WSConnection(ConnectionType.SERVER),
message_queue_size=self._message_queue_size,
max_message_size=self._max_message_size)
nursery.start_soon(connection._reader_task)
with trio.move_on_after(self._connect_timeout) as connect_scope:
request = await connection._get_request()
if connect_scope.cancelled_caught:
nursery.cancel_scope.cancel()
await stream.aclose()
return
try:
await self._handler(request)
finally:
with trio.move_on_after(self._disconnect_timeout):
# aclose() will shut down the reader task even if it's
# cancelled:
await connection.aclose()
| (handler, listeners, *, handler_nursery=None, message_queue_size=1, max_message_size=1048576, connect_timeout=60, disconnect_timeout=60) |
40,266 | trio_websocket._impl | __init__ |
Constructor.
Note that if ``host`` is ``None`` and ``port`` is zero, then you may get
multiple listeners that have _different port numbers!_ See the
``listeners`` property.
:param handler: the async function called with a :class:`WebSocketRequest`
on each new connection. The call will be made
once the HTTP handshake completes, which notably implies that the
connection's `path` property will be valid.
:param listeners: The WebSocket will be served on each of the listeners.
:param handler_nursery: An optional nursery to spawn connection tasks
inside of. If ``None``, then a new nursery will be created
internally.
:param float connect_timeout: The number of seconds to wait for a client
to finish connection handshake before timing out.
:param float disconnect_timeout: The number of seconds to wait for a client
to finish the closing handshake before timing out.
| def __init__(self, handler, listeners, *, handler_nursery=None,
message_queue_size=MESSAGE_QUEUE_SIZE,
max_message_size=MAX_MESSAGE_SIZE, connect_timeout=CONN_TIMEOUT,
disconnect_timeout=CONN_TIMEOUT):
'''
Constructor.
Note that if ``host`` is ``None`` and ``port`` is zero, then you may get
multiple listeners that have _different port numbers!_ See the
``listeners`` property.
:param handler: the async function called with a :class:`WebSocketRequest`
on each new connection. The call will be made
once the HTTP handshake completes, which notably implies that the
connection's `path` property will be valid.
:param listeners: The WebSocket will be served on each of the listeners.
:param handler_nursery: An optional nursery to spawn connection tasks
inside of. If ``None``, then a new nursery will be created
internally.
:param float connect_timeout: The number of seconds to wait for a client
to finish connection handshake before timing out.
:param float disconnect_timeout: The number of seconds to wait for a client
to finish the closing handshake before timing out.
'''
if len(listeners) == 0:
raise ValueError('Listeners must contain at least one item.')
self._handler = handler
self._handler_nursery = handler_nursery
self._listeners = listeners
self._message_queue_size = message_queue_size
self._max_message_size = max_message_size
self._connect_timeout = connect_timeout
self._disconnect_timeout = disconnect_timeout
| (self, handler, listeners, *, handler_nursery=None, message_queue_size=1, max_message_size=1048576, connect_timeout=60, disconnect_timeout=60) |
40,267 | trio_websocket._impl | _handle_connection |
Handle an incoming connection by spawning a connection background task
and a handler task inside a new nursery.
:param stream:
:type stream: trio.abc.Stream
| @property
def listeners(self):
'''
Return a list of listener metadata. Each TCP listener is represented as
an ``Endpoint`` instance. Other listener types are represented by their
``repr()``.
:returns: Listeners
:rtype list[Endpoint or str]:
'''
listeners = []
for listener in self._listeners:
socket, is_ssl = None, False
if isinstance(listener, trio.SocketListener):
socket = listener.socket
elif isinstance(listener, trio.SSLListener):
socket = listener.transport_listener.socket
is_ssl = True
if socket:
sockname = socket.getsockname()
listeners.append(Endpoint(sockname[0], sockname[1], is_ssl))
else:
listeners.append(repr(listener))
return listeners
| (self, stream) |
40,268 | trio_websocket._impl | run |
Start serving incoming connections requests.
This method supports the Trio nursery start protocol: ``server = await
nursery.start(server.run, …)``. It will block until the server is
accepting connections and then return a :class:`WebSocketServer` object.
:param task_status: Part of the Trio nursery start protocol.
:returns: This method never returns unless cancelled.
| @property
def listeners(self):
'''
Return a list of listener metadata. Each TCP listener is represented as
an ``Endpoint`` instance. Other listener types are represented by their
``repr()``.
:returns: Listeners
:rtype list[Endpoint or str]:
'''
listeners = []
for listener in self._listeners:
socket, is_ssl = None, False
if isinstance(listener, trio.SocketListener):
socket = listener.socket
elif isinstance(listener, trio.SSLListener):
socket = listener.transport_listener.socket
is_ssl = True
if socket:
sockname = socket.getsockname()
listeners.append(Endpoint(sockname[0], sockname[1], is_ssl))
else:
listeners.append(repr(listener))
return listeners
| (self, *, task_status=TASK_STATUS_IGNORED) |
40,271 | trio_websocket._impl | connect_websocket |
Return an open WebSocket client connection to a host.
This function is used to specify a custom nursery to run connection
background tasks in. The caller is responsible for closing the connection.
If you don't need a custom nursery, you should probably use
:func:`open_websocket` instead.
:param nursery: A Trio nursery to run background tasks in.
:param str host: The host to connect to.
:param int port: The port to connect to.
:param str resource: The resource, i.e. URL path.
:param Union[bool, ssl.SSLContext] use_ssl: If this is an SSL context, then
use that context. If this is ``True`` then use default SSL context. If
this is ``False`` then disable SSL.
:param subprotocols: An iterable of strings representing preferred
subprotocols.
:param list[tuple[bytes,bytes]] extra_headers: A list of 2-tuples containing
HTTP header key/value pairs to send with the connection request. Note
that headers used by the WebSocket protocol (e.g.
``Sec-WebSocket-Accept``) will be overwritten.
:param int message_queue_size: The maximum number of messages that will be
buffered in the library's internal message queue.
:param int max_message_size: The maximum message size as measured by
``len()``. If a message is received that is larger than this size,
then the connection is closed with code 1009 (Message Too Big).
:rtype: WebSocketConnection
| @asynccontextmanager
async def open_websocket(host, port, resource, *, use_ssl, subprotocols=None,
extra_headers=None,
message_queue_size=MESSAGE_QUEUE_SIZE, max_message_size=MAX_MESSAGE_SIZE,
connect_timeout=CONN_TIMEOUT, disconnect_timeout=CONN_TIMEOUT):
'''
Open a WebSocket client connection to a host.
This async context manager connects when entering the context manager and
disconnects when exiting. It yields a
:class:`WebSocketConnection` instance.
:param str host: The host to connect to.
:param int port: The port to connect to.
:param str resource: The resource, i.e. URL path.
:param Union[bool, ssl.SSLContext] use_ssl: If this is an SSL context, then
use that context. If this is ``True`` then use default SSL context. If
this is ``False`` then disable SSL.
:param subprotocols: An iterable of strings representing preferred
subprotocols.
:param list[tuple[bytes,bytes]] extra_headers: A list of 2-tuples containing
HTTP header key/value pairs to send with the connection request. Note
that headers used by the WebSocket protocol (e.g.
``Sec-WebSocket-Accept``) will be overwritten.
:param int message_queue_size: The maximum number of messages that will be
buffered in the library's internal message queue.
:param int max_message_size: The maximum message size as measured by
``len()``. If a message is received that is larger than this size,
then the connection is closed with code 1009 (Message Too Big).
:param float connect_timeout: The number of seconds to wait for the
connection before timing out.
:param float disconnect_timeout: The number of seconds to wait when closing
the connection before timing out.
:raises HandshakeError: for any networking error,
client-side timeout (:exc:`ConnectionTimeout`, :exc:`DisconnectionTimeout`),
or server rejection (:exc:`ConnectionRejected`) during handshakes.
'''
async with trio.open_nursery() as new_nursery:
try:
with trio.fail_after(connect_timeout):
connection = await connect_websocket(new_nursery, host, port,
resource, use_ssl=use_ssl, subprotocols=subprotocols,
extra_headers=extra_headers,
message_queue_size=message_queue_size,
max_message_size=max_message_size)
except trio.TooSlowError:
raise ConnectionTimeout from None
except OSError as e:
raise HandshakeError from e
try:
yield connection
finally:
try:
with trio.fail_after(disconnect_timeout):
await connection.aclose()
except trio.TooSlowError:
raise DisconnectionTimeout from None
| (nursery, host, port, resource, *, use_ssl, subprotocols=None, extra_headers=None, message_queue_size=1, max_message_size=1048576) |
40,272 | trio_websocket._impl | connect_websocket_url |
Return an open WebSocket client connection to a URL.
This function is used to specify a custom nursery to run connection
background tasks in. The caller is responsible for closing the connection.
If you don't need a custom nursery, you should probably use
:func:`open_websocket_url` instead.
:param nursery: A nursery to run background tasks in.
:param str url: A WebSocket URL.
:param ssl_context: Optional SSL context used for ``wss:`` URLs.
:type ssl_context: ssl.SSLContext or None
:param subprotocols: An iterable of strings representing preferred
subprotocols.
:param list[tuple[bytes,bytes]] extra_headers: A list of 2-tuples containing
HTTP header key/value pairs to send with the connection request. Note
that headers used by the WebSocket protocol (e.g.
``Sec-WebSocket-Accept``) will be overwritten.
:param int message_queue_size: The maximum number of messages that will be
buffered in the library's internal message queue.
:param int max_message_size: The maximum message size as measured by
``len()``. If a message is received that is larger than this size,
then the connection is closed with code 1009 (Message Too Big).
:rtype: WebSocketConnection
| def open_websocket_url(url, ssl_context=None, *, subprotocols=None,
extra_headers=None,
message_queue_size=MESSAGE_QUEUE_SIZE, max_message_size=MAX_MESSAGE_SIZE,
connect_timeout=CONN_TIMEOUT, disconnect_timeout=CONN_TIMEOUT):
'''
Open a WebSocket client connection to a URL.
This async context manager connects when entering the context manager and
disconnects when exiting. It yields a
:class:`WebSocketConnection` instance.
:param str url: A WebSocket URL, i.e. `ws:` or `wss:` URL scheme.
:param ssl_context: Optional SSL context used for ``wss:`` URLs. A default
SSL context is used for ``wss:`` if this argument is ``None``.
:type ssl_context: ssl.SSLContext or None
:param subprotocols: An iterable of strings representing preferred
subprotocols.
:param list[tuple[bytes,bytes]] extra_headers: A list of 2-tuples containing
HTTP header key/value pairs to send with the connection request. Note
that headers used by the WebSocket protocol (e.g.
``Sec-WebSocket-Accept``) will be overwritten.
:param int message_queue_size: The maximum number of messages that will be
buffered in the library's internal message queue.
:param int max_message_size: The maximum message size as measured by
``len()``. If a message is received that is larger than this size,
then the connection is closed with code 1009 (Message Too Big).
:param float connect_timeout: The number of seconds to wait for the
connection before timing out.
:param float disconnect_timeout: The number of seconds to wait when closing
the connection before timing out.
:raises HandshakeError: for any networking error,
client-side timeout (:exc:`ConnectionTimeout`, :exc:`DisconnectionTimeout`),
or server rejection (:exc:`ConnectionRejected`) during handshakes.
'''
host, port, resource, ssl_context = _url_to_host(url, ssl_context)
return open_websocket(host, port, resource, use_ssl=ssl_context,
subprotocols=subprotocols, extra_headers=extra_headers,
message_queue_size=message_queue_size,
max_message_size=max_message_size,
connect_timeout=connect_timeout, disconnect_timeout=disconnect_timeout)
| (nursery, url, ssl_context=None, *, subprotocols=None, extra_headers=None, message_queue_size=1, max_message_size=1048576) |
40,273 | trio_websocket._impl | open_websocket |
Open a WebSocket client connection to a host.
This async context manager connects when entering the context manager and
disconnects when exiting. It yields a
:class:`WebSocketConnection` instance.
:param str host: The host to connect to.
:param int port: The port to connect to.
:param str resource: The resource, i.e. URL path.
:param Union[bool, ssl.SSLContext] use_ssl: If this is an SSL context, then
use that context. If this is ``True`` then use default SSL context. If
this is ``False`` then disable SSL.
:param subprotocols: An iterable of strings representing preferred
subprotocols.
:param list[tuple[bytes,bytes]] extra_headers: A list of 2-tuples containing
HTTP header key/value pairs to send with the connection request. Note
that headers used by the WebSocket protocol (e.g.
``Sec-WebSocket-Accept``) will be overwritten.
:param int message_queue_size: The maximum number of messages that will be
buffered in the library's internal message queue.
:param int max_message_size: The maximum message size as measured by
``len()``. If a message is received that is larger than this size,
then the connection is closed with code 1009 (Message Too Big).
:param float connect_timeout: The number of seconds to wait for the
connection before timing out.
:param float disconnect_timeout: The number of seconds to wait when closing
the connection before timing out.
:raises HandshakeError: for any networking error,
client-side timeout (:exc:`ConnectionTimeout`, :exc:`DisconnectionTimeout`),
or server rejection (:exc:`ConnectionRejected`) during handshakes.
| def _url_to_host(url, ssl_context):
'''
Convert a WebSocket URL to a (host,port,resource) tuple.
The returned ``ssl_context`` is either the same object that was passed in,
or if ``ssl_context`` is None, then a bool indicating if a default SSL
context needs to be created.
:param str url: A WebSocket URL.
:type ssl_context: ssl.SSLContext or None
:returns: A tuple of ``(host, port, resource, ssl_context)``.
'''
url = str(url) # For backward compat with isinstance(url, yarl.URL).
parts = urllib.parse.urlsplit(url)
if parts.scheme not in ('ws', 'wss'):
raise ValueError('WebSocket URL scheme must be "ws:" or "wss:"')
if ssl_context is None:
ssl_context = parts.scheme == 'wss'
elif parts.scheme == 'ws':
raise ValueError('SSL context must be None for ws: URL scheme')
host = parts.hostname
if parts.port is not None:
port = parts.port
else:
port = 443 if ssl_context else 80
path_qs = parts.path
# RFC 7230, Section 5.3.1:
# If the target URI's path component is empty, the client MUST
# send "/" as the path within the origin-form of request-target.
if not path_qs:
path_qs = '/'
if '?' in url:
path_qs += '?' + parts.query
return host, port, path_qs, ssl_context
| (host, port, resource, *, use_ssl, subprotocols=None, extra_headers=None, message_queue_size=1, max_message_size=1048576, connect_timeout=60, disconnect_timeout=60) |
40,274 | trio_websocket._impl | open_websocket_url |
Open a WebSocket client connection to a URL.
This async context manager connects when entering the context manager and
disconnects when exiting. It yields a
:class:`WebSocketConnection` instance.
:param str url: A WebSocket URL, i.e. `ws:` or `wss:` URL scheme.
:param ssl_context: Optional SSL context used for ``wss:`` URLs. A default
SSL context is used for ``wss:`` if this argument is ``None``.
:type ssl_context: ssl.SSLContext or None
:param subprotocols: An iterable of strings representing preferred
subprotocols.
:param list[tuple[bytes,bytes]] extra_headers: A list of 2-tuples containing
HTTP header key/value pairs to send with the connection request. Note
that headers used by the WebSocket protocol (e.g.
``Sec-WebSocket-Accept``) will be overwritten.
:param int message_queue_size: The maximum number of messages that will be
buffered in the library's internal message queue.
:param int max_message_size: The maximum message size as measured by
``len()``. If a message is received that is larger than this size,
then the connection is closed with code 1009 (Message Too Big).
:param float connect_timeout: The number of seconds to wait for the
connection before timing out.
:param float disconnect_timeout: The number of seconds to wait when closing
the connection before timing out.
:raises HandshakeError: for any networking error,
client-side timeout (:exc:`ConnectionTimeout`, :exc:`DisconnectionTimeout`),
or server rejection (:exc:`ConnectionRejected`) during handshakes.
| def open_websocket_url(url, ssl_context=None, *, subprotocols=None,
extra_headers=None,
message_queue_size=MESSAGE_QUEUE_SIZE, max_message_size=MAX_MESSAGE_SIZE,
connect_timeout=CONN_TIMEOUT, disconnect_timeout=CONN_TIMEOUT):
'''
Open a WebSocket client connection to a URL.
This async context manager connects when entering the context manager and
disconnects when exiting. It yields a
:class:`WebSocketConnection` instance.
:param str url: A WebSocket URL, i.e. `ws:` or `wss:` URL scheme.
:param ssl_context: Optional SSL context used for ``wss:`` URLs. A default
SSL context is used for ``wss:`` if this argument is ``None``.
:type ssl_context: ssl.SSLContext or None
:param subprotocols: An iterable of strings representing preferred
subprotocols.
:param list[tuple[bytes,bytes]] extra_headers: A list of 2-tuples containing
HTTP header key/value pairs to send with the connection request. Note
that headers used by the WebSocket protocol (e.g.
``Sec-WebSocket-Accept``) will be overwritten.
:param int message_queue_size: The maximum number of messages that will be
buffered in the library's internal message queue.
:param int max_message_size: The maximum message size as measured by
``len()``. If a message is received that is larger than this size,
then the connection is closed with code 1009 (Message Too Big).
:param float connect_timeout: The number of seconds to wait for the
connection before timing out.
:param float disconnect_timeout: The number of seconds to wait when closing
the connection before timing out.
:raises HandshakeError: for any networking error,
client-side timeout (:exc:`ConnectionTimeout`, :exc:`DisconnectionTimeout`),
or server rejection (:exc:`ConnectionRejected`) during handshakes.
'''
host, port, resource, ssl_context = _url_to_host(url, ssl_context)
return open_websocket(host, port, resource, use_ssl=ssl_context,
subprotocols=subprotocols, extra_headers=extra_headers,
message_queue_size=message_queue_size,
max_message_size=max_message_size,
connect_timeout=connect_timeout, disconnect_timeout=disconnect_timeout)
| (url, ssl_context=None, *, subprotocols=None, extra_headers=None, message_queue_size=1, max_message_size=1048576, connect_timeout=60, disconnect_timeout=60) |
40,275 | trio_websocket._impl | serve_websocket |
Serve a WebSocket over TCP.
This function supports the Trio nursery start protocol: ``server = await
nursery.start(serve_websocket, …)``. It will block until the server
is accepting connections and then return a :class:`WebSocketServer` object.
Note that if ``host`` is ``None`` and ``port`` is zero, then you may get
multiple listeners that have *different port numbers!*
:param handler: An async function that is invoked with a request
for each new connection.
:param host: The host interface to bind. This can be an address of an
interface, a name that resolves to an interface address (e.g.
``localhost``), or a wildcard address like ``0.0.0.0`` for IPv4 or
``::`` for IPv6. If ``None``, then all local interfaces are bound.
:type host: str, bytes, or None
:param int port: The port to bind to.
:param ssl_context: The SSL context to use for encrypted connections, or
``None`` for unencrypted connection.
:type ssl_context: ssl.SSLContext or None
:param handler_nursery: An optional nursery to spawn handlers and background
tasks in. If not specified, a new nursery will be created internally.
:param int message_queue_size: The maximum number of messages that will be
buffered in the library's internal message queue.
:param int max_message_size: The maximum message size as measured by
``len()``. If a message is received that is larger than this size,
then the connection is closed with code 1009 (Message Too Big).
:param float connect_timeout: The number of seconds to wait for a client
to finish connection handshake before timing out.
:param float disconnect_timeout: The number of seconds to wait for a client
to finish the closing handshake before timing out.
:param task_status: Part of Trio nursery start protocol.
:returns: This function runs until cancelled.
| def _url_to_host(url, ssl_context):
'''
Convert a WebSocket URL to a (host,port,resource) tuple.
The returned ``ssl_context`` is either the same object that was passed in,
or if ``ssl_context`` is None, then a bool indicating if a default SSL
context needs to be created.
:param str url: A WebSocket URL.
:type ssl_context: ssl.SSLContext or None
:returns: A tuple of ``(host, port, resource, ssl_context)``.
'''
url = str(url) # For backward compat with isinstance(url, yarl.URL).
parts = urllib.parse.urlsplit(url)
if parts.scheme not in ('ws', 'wss'):
raise ValueError('WebSocket URL scheme must be "ws:" or "wss:"')
if ssl_context is None:
ssl_context = parts.scheme == 'wss'
elif parts.scheme == 'ws':
raise ValueError('SSL context must be None for ws: URL scheme')
host = parts.hostname
if parts.port is not None:
port = parts.port
else:
port = 443 if ssl_context else 80
path_qs = parts.path
# RFC 7230, Section 5.3.1:
# If the target URI's path component is empty, the client MUST
# send "/" as the path within the origin-form of request-target.
if not path_qs:
path_qs = '/'
if '?' in url:
path_qs += '?' + parts.query
return host, port, path_qs, ssl_context
| (handler, host, port, ssl_context, *, handler_nursery=None, message_queue_size=1, max_message_size=1048576, connect_timeout=60, disconnect_timeout=60, task_status=TASK_STATUS_IGNORED) |
40,276 | trio_websocket._impl | wrap_client_stream |
Wrap an arbitrary stream in a WebSocket connection.
This is a low-level function only needed in rare cases. In most cases, you
should use :func:`open_websocket` or :func:`open_websocket_url`.
:param nursery: A Trio nursery to run background tasks in.
:param stream: A Trio stream to be wrapped.
:type stream: trio.abc.Stream
:param str host: A host string that will be sent in the ``Host:`` header.
:param str resource: A resource string, i.e. the path component to be
accessed on the server.
:param subprotocols: An iterable of strings representing preferred
subprotocols.
:param list[tuple[bytes,bytes]] extra_headers: A list of 2-tuples containing
HTTP header key/value pairs to send with the connection request. Note
that headers used by the WebSocket protocol (e.g.
``Sec-WebSocket-Accept``) will be overwritten.
:param int message_queue_size: The maximum number of messages that will be
buffered in the library's internal message queue.
:param int max_message_size: The maximum message size as measured by
``len()``. If a message is received that is larger than this size,
then the connection is closed with code 1009 (Message Too Big).
:rtype: WebSocketConnection
| def _url_to_host(url, ssl_context):
'''
Convert a WebSocket URL to a (host,port,resource) tuple.
The returned ``ssl_context`` is either the same object that was passed in,
or if ``ssl_context`` is None, then a bool indicating if a default SSL
context needs to be created.
:param str url: A WebSocket URL.
:type ssl_context: ssl.SSLContext or None
:returns: A tuple of ``(host, port, resource, ssl_context)``.
'''
url = str(url) # For backward compat with isinstance(url, yarl.URL).
parts = urllib.parse.urlsplit(url)
if parts.scheme not in ('ws', 'wss'):
raise ValueError('WebSocket URL scheme must be "ws:" or "wss:"')
if ssl_context is None:
ssl_context = parts.scheme == 'wss'
elif parts.scheme == 'ws':
raise ValueError('SSL context must be None for ws: URL scheme')
host = parts.hostname
if parts.port is not None:
port = parts.port
else:
port = 443 if ssl_context else 80
path_qs = parts.path
# RFC 7230, Section 5.3.1:
# If the target URI's path component is empty, the client MUST
# send "/" as the path within the origin-form of request-target.
if not path_qs:
path_qs = '/'
if '?' in url:
path_qs += '?' + parts.query
return host, port, path_qs, ssl_context
| (nursery, stream, host, resource, *, subprotocols=None, extra_headers=None, message_queue_size=1, max_message_size=1048576) |
40,277 | trio_websocket._impl | wrap_server_stream |
Wrap an arbitrary stream in a server-side WebSocket.
This is a low-level function only needed in rare cases. In most cases, you
should use :func:`serve_websocket`.
:param nursery: A nursery to run background tasks in.
:param stream: A stream to be wrapped.
:param int message_queue_size: The maximum number of messages that will be
buffered in the library's internal message queue.
:param int max_message_size: The maximum message size as measured by
``len()``. If a message is received that is larger than this size,
then the connection is closed with code 1009 (Message Too Big).
:type stream: trio.abc.Stream
:rtype: WebSocketRequest
| def _url_to_host(url, ssl_context):
'''
Convert a WebSocket URL to a (host,port,resource) tuple.
The returned ``ssl_context`` is either the same object that was passed in,
or if ``ssl_context`` is None, then a bool indicating if a default SSL
context needs to be created.
:param str url: A WebSocket URL.
:type ssl_context: ssl.SSLContext or None
:returns: A tuple of ``(host, port, resource, ssl_context)``.
'''
url = str(url) # For backward compat with isinstance(url, yarl.URL).
parts = urllib.parse.urlsplit(url)
if parts.scheme not in ('ws', 'wss'):
raise ValueError('WebSocket URL scheme must be "ws:" or "wss:"')
if ssl_context is None:
ssl_context = parts.scheme == 'wss'
elif parts.scheme == 'ws':
raise ValueError('SSL context must be None for ws: URL scheme')
host = parts.hostname
if parts.port is not None:
port = parts.port
else:
port = 443 if ssl_context else 80
path_qs = parts.path
# RFC 7230, Section 5.3.1:
# If the target URI's path component is empty, the client MUST
# send "/" as the path within the origin-form of request-target.
if not path_qs:
path_qs = '/'
if '?' in url:
path_qs += '?' + parts.query
return host, port, path_qs, ssl_context
| (nursery, stream, message_queue_size=1, max_message_size=1048576) |
40,278 | pyglove.core.symbolic.class_wrapper | ClassWrapper | Base class for symbolic class wrapper.
Please see :func:`pyglove.wrap` for details.
| class ClassWrapper(pg_object.Object, metaclass=ClassWrapperMeta):
"""Base class for symbolic class wrapper.
Please see :func:`pyglove.wrap` for details.
"""
@property
@abc.abstractmethod
def sym_wrapped(self):
"""Returns symbolically wrapped object."""
| () |
40,279 | pyglove.core.typing.type_conversion | get_json_value_converter | Get converter from source type to a JSON simple type. | def get_json_value_converter(src: Type[Any]) -> Optional[Callable[[Any], Any]]:
"""Get converter from source type to a JSON simple type."""
return _TYPE_CONVERTER_REGISTRY.get_json_value_converter(src)
| (src: Type[Any]) -> Optional[Callable[[Any], Any]] |
40,280 | pyglove.core.symbolic.base | __copy__ | Overridden shallow copy. | def __copy__(self) -> 'Symbolic':
"""Overridden shallow copy."""
return self.sym_clone(deep=False)
| (self) -> pyglove.core.symbolic.base.Symbolic |
40,281 | pyglove.core.symbolic.base | __deepcopy__ | Overridden deep copy. | def __deepcopy__(self, memo) -> 'Symbolic':
"""Overridden deep copy."""
return self.sym_clone(deep=True, memo=memo)
| (self, memo) -> pyglove.core.symbolic.base.Symbolic |
40,282 | pyglove.core.symbolic.object | __eq__ | Operator==. | def __eq__(self, other: Any) -> bool:
"""Operator==."""
if self.use_symbolic_comparison:
return self.sym_eq(other)
return super().__eq__(other)
| (self, other: Any) -> bool |
40,283 | pyglove.core.symbolic.object | __getattribute__ | Override to accomondate symbolic attributes with variable keys. | def __getattribute__(self, name: str) -> Any:
"""Override to accomondate symbolic attributes with variable keys."""
try:
return super().__getattribute__(name)
except AttributeError as error:
if not self.allow_symbolic_attribute or not self.sym_hasattr(name):
raise error
return self.sym_inferred(name)
| (self, name: str) -> Any |
40,284 | pyglove.core.symbolic.object | __getstate__ | Customizes pickle.dump. | def __getstate__(self) -> Dict[str, Any]:
"""Customizes pickle.dump."""
return dict(kwargs=self._init_kwargs())
| (self) -> Dict[str, Any] |
40,285 | pyglove.core.symbolic.object | __hash__ | Hashing function. | def __hash__(self) -> int:
"""Hashing function."""
if self.use_symbolic_comparison:
return self.sym_hash()
return super().__hash__()
| (self) -> int |
40,286 | pyglove.core.symbolic.class_wrapper | __init__ | null | def wrap(
cls,
init_args: Optional[List[Union[
Tuple[Union[Text, pg_typing.KeySpec], pg_typing.ValueSpec, Text],
Tuple[Union[Text, pg_typing.KeySpec], pg_typing.ValueSpec, Text, Any]
]]] = None,
*,
reset_state_fn: Optional[Callable[[Any], None]] = None,
repr: bool = True, # pylint: disable=redefined-builtin
eq: bool = False,
class_name: Optional[str] = None,
module_name: Optional[str] = None,
auto_doc: bool = False,
auto_typing: bool = False,
serialization_key: Optional[str] = None,
additional_keys: Optional[List[str]] = None,
override: Optional[Dict[str, Any]] = None
) -> Type['ClassWrapper']:
"""Makes a symbolic class wrapper from a regular Python class.
``pg.wrap`` is called by :func:`pyglove.symbolize` for symbolizing existing
Python classes. For example::
class A:
def __init__(self, x):
self.x = x
# The following two lines are equivalent.
A1 = pg.symbolize(A)
A2 = pg.wrap(A)
Besides passing the source class, ``pg.wrap`` allows the user to pass symbolic
field definitions for the init arguments. For example::
A3 = pg.wrap(A, [
('x', pg.typing.Int())
])
Moreover, multiple flags are provided to determine whether or not to use the
symbolic operations as the default behaviors. For example::
A4 = pg.wrap(
A,
[],
# Instead clearing out all internal states (default),
# do not reset internal state.
reset_state_fn=lambda self: None,
# Use symbolic representation for __repr__ and __str__.
repr=True,
# use symbolic equality for __eq__, __ne__ and __hash__.
eq=True,
# Customize the class name obtained (the default behaivor
# is to use the source class name).
class_name='A4'
# Customize the module name for created class (the default
# behavior is to use the source module name).
module_name='my_module')
Args:
cls: Class to wrap.
init_args: An optional list of field definitions for the arguments of
__init__. It can be a sparse value specifications for argument in the
__init__ method of `cls`.
reset_state_fn: An optional callable object to reset the internal state of
the user class when rebind happens.
repr: Options for generating `__repr__` and `__str__`. If True (default),
use symbolic representation if the user class does not define its own.
Otherwise use the user class' definition. If False, always use
non-symbolic representations, which falls back to `object.__repr__` and
`object.__str__` if the user class does not define them.
eq: Options for generating `__eq__`, `__ne__` and `__hash__`. If True and
the `user_cls` defines `__eq__`, `__ne__` and `__hash__`, use the
definitions from the `user_cls`. If True and the `user_cls` does not
define `__eq__`, `__ne__` and `__hash__`, use symbolic eq/hash. If False
(default), use `user_cls`'s definition if present, or the definitions from
the `object` class.
class_name: An optional string used as class name for the wrapper class. If
None, the wrapper class will use the class name of the wrapped class.
module_name: An optional string used as module name for the wrapper class.
If None, the wrapper class will use the module name of the wrapped class.
auto_doc: If True, the descriptions for init argument fields will be
extracted from docstring if present.
auto_typing: If True, PyGlove typing (runtime-typing) will be enabled based
on type annotations inspected from the `__init__` method.
serialization_key: An optional string to be used as the serialization key
for the class during `sym_jsonify`. If None, `cls.__type_name__` will be
used. This is introduced for scenarios when we want to relocate a class,
before the downstream can recognize the new location, we need the class to
serialize it using previous key.
additional_keys: An optional list of strings as additional keys to
deserialize an object of the registered class. This can be useful when we
need to relocate or rename the registered class while being able to load
existing serialized JSON values.
override: Additional class attributes to override.
Returns:
A subclass of `cls` and `ClassWrapper`.
Raises:
TypeError: input `cls` is not a class.
"""
if not inspect.isclass(cls):
raise TypeError(f'Class wrapper can only be created from classes. '
f'Encountered: {cls!r}.')
if not issubclass(cls, ClassWrapper):
cls = _subclassed_wrapper(
cls,
use_symbolic_repr=repr,
use_symbolic_comp=eq,
reset_state_fn=reset_state_fn,
class_name=class_name,
module_name=module_name,
use_auto_doc=auto_doc,
use_auto_typing=auto_typing)
if issubclass(cls, ClassWrapper):
# Update init argument specifications according to user specified specs.
# Replace schema instead of extending it.
description, init_arg_list, arg_fields = _extract_init_signature(
cls, init_args, auto_doc=auto_doc, auto_typing=auto_typing)
schema_utils.update_schema(
cls,
arg_fields,
init_arg_list=init_arg_list,
extend=False,
description=description,
serialization_key=serialization_key,
additional_keys=additional_keys)
if override:
for k, v in override.items():
setattr(cls, k, v)
return cls
| (self) |
40,287 | pyglove.core.symbolic.object | __ne__ | Operator!=. | def __ne__(self, other: Any) -> bool:
"""Operator!=."""
r = self.__eq__(other)
if r is NotImplemented:
return r
return not r
| (self, other: Any) -> bool |
40,288 | pyglove.core.object_utils.common_traits | __repr__ | Returns a single-line representation of this object. | def __repr__(self) -> str:
"""Returns a single-line representation of this object."""
kwargs = dict(self.__repr_format_kwargs__)
kwargs.update(thread_local.thread_local_kwargs(_TLS_REPR_FORMAT_KWARGS))
return self._maybe_quote(self.format(**kwargs), **kwargs)
| (self) -> str |
40,289 | pyglove.core.symbolic.object | __setattr__ | Set field value by attribute. | def __setattr__(self, name: str, value: Any) -> None:
"""Set field value by attribute."""
# NOTE(daiyip): two types of members are treated as regular members:
# 1) All private members which prefixed with '_'.
# 2) Public members that are not declared as symbolic members.
if (
not self.allow_symbolic_attribute
or not self.__class__.__schema__.get_field(name)
or name.startswith('_')
):
super().__setattr__(name, value)
else:
if base.treats_as_sealed(self):
raise base.WritePermissionError(
self._error_message(
f'Cannot set attribute {name!r}: object is sealed.'))
if not base.writtable_via_accessors(self):
raise base.WritePermissionError(
self._error_message(
f'Cannot set attribute of <class {self.__class__.__name__}> '
f'while `{self.__class__.__name__}.allow_symbolic_assignment` '
f'is set to False or under `pg.as_sealed` context.'))
self._sym_attributes[name] = value
| (self, name: str, value: Any) -> NoneType |
40,290 | pyglove.core.symbolic.object | __setstate__ | Customizes pickle.load. | def __setstate__(self, state) -> None:
"""Customizes pickle.load."""
self.__init__(**state['kwargs'])
| (self, state) -> NoneType |
40,291 | pyglove.core.object_utils.common_traits | __str__ | Returns the full (maybe multi-line) representation of this object. | def __str__(self) -> str:
"""Returns the full (maybe multi-line) representation of this object."""
kwargs = dict(self.__str_format_kwargs__)
kwargs.update(thread_local.thread_local_kwargs(_TLS_STR_FORMAT_KWARGS))
return self._maybe_quote(self.format(**kwargs), **kwargs)
| (self) -> str |
40,292 | pyglove.core.symbolic.base | _error_message | Create error message to include path information. | def _error_message(self, message: str) -> str:
"""Create error message to include path information."""
return object_utils.message_on_path(message, self.sym_path)
| (self, message: str) -> str |
40,293 | pyglove.core.symbolic.object | _init_kwargs | null | def _init_kwargs(self) -> typing.Dict[str, Any]:
kwargs = super()._init_kwargs()
kwargs.update(self._sym_attributes)
return kwargs
| (self) -> Dict[str, Any] |
40,294 | pyglove.core.object_utils.common_traits | _maybe_quote | Maybe quote the formatted string with markdown. | def _maybe_quote(
self,
s: str,
*,
compact: bool = False,
root_indent: int = 0,
markdown: bool = False,
**kwargs
) -> str:
"""Maybe quote the formatted string with markdown."""
del kwargs
if not markdown or root_indent > 0:
return s
if compact:
return f'`{s}`'
else:
return f'\n```\n{s}\n```\n'
| (self, s: str, *, compact: bool = False, root_indent: int = 0, markdown: bool = False, **kwargs) -> str |
40,295 | pyglove.core.symbolic.base | _notify_field_updates | Notify field updates. | def _notify_field_updates(
self,
field_updates: List[FieldUpdate],
notify_parents: bool = True) -> None:
"""Notify field updates."""
per_target_updates = dict()
def _get_target_updates(
target: 'Symbolic'
) -> Dict[object_utils.KeyPath, FieldUpdate]:
target_id = id(target)
if target_id not in per_target_updates:
per_target_updates[target_id] = (target, dict())
return per_target_updates[target_id][1]
for update in field_updates:
target = update.target
while target is not None:
target_updates = _get_target_updates(target)
if target._subscribes_field_updates: # pylint: disable=protected-access
relative_path = update.path - target.sym_path
target_updates[relative_path] = update
target = target.sym_parent
# Trigger the notification bottom-up, thus the parent node will always
# be notified after the child nodes.
for target, updates in sorted(per_target_updates.values(),
key=lambda x: x[0].sym_path,
reverse=True):
# Reset content-based cache for the object being notified.
target._set_raw_attr('_sym_puresymbolic', None) # pylint: disable=protected-access
target._set_raw_attr('_sym_missing_values', None) # pylint: disable=protected-access
target._set_raw_attr('_sym_nondefault_values', None) # pylint: disable=protected-access
target._on_change(updates) # pylint: disable=protected-access
# If `notify_parents` is set to False, stop notifications once `self`
# is processed.
if target is self and not notify_parents:
break
| (self, field_updates: List[pyglove.core.symbolic.base.FieldUpdate], notify_parents: bool = True) -> NoneType |
40,296 | pyglove.core.symbolic.object | _on_bound | Event that is triggered when any value in the subtree are set/updated.
NOTE(daiyip): This is the best place to set derived members from members
registered by the schema. It's called when any value in the sub-tree is
modified, thus making sure derived members are up-to-date.
When derived members are expensive to create/update, you can implement
_init, _on_rebound, _on_subtree_rebound to update derived members only when
they are impacted.
_on_bound is not called on per-field basis, it's called at most once
during a rebind call (though many fields may be updated)
and during __init__.
| def _on_bound(self) -> None:
"""Event that is triggered when any value in the subtree are set/updated.
NOTE(daiyip): This is the best place to set derived members from members
registered by the schema. It's called when any value in the sub-tree is
modified, thus making sure derived members are up-to-date.
When derived members are expensive to create/update, you can implement
_init, _on_rebound, _on_subtree_rebound to update derived members only when
they are impacted.
_on_bound is not called on per-field basis, it's called at most once
during a rebind call (though many fields may be updated)
and during __init__.
"""
| (self) -> NoneType |
40,297 | pyglove.core.symbolic.object | _on_change | Event that is triggered when field values in the subtree are updated.
This event will be called
* On per-field basis when object is modified via attribute.
* In batch when multiple fields are modified via `rebind` method.
When a field in an object tree is updated, all ancestors' `_on_change` event
will be triggered in order, from the nearest one to furthest one.
Args:
field_updates: Updates made to the subtree. Key path is relative to
current object.
Returns:
it will call `_on_bound` and return the return value of `_on_bound`.
| def _on_change(self,
field_updates: Dict[object_utils.KeyPath, base.FieldUpdate]):
"""Event that is triggered when field values in the subtree are updated.
This event will be called
* On per-field basis when object is modified via attribute.
* In batch when multiple fields are modified via `rebind` method.
When a field in an object tree is updated, all ancestors' `_on_change` event
will be triggered in order, from the nearest one to furthest one.
Args:
field_updates: Updates made to the subtree. Key path is relative to
current object.
Returns:
it will call `_on_bound` and return the return value of `_on_bound`.
"""
del field_updates
return self._on_bound()
| (self, field_updates: Dict[pyglove.core.object_utils.value_location.KeyPath, pyglove.core.symbolic.base.FieldUpdate]) |
40,298 | pyglove.core.symbolic.object | _on_init | Event that is triggered at then end of __init__. | def _on_init(self):
"""Event that is triggered at then end of __init__."""
self._on_bound()
| (self) |
40,299 | pyglove.core.symbolic.object | _on_parent_change | Event that is triggered after the symbolic parent changes. | def _on_parent_change(
self,
old_parent: Optional[base.Symbolic],
new_parent: Optional[base.Symbolic]):
"""Event that is triggered after the symbolic parent changes."""
del old_parent, new_parent
| (self, old_parent: Optional[pyglove.core.symbolic.base.Symbolic], new_parent: Optional[pyglove.core.symbolic.base.Symbolic]) |
40,300 | pyglove.core.symbolic.object | _on_path_change | Event that is triggered after the symbolic path changes. | def _on_path_change(
self, old_path: object_utils.KeyPath, new_path: object_utils.KeyPath):
"""Event that is triggered after the symbolic path changes."""
del old_path, new_path
| (self, old_path: pyglove.core.object_utils.value_location.KeyPath, new_path: pyglove.core.object_utils.value_location.KeyPath) |
40,301 | pyglove.core.symbolic.base | _relocate_if_symbolic | Relocate if a symbolic value is to be inserted as member.
NOTE(daiyip): when a symbolic value is inserted into the object tree,
if it already has a parent, we need to make a shallow copy of this object
to avoid multiple parents. Otherwise we need to set its parent and root_path
according to current object.
Args:
key: Key used to insert the value.
value: formal value to be inserted.
Returns:
Formalized value that is ready for insertion as members.
| def _relocate_if_symbolic(self, key: Union[str, int], value: Any) -> Any:
"""Relocate if a symbolic value is to be inserted as member.
NOTE(daiyip): when a symbolic value is inserted into the object tree,
if it already has a parent, we need to make a shallow copy of this object
to avoid multiple parents. Otherwise we need to set its parent and root_path
according to current object.
Args:
key: Key used to insert the value.
value: formal value to be inserted.
Returns:
Formalized value that is ready for insertion as members.
"""
if isinstance(value, Symbolic):
# NOTE(daiyip): make a copy of symbolic object if it belongs to another
# object tree, this prevents it from having multiple parents. See
# List._formalized_value for similar logic.
root_path = object_utils.KeyPath(key, self.sym_path)
if (value.sym_parent is not None and
(value.sym_parent is not self
or root_path != value.sym_path)):
value = value.clone()
if isinstance(value, TopologyAware):
value.sym_setpath(object_utils.KeyPath(key, self.sym_path))
value.sym_setparent(self._sym_parent_for_children())
return value
| (self, key: Union[str, int], value: Any) -> Any |
40,302 | pyglove.core.symbolic.base | _set_item_of_current_tree | Set a field of current tree by key path and return its parent. | def _set_item_of_current_tree(
self, path: object_utils.KeyPath, value: Any) -> Optional[FieldUpdate]:
"""Set a field of current tree by key path and return its parent."""
assert isinstance(path, object_utils.KeyPath), path
if not path:
raise KeyError(
self._error_message(
f'Root key \'$\' cannot be used in '
f'{self.__class__.__name__}.rebind. '
f'Encountered {path!r}'))
parent_node = path.parent.query(self)
if not isinstance(parent_node, Symbolic):
raise KeyError(
f'Cannot rebind key {path.key!r}: {parent_node!r} is not a '
f'symbolic type. (path=\'{path.parent}\')')
if treats_as_sealed(parent_node):
raise WritePermissionError(
f'Cannot rebind key {path.key!r} of '
f'sealed {parent_node.__class__.__name__}: {parent_node!r}. '
f'(path=\'{path.parent}\')')
return parent_node._set_item_without_permission_check(path.key, value) # pylint: disable=protected-access
| (self, path: pyglove.core.object_utils.value_location.KeyPath, value: Any) -> Optional[pyglove.core.symbolic.base.FieldUpdate] |
40,303 | pyglove.core.symbolic.object | _set_item_without_permission_check | Set item without permission check. | def _set_item_without_permission_check( # pytype: disable=signature-mismatch # overriding-parameter-type-checks
self, key: str, value: Any) -> Optional[base.FieldUpdate]:
"""Set item without permission check."""
return self._sym_attributes._set_item_without_permission_check(key, value) # pylint: disable=protected-access
| (self, key: str, value: Any) -> Optional[pyglove.core.symbolic.base.FieldUpdate] |
40,304 | pyglove.core.symbolic.base | _set_raw_attr | Set raw property without trigger __setattr__. | def _set_raw_attr(self, name: str, value: Any) -> 'Symbolic':
"""Set raw property without trigger __setattr__."""
# `object.__setattr__` adds a property to the instance without side effects.
object.__setattr__(self, name, value)
return self
| (self, name: str, value: Any) -> pyglove.core.symbolic.base.Symbolic |
40,305 | pyglove.core.symbolic.object | _sym_clone | Copy flags. | def _sym_clone(self, deep: bool, memo: Any = None) -> 'Object':
"""Copy flags."""
kwargs = dict()
for k, v in self._sym_attributes.sym_items():
if deep or isinstance(v, base.Symbolic):
v = base.clone(v, deep, memo)
kwargs[k] = v
return self.__class__(allow_partial=self._allow_partial,
sealed=self._sealed,
**kwargs) # pytype: disable=not-instantiable
| (self, deep: bool, memo: Optional[Any] = None) -> pyglove.core.symbolic.object.Object |
40,306 | pyglove.core.symbolic.object | _sym_getattr | Get symbolic field by key. | def _sym_getattr( # pytype: disable=signature-mismatch # overriding-parameter-type-checks
self, key: str) -> Any:
"""Get symbolic field by key."""
return self._sym_attributes.sym_getattr(key)
| (self, key: str) -> Any |
40,307 | pyglove.core.symbolic.base | _sym_inferred | null | def _sym_inferred(self, key: Union[str, int], **kwargs) -> Any:
v = self.sym_getattr(key)
if isinstance(v, Inferential):
v = v.infer(**kwargs)
return v
| (self, key: Union[str, int], **kwargs) -> Any |
40,308 | pyglove.core.symbolic.object | _sym_missing | Returns missing values. | def _sym_missing(self) -> Dict[str, Any]:
"""Returns missing values."""
# Invalidate the cache of child attributes' missing values before calling
# `Dict.sym_missing`.
setattr(self._sym_attributes, '_sym_missing_values', None)
return self._sym_attributes.sym_missing(flatten=False)
| (self) -> Dict[str, Any] |
40,309 | pyglove.core.symbolic.object | _sym_nondefault | Returns non-default values. | def _sym_nondefault(self) -> Dict[str, Any]:
"""Returns non-default values."""
# Invalidate the cache of child attributes' non-default values before
# calling `Dict.sym_nondefault`.
setattr(self._sym_attributes, '_sym_nondefault_values', None)
return self._sym_attributes.sym_nondefault(flatten=False)
| (self) -> Dict[str, Any] |
40,310 | pyglove.core.symbolic.base | _sym_parent_for_children | Returns the symbolic parent for children. | def _sym_parent_for_children(self) -> Optional['Symbolic']:
"""Returns the symbolic parent for children."""
return self
| (self) -> Optional[pyglove.core.symbolic.base.Symbolic] |
40,311 | pyglove.core.symbolic.object | _sym_rebind | Rebind current object using object-form members. | def _sym_rebind(
self, path_value_pairs: Dict[object_utils.KeyPath, Any]
) -> List[base.FieldUpdate]:
"""Rebind current object using object-form members."""
if base.treats_as_sealed(self):
raise base.WritePermissionError(
f'Cannot rebind a sealed {self.__class__.__name__}.')
return self._sym_attributes._sym_rebind(path_value_pairs) # pylint: disable=protected-access
| (self, path_value_pairs: Dict[pyglove.core.object_utils.value_location.KeyPath, Any]) -> List[pyglove.core.symbolic.base.FieldUpdate] |
40,312 | pyglove.core.symbolic.object | _update_children_paths | Update children paths according to root_path of current node. | def _update_children_paths(
self,
old_path: object_utils.KeyPath,
new_path: object_utils.KeyPath) -> None:
"""Update children paths according to root_path of current node."""
self._sym_attributes.sym_setpath(new_path)
self._on_path_change(old_path, new_path)
| (self, old_path: pyglove.core.object_utils.value_location.KeyPath, new_path: pyglove.core.object_utils.value_location.KeyPath) -> NoneType |
40,313 | pyglove.core.symbolic.base | clone | Clones current object symbolically.
Args:
deep: If True, perform deep copy (equivalent to copy.deepcopy). Otherwise
shallow copy (equivalent to copy.copy).
memo: Memo object for deep clone.
override: An optional dict of key path to new values to override cloned
value.
Returns:
A copy of self.
| def clone(
self,
deep: bool = False,
memo: Optional[Any] = None,
override: Optional[Dict[str, Any]] = None
) -> 'Symbolic':
"""Clones current object symbolically.
Args:
deep: If True, perform deep copy (equivalent to copy.deepcopy). Otherwise
shallow copy (equivalent to copy.copy).
memo: Memo object for deep clone.
override: An optional dict of key path to new values to override cloned
value.
Returns:
A copy of self.
"""
return self.sym_clone(deep, memo, override)
| (self, deep: bool = False, memo: Optional[Any] = None, override: Optional[Dict[str, Any]] = None) -> pyglove.core.symbolic.base.Symbolic |
40,314 | pyglove.core.symbolic.object | format | Formats this object. | def format(self,
compact: bool = False,
verbose: bool = False,
root_indent: int = 0,
**kwargs) -> str:
"""Formats this object."""
return self._sym_attributes.format(
compact,
verbose,
root_indent,
cls_name=self.__class__.__name__,
key_as_attribute=True,
bracket_type=object_utils.BracketType.ROUND,
**kwargs)
| (self, compact: bool = False, verbose: bool = False, root_indent: int = 0, **kwargs) -> str |
40,315 | pyglove.core.symbolic.base | inspect | Inspects current object by printing out selected values.
Example::
@pg.members([
('x', pg.typing.Int(0)),
('y', pg.typing.Str())
])
class A(pg.Object):
pass
value = {
'a1': A(x=0, y=0),
'a2': [A(x=1, y=1), A(x=1, y=2)],
'a3': {
'p': A(x=2, y=1),
'q': A(x=2, y=2)
}
}
# Inspect without constraint,
# which is equivalent as `print(value.format(hide_default_values=True))`
# Shall print:
# {
# a1 = A(y=0)
# a2 = [
# 0: A(x=1, y=1)
# 1: A(x=1, y=2)
# a3 = {
# p = A(x=2, y=1)
# q = A(x=2, y=2)
# }
# }
value.inspect(hide_default_values=True)
# Inspect by path regex.
# Shall print:
# {'a3.p': A(x=2, y=1)}
value.inspect(r'.*p')
# Inspect by value.
# Shall print:
# {
# 'a3.p.x': 2,
# 'a3.q.x': 2,
# 'a3.q.y': 2,
# }
value.inspect(where=lambda v: v==2)
# Inspect by path, value and parent.
# Shall print:
# {
# 'a2[1].y': 2
# }
value.inspect(
r'.*y', where=lambda v, p: v > 1 and isinstance(p, A) and p.x == 1))
# Inspect by custom_selector.
# Shall print:
# {
# 'a2[0].x': 1,
# 'a2[0].y': 1,
# 'a3.q.x': 2,
# 'a3.q.y': 2
# }
value.inspect(
custom_selector=lambda k, v, p: (
len(k) == 3 and isinstance(p, A) and p.x == v))
Args:
path_regex: Optional regex expression to constrain path.
where: Optional callable to constrain value and parent when path matches
`path_regex` or `path_regex` is not provided. The signature is:
`(value) -> should_select`, or `(value, parent) -> should_select`.
custom_selector: Optional callable object as custom selector. When
`custom_selector` is provided, `path_regex` and `where` must be None.
The signature of `custom_selector` is:
`(key_path, value) -> should_select`
or `(key_path, value, parent) -> should_select`.
file: Output file stream. This can be any object with a `write(str)`
method.
**kwargs: Wildcard keyword arguments to pass to `format`.
| def inspect(
self,
path_regex: Optional[str] = None,
where: Optional[Union[Callable[[Any], bool],
Callable[[Any, Any], bool]]] = None,
custom_selector: Optional[Union[
Callable[[object_utils.KeyPath, Any], bool],
Callable[[object_utils.KeyPath, Any, Any], bool]]] = None,
file=sys.stdout, # pylint: disable=redefined-builtin
**kwargs) -> None:
"""Inspects current object by printing out selected values.
Example::
@pg.members([
('x', pg.typing.Int(0)),
('y', pg.typing.Str())
])
class A(pg.Object):
pass
value = {
'a1': A(x=0, y=0),
'a2': [A(x=1, y=1), A(x=1, y=2)],
'a3': {
'p': A(x=2, y=1),
'q': A(x=2, y=2)
}
}
# Inspect without constraint,
# which is equivalent as `print(value.format(hide_default_values=True))`
# Shall print:
# {
# a1 = A(y=0)
# a2 = [
# 0: A(x=1, y=1)
# 1: A(x=1, y=2)
# a3 = {
# p = A(x=2, y=1)
# q = A(x=2, y=2)
# }
# }
value.inspect(hide_default_values=True)
# Inspect by path regex.
# Shall print:
# {'a3.p': A(x=2, y=1)}
value.inspect(r'.*p')
# Inspect by value.
# Shall print:
# {
# 'a3.p.x': 2,
# 'a3.q.x': 2,
# 'a3.q.y': 2,
# }
value.inspect(where=lambda v: v==2)
# Inspect by path, value and parent.
# Shall print:
# {
# 'a2[1].y': 2
# }
value.inspect(
r'.*y', where=lambda v, p: v > 1 and isinstance(p, A) and p.x == 1))
# Inspect by custom_selector.
# Shall print:
# {
# 'a2[0].x': 1,
# 'a2[0].y': 1,
# 'a3.q.x': 2,
# 'a3.q.y': 2
# }
value.inspect(
custom_selector=lambda k, v, p: (
len(k) == 3 and isinstance(p, A) and p.x == v))
Args:
path_regex: Optional regex expression to constrain path.
where: Optional callable to constrain value and parent when path matches
`path_regex` or `path_regex` is not provided. The signature is:
`(value) -> should_select`, or `(value, parent) -> should_select`.
custom_selector: Optional callable object as custom selector. When
`custom_selector` is provided, `path_regex` and `where` must be None.
The signature of `custom_selector` is:
`(key_path, value) -> should_select`
or `(key_path, value, parent) -> should_select`.
file: Output file stream. This can be any object with a `write(str)`
method.
**kwargs: Wildcard keyword arguments to pass to `format`.
"""
if path_regex is None and where is None and custom_selector is None:
v = self
else:
v = query(self, path_regex, where, False, custom_selector)
object_utils.print(v, file=file, **kwargs)
| (self, path_regex: Optional[str] = None, where: Union[Callable[[Any], bool], Callable[[Any, Any], bool], NoneType] = None, custom_selector: Union[Callable[[pyglove.core.object_utils.value_location.KeyPath, Any], bool], Callable[[pyglove.core.object_utils.value_location.KeyPath, Any, Any], bool], NoneType] = None, file=<_io.TextIOWrapper name='<stdout>' mode='w' encoding='utf-8'>, **kwargs) -> NoneType |
40,316 | pyglove.core.symbolic.base | missing_values | Alias for `sym_missing`. | def missing_values(self, flatten: bool = True) -> Dict[str, Any]:
"""Alias for `sym_missing`."""
return self.sym_missing(flatten)
| (self, flatten: bool = True) -> Dict[str, Any] |
40,317 | pyglove.core.symbolic.base | non_default_values | Alias for `sym_nondefault`. | def non_default_values(
self, flatten: bool = True) -> Dict[Union[int, str], Any]:
"""Alias for `sym_nondefault`."""
return self.sym_nondefault(flatten)
| (self, flatten: bool = True) -> Dict[Union[int, str], Any] |
40,318 | pyglove.core.symbolic.base | rebind | Alias for `sym_rebind`.
Alias for `sym_rebind`. `rebind` is the recommended way for mutating
symbolic objects in PyGlove:
* It allows mutations not only on immediate child nodes, but on the
entire sub-tree.
* It allows mutations by rules via passing a callable object as the
value for `path_value_pairs`.
* It batches the updates from multiple sub-nodes, which triggers the
`_on_change` or `_on_bound` event once for recomputing the parent
object's internal states.
* It respects the "sealed" flag of the object or the `pg.seal`
context manager to trigger permission error.
Example::
#
# Rebind on pg.Object subclasses.
#
@pg.members([
('x', pg.typing.Dict([
('y', pg.typing.Int(default=0))
])),
('z', pg.typing.Int(default=1))
])
class A(pg.Object):
pass
a = A()
# Rebind using path-value pairs.
a.rebind({
'x.y': 1,
'z': 0
})
# Rebind using **kwargs.
a.rebind(x={y: 1}, z=0)
# Rebind using rebinders.
# Rebind based on path.
a.rebind(lambda k, v: 1 if k == 'x.y' else v)
# Rebind based on key.
a.rebind(lambda k, v: 1 if k and k.key == 'y' else v)
# Rebind based on value.
a.rebind(lambda k, v: 0 if v == 1 else v)
# Rebind baesd on value and parent.
a.rebind(lambda k, v, p: (0 if isinstance(p, A) and isinstance(v, int)
else v))
# Rebind on pg.Dict.
#
d = pg.Dict(value_spec=pg.typing.Dict([
('a', pg.typing.Dict([
('b', pg.typing.Int()),
])),
('c', pg.typing.Float())
])
# Rebind using **kwargs.
d.rebind(a={b: 1}, c=1.0)
# Rebind using key path to value dict.
d.rebind({
'a.b': 2,
'c': 2.0
})
# NOT OKAY: **kwargs and dict/rebinder cannot be used at the same time.
d.rebind({'a.b': 2}, c=2)
# Rebind with rebinder by path (on subtree).
d.rebind(lambda k, v: 1 if k.key == 'b' else v)
# Rebind with rebinder by value (on subtree).
d.rebind(lambda k, v: 0 if isinstance(v, int) else v)
#
# Rebind on pg.List.
#
l = pg.List([{
'a': 'foo',
'b': 0,
}
],
value_spec = pg.typing.List(pg.typing.Dict([
('a', pg.typing.Str()),
('b', pg.typing.Int())
]), max_size=10))
# Rebind using integer as list index: update semantics on list[0].
l.rebind({
0: {
'a': 'bar',
'b': 1
}
})
# Rebind: trigger append semantics when index is larger than list length.
l.rebind({
999: {
'a': 'fun',
'b': 2
}
})
# Rebind using key path.
l.rebind({
'[0].a': 'bar2'
'[1].b': 3
})
# Rebind using function (rebinder).
# Change all integers to 0 in sub-tree.
l.rebind(lambda k, v: v if not isinstance(v, int) else 0)
Args:
path_value_pairs: A dictionary of key/or key path to new field value, or
a function that generate updates based on the key path, value and
parent of each node under current object. We use terminology 'rebinder'
for this type of functions. The signature of a rebinder is:
`(key_path: pg.KeyPath, value: Any)` or
`(key_path: pg.KeyPath, value: Any, parent: pg.Symbolic)`
raise_on_no_change: If True, raises ``ValueError`` when there are no
values to change. This is useful when rebinder is used, which may or
may not generate any updates.
notify_parents: If True (default), parents will be notified upon change.
Otherwisee only the current object and the impacted children will
be notified. A most common use case for setting this flag to False
is when users want to rebind a child within the parent `_on_bound`
method.
skip_notification: If True, there will be no ``_on_change`` event
triggered from current `rebind`. If None, the default value will be
inferred from the :func:`pyglove.notify_on_change` context manager.
Use it only when you are certain that current rebind does not
invalidate internal states of its object tree.
**kwargs: For ``pg.Dict`` and ``pg.Object`` subclasses, user can use
keyword arguments (in format of `<field_name>=<field_value>`) to
directly modify immediate child nodes.
Returns:
Self.
Raises:
WritePermissionError: If object is sealed.
KeyError: If update location specified by key or key path is not aligned
with the schema of the object tree.
TypeError: If updated field value type does not conform to field spec.
ValueError: If updated field value is not acceptable according to field
spec, or nothing is updated and `raise_on_no_change` is set to
True.
| def rebind(
self,
path_value_pairs: Optional[Union[
Dict[
Union[object_utils.KeyPath, str, int],
Any],
Callable]] = None, # pylint: disable=g-bare-generic
*,
raise_on_no_change: bool = True,
notify_parents: bool = True,
skip_notification: Optional[bool] = None,
**kwargs) -> 'Symbolic':
"""Alias for `sym_rebind`.
Alias for `sym_rebind`. `rebind` is the recommended way for mutating
symbolic objects in PyGlove:
* It allows mutations not only on immediate child nodes, but on the
entire sub-tree.
* It allows mutations by rules via passing a callable object as the
value for `path_value_pairs`.
* It batches the updates from multiple sub-nodes, which triggers the
`_on_change` or `_on_bound` event once for recomputing the parent
object's internal states.
* It respects the "sealed" flag of the object or the `pg.seal`
context manager to trigger permission error.
Example::
#
# Rebind on pg.Object subclasses.
#
@pg.members([
('x', pg.typing.Dict([
('y', pg.typing.Int(default=0))
])),
('z', pg.typing.Int(default=1))
])
class A(pg.Object):
pass
a = A()
# Rebind using path-value pairs.
a.rebind({
'x.y': 1,
'z': 0
})
# Rebind using **kwargs.
a.rebind(x={y: 1}, z=0)
# Rebind using rebinders.
# Rebind based on path.
a.rebind(lambda k, v: 1 if k == 'x.y' else v)
# Rebind based on key.
a.rebind(lambda k, v: 1 if k and k.key == 'y' else v)
# Rebind based on value.
a.rebind(lambda k, v: 0 if v == 1 else v)
# Rebind baesd on value and parent.
a.rebind(lambda k, v, p: (0 if isinstance(p, A) and isinstance(v, int)
else v))
# Rebind on pg.Dict.
#
d = pg.Dict(value_spec=pg.typing.Dict([
('a', pg.typing.Dict([
('b', pg.typing.Int()),
])),
('c', pg.typing.Float())
])
# Rebind using **kwargs.
d.rebind(a={b: 1}, c=1.0)
# Rebind using key path to value dict.
d.rebind({
'a.b': 2,
'c': 2.0
})
# NOT OKAY: **kwargs and dict/rebinder cannot be used at the same time.
d.rebind({'a.b': 2}, c=2)
# Rebind with rebinder by path (on subtree).
d.rebind(lambda k, v: 1 if k.key == 'b' else v)
# Rebind with rebinder by value (on subtree).
d.rebind(lambda k, v: 0 if isinstance(v, int) else v)
#
# Rebind on pg.List.
#
l = pg.List([{
'a': 'foo',
'b': 0,
}
],
value_spec = pg.typing.List(pg.typing.Dict([
('a', pg.typing.Str()),
('b', pg.typing.Int())
]), max_size=10))
# Rebind using integer as list index: update semantics on list[0].
l.rebind({
0: {
'a': 'bar',
'b': 1
}
})
# Rebind: trigger append semantics when index is larger than list length.
l.rebind({
999: {
'a': 'fun',
'b': 2
}
})
# Rebind using key path.
l.rebind({
'[0].a': 'bar2'
'[1].b': 3
})
# Rebind using function (rebinder).
# Change all integers to 0 in sub-tree.
l.rebind(lambda k, v: v if not isinstance(v, int) else 0)
Args:
path_value_pairs: A dictionary of key/or key path to new field value, or
a function that generate updates based on the key path, value and
parent of each node under current object. We use terminology 'rebinder'
for this type of functions. The signature of a rebinder is:
`(key_path: pg.KeyPath, value: Any)` or
`(key_path: pg.KeyPath, value: Any, parent: pg.Symbolic)`
raise_on_no_change: If True, raises ``ValueError`` when there are no
values to change. This is useful when rebinder is used, which may or
may not generate any updates.
notify_parents: If True (default), parents will be notified upon change.
Otherwisee only the current object and the impacted children will
be notified. A most common use case for setting this flag to False
is when users want to rebind a child within the parent `_on_bound`
method.
skip_notification: If True, there will be no ``_on_change`` event
triggered from current `rebind`. If None, the default value will be
inferred from the :func:`pyglove.notify_on_change` context manager.
Use it only when you are certain that current rebind does not
invalidate internal states of its object tree.
**kwargs: For ``pg.Dict`` and ``pg.Object`` subclasses, user can use
keyword arguments (in format of `<field_name>=<field_value>`) to
directly modify immediate child nodes.
Returns:
Self.
Raises:
WritePermissionError: If object is sealed.
KeyError: If update location specified by key or key path is not aligned
with the schema of the object tree.
TypeError: If updated field value type does not conform to field spec.
ValueError: If updated field value is not acceptable according to field
spec, or nothing is updated and `raise_on_no_change` is set to
True.
"""
return self.sym_rebind(
path_value_pairs,
raise_on_no_change=raise_on_no_change,
notify_parents=notify_parents,
skip_notification=skip_notification,
**kwargs)
| (self, path_value_pairs: Union[Dict[Union[pyglove.core.object_utils.value_location.KeyPath, str, int], Any], Callable, NoneType] = None, *, raise_on_no_change: bool = True, notify_parents: bool = True, skip_notification: Optional[bool] = None, **kwargs) -> pyglove.core.symbolic.base.Symbolic |
40,319 | pyglove.core.symbolic.base | save | Saves current object using the global save handler. | def save(self, *args, **kwargs) -> Any:
"""Saves current object using the global save handler."""
return save(self, *args, **kwargs)
| (self, *args, **kwargs) -> Any |
40,320 | pyglove.core.symbolic.object | seal | Seal or unseal current object from further modification. | def seal(self, sealed: bool = True) -> 'Object':
"""Seal or unseal current object from further modification."""
self._sym_attributes.seal(sealed)
super().seal(sealed)
return self
| (self, sealed: bool = True) -> pyglove.core.symbolic.object.Object |
40,321 | pyglove.core.symbolic.base | set_accessor_writable | Sets accessor writable. | def set_accessor_writable(self, writable: bool = True) -> 'Symbolic':
"""Sets accessor writable."""
return self._set_raw_attr('_accessor_writable', writable)
| (self, writable: bool = True) -> pyglove.core.symbolic.base.Symbolic |
40,322 | pyglove.core.symbolic.base | sym_ancestor | Returns the nearest ancestor of specific classes. | def sym_ancestor(
self,
where: Optional[Callable[[Any], bool]] = None,
) -> Optional['Symbolic']:
"""Returns the nearest ancestor of specific classes."""
ancestor = self.sym_parent
where = where or (lambda x: True)
while ancestor is not None and not where(ancestor):
ancestor = ancestor.sym_parent
return ancestor
| (self, where: Optional[Callable[[Any], bool]] = None) -> Optional[pyglove.core.symbolic.base.Symbolic] |
40,323 | pyglove.core.symbolic.object | sym_attr_field | Returns the field definition for a symbolic attribute. | def sym_attr_field(
self, key: Union[str, int]
) -> Optional[pg_typing.Field]:
"""Returns the field definition for a symbolic attribute."""
return self._sym_attributes.sym_attr_field(key)
| (self, key: Union[str, int]) -> Optional[pyglove.core.typing.class_schema.Field] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.