Python API#

_console#

ast_utils#

class reactpy._console.ast_utils.ChangedNode(node: 'ast.AST', parents: 'Sequence[ast.AST]')[source]#

Bases: object

Parameters
Return type

None

class reactpy._console.ast_utils.ElementConstructorInfo(call: 'ast.Call', props: 'ast.Dict | ast.Call', parents: 'Sequence[ast.AST]')[source]#

Bases: object

Parameters
Return type

None

rewrite_camel_case_props#

rewrite_keys#

backend#

default#

class reactpy.backend.default.Options(*args, **kwds)[source]#

Bases: object

Configuration options that can be provided to the backend. This definition should not be used/instantiated. It exists only for type hinting purposes.

Parameters
  • args (Any) –

  • kwds (Any) –

Return type

NoReturn

reactpy.backend.default.configure(app, component, options=None)[source]#

Configure the given app instance to display the given component

Parameters
  • app (Any) –

  • component (RootComponentConstructor) –

  • options (None) –

Return type

None

reactpy.backend.default.create_development_app()[source]#

Create an application instance for development purposes

Return type

Any

async reactpy.backend.default.serve_development_app(app, host, port, started=None)[source]#

Run an application using a development server

Parameters
  • app (Any) –

  • host (str) –

  • port (int) –

  • started (asyncio.locks.Event | None) –

Return type

None

fastapi#

reactpy.backend.fastapi.create_development_app()[source]#

Create a development FastAPI application instance.

Return type

fastapi.applications.FastAPI

flask#

class reactpy.backend.flask.Options(head=({'tagName': 'title', 'children': ['ReactPy']},), url_prefix='', serve_index_route=True, cors=False)[source]#

Bases: reactpy.backend._common.CommonOptions

Render server config for reactpy.backend.flask.configure()

Parameters
Return type

None

cors: bool | dict[str, Any] = False#

Enable or configure Cross Origin Resource Sharing (CORS)

For more information see docs for flask_cors.CORS

reactpy.backend.flask.configure(app, component, options=None)[source]#

Configure the necessary ReactPy routes on the given app.

Parameters
Return type

None

reactpy.backend.flask.create_development_app()[source]#

Create an application instance for development purposes

Return type

flask.app.Flask

async reactpy.backend.flask.serve_development_app(app, host, port, started=None)[source]#

Run a development server for FastAPI

Parameters
  • app (flask.app.Flask) –

  • host (str) –

  • port (int) –

  • started (asyncio.locks.Event | None) –

Return type

None

reactpy.backend.flask.use_websocket()[source]#

A handle to the current websocket

Return type

simple_websocket.ws.Server

reactpy.backend.flask.use_request()[source]#

Get the current Request

Return type

flask.wrappers.Request

reactpy.backend.flask.use_connection()[source]#

Get the current Connection

Return type

reactpy.backend.types.Connection[reactpy.backend.flask._FlaskCarrier]

hooks#

reactpy.backend.hooks.use_connection()[source]#

Get the current Connection.

Return type

reactpy.backend.types.Connection[Any]

reactpy.backend.hooks.use_scope()[source]#

Get the current Connection’s scope.

Return type

collections.abc.MutableMapping[str, Any]

reactpy.backend.hooks.use_location()[source]#

Get the current Connection’s location.

Return type

reactpy.backend.types.Location

sanic#

class reactpy.backend.sanic.Options(head=({'tagName': 'title', 'children': ['ReactPy']},), url_prefix='', serve_index_route=True, cors=False)[source]#

Bases: reactpy.backend._common.CommonOptions

Render server config for reactpy.backend.sanic.configure()

Parameters
Return type

None

cors: bool | dict[str, Any] = False#

Enable or configure Cross Origin Resource Sharing (CORS)

For more information see docs for sanic_cors.CORS

reactpy.backend.sanic.configure(app, component, options=None)[source]#

Configure an application instance to display the given component

Parameters
  • app (Sanic[Any, Any]) –

  • component (RootComponentConstructor) –

  • options (Options | None) –

Return type

None

reactpy.backend.sanic.create_development_app()[source]#

Return a Sanic app instance in test mode

Return type

sanic.app.Sanic[Any, Any]

async reactpy.backend.sanic.serve_development_app(app, host, port, started=None)[source]#

Run a development server for sanic

Parameters
Return type

None

reactpy.backend.sanic.use_request()[source]#

Get the current Request

Return type

sanic.request.types.Request[Any, Any]

reactpy.backend.sanic.use_websocket()[source]#

Get the current websocket

Return type

sanic.server.websockets.connection.WebSocketConnection

reactpy.backend.sanic.use_connection()[source]#

Get the current Connection

Return type

reactpy.backend.types.Connection[reactpy.backend.sanic._SanicCarrier]

starlette#

class reactpy.backend.starlette.Options(head=({'tagName': 'title', 'children': ['ReactPy']},), url_prefix='', serve_index_route=True, cors=False)[source]#

Bases: reactpy.backend._common.CommonOptions

Render server config for reactpy.backend.starlette.configure()

Parameters
Return type

None

cors: bool | dict[str, Any] = False#

Enable or configure Cross Origin Resource Sharing (CORS)

For more information see docs for starlette.middleware.cors.CORSMiddleware

reactpy.backend.starlette.configure(app, component, options=None)[source]#

Configure the necessary ReactPy routes on the given app.

Parameters
  • app (Starlette) – An application instance

  • component (RootComponentConstructor) – A component constructor

  • options (Options | None) – Options for configuring server behavior

Return type

None

reactpy.backend.starlette.create_development_app()[source]#

Return a Starlette app instance in debug mode

Return type

starlette.applications.Starlette

async reactpy.backend.starlette.serve_development_app(app, host, port, started=None)[source]#

Run a development server for starlette

Parameters
  • app (starlette.applications.Starlette) –

  • host (str) –

  • port (int) –

  • started (asyncio.locks.Event | None) –

Return type

None

reactpy.backend.starlette.use_websocket()[source]#

Get the current WebSocket object

Return type

starlette.websockets.WebSocket

tornado#

reactpy.backend.tornado.configure(app, component, options=None)[source]#

Configure the necessary ReactPy routes on the given app.

Parameters
  • app (Application) – An application instance

  • component (ComponentConstructor) – A component constructor

  • options (CommonOptions | None) – Options for configuring server behavior

Return type

None

reactpy.backend.tornado.use_request()[source]#

Get the current HTTPServerRequest

Return type

tornado.httputil.HTTPServerRequest

class reactpy.backend.tornado.IndexHandler(application, request, **kwargs)[source]#

Bases: tornado.web.RequestHandler

Parameters
Return type

None

class reactpy.backend.tornado.ModelStreamHandler(application, request, **kwargs)[source]#

Bases: tornado.websocket.WebSocketHandler

A web-socket handler that serves up a new model stream to each new client

Parameters
Return type

None

async open(path='', *args, **kwargs)[source]#

Invoked when a new WebSocket is opened.

The arguments to open are extracted from the tornado.web.URLSpec regular expression, just like the arguments to tornado.web.RequestHandler.get.

open may be a coroutine. on_message will not be called until open has returned.

Changed in version 5.1: open may be a coroutine.

Parameters
  • path (str) –

  • args (Any) –

  • kwargs (Any) –

Return type

None

async on_message(message)[source]#

Handle incoming messages on the WebSocket

This method must be overridden.

Changed in version 4.5: on_message can be a coroutine.

Parameters

message (str | bytes) –

Return type

None

on_close()[source]#

Invoked when the WebSocket is closed.

If the connection was closed cleanly and a status code or reason phrase was supplied, these values will be available as the attributes self.close_code and self.close_reason.

Changed in version 4.0: Added close_code and close_reason attributes.

Return type

None

types#

class reactpy.backend.types.BackendType(*args, **kwargs)[source]#

Bases: Protocol[reactpy.backend.types._App]

Common interface for built-in web server/framework integrations

Options: Callable[[...], Any]#

A constructor for options passed to BackendType.configure()

configure(app, component, options=None)[source]#

Configure the given app instance to display the given component

Parameters
  • app (_App) –

  • component (RootComponentConstructor) –

  • options (Any | None) –

Return type

None

create_development_app()[source]#

Create an application instance for development purposes

Return type

reactpy.backend.types._App

async serve_development_app(app, host, port, started=None)[source]#

Run an application using a development server

Parameters
  • app (reactpy.backend.types._App) –

  • host (str) –

  • port (int) –

  • started (asyncio.locks.Event | None) –

Return type

None

class reactpy.backend.types.Connection(scope, location, carrier)[source]#

Bases: Generic[reactpy.backend.types._Carrier]

Represents a connection with a client

Parameters
Return type

None

scope: collections.abc.MutableMapping[str, Any]#

An ASGI scope or WSGI environment dictionary

location: reactpy.backend.types.Location#

The current location (URL)

carrier: reactpy.backend.types._Carrier#

How the connection is mediated. For example, a request or websocket.

This typically depends on the backend implementation.

class reactpy.backend.types.Location(pathname, search)[source]#

Bases: object

Represents the current location (URL)

Analogous to, but not necessarily identical to, the client-side document.location object.

Parameters
  • pathname (str) –

  • search (str) –

Return type

None

pathname: str#

the path of the URL for the location

search: str#

A search or query string - a β€˜?’ followed by the parameters of the URL.

If there are no search parameters this should be an empty string

utils#

reactpy.backend.utils.run(component, host='127.0.0.1', port=None, implementation=None)[source]#

Run a component with a development server

Parameters
  • component (RootComponentConstructor) –

  • host (str) –

  • port (int | None) –

  • implementation (BackendType[Any] | None) –

Return type

None

reactpy.backend.utils.find_available_port(host, port_min=8000, port_max=9000)[source]#

Get a port that’s available for the given host and port range

Parameters
  • host (str) –

  • port_min (int) –

  • port_max (int) –

Return type

int

reactpy.backend.utils.all_implementations()[source]#

Yield all available server implementations

Return type

collections.abc.Iterator[reactpy.backend.types.BackendType[Any]]

core#

component#

reactpy.core.component.component(function)[source]#

A decorator for defining a new component.

Parameters

function (Callable[[...], reactpy.core.types.ComponentType | reactpy.core.types.VdomDict | str | None]) – The component’s reactpy.core.proto.ComponentType.render() function.

Return type

Callable[[…], reactpy.core.component.Component]

class reactpy.core.component.Component(function, key, args, kwargs, sig)[source]#

Bases: object

An object for rending component models.

Parameters
Return type

None

events#

reactpy.core.events.event(function: Callable[[...], Any], *, stop_propagation: bool = False, prevent_default: bool = False) β†’ reactpy.core.events.EventHandler[source]#
reactpy.core.events.event(function: Literal[None] = None, *, stop_propagation: bool = False, prevent_default: bool = False) β†’ Callable[[Callable[[...], Any]], reactpy.core.events.EventHandler]

A decorator for constructing an EventHandler.

While you’re always free to add callbacks by assigning them to an element’s attributes

element = reactpy.html.button({"onClick": my_callback})

You may want the ability to prevent the default action associated with the event from taking place, or stopping the event from propagating up the DOM. This decorator allows you to add that functionality to your callbacks.

@event(stop_propagation=True, prevent_default=True)
def my_callback(*data): ...


element = reactpy.html.button({"onClick": my_callback})
Parameters
  • function – A function or coroutine responsible for handling the event.

  • stop_propagation – Block the event from propagating further up the DOM.

  • prevent_default – Stops the default actional associate with the event from taking place.

class reactpy.core.events.EventHandler(function, stop_propagation=False, prevent_default=False, target=None)[source]#

Bases: object

Turn a function or coroutine into an event handler

Parameters
  • function (EventHandlerFunc) – The function or coroutine which handles the event.

  • stop_propagation (bool) – Block the event from propagating further up the DOM.

  • prevent_default (bool) – Stops the default action associate with the event from taking place.

  • target (str | None) – A unique identifier for this event handler (auto-generated by default)

Return type

None

reactpy.core.events.to_event_handler_function(function, positional_args=True)[source]#

Make a EventHandlerFunc from a function or coroutine

Parameters
  • function (Callable[[...], Any]) – A function or coroutine accepting a number of positional arguments.

  • positional_args (bool) – Whether to pass the event parameters a positional args or as a list.

Return type

reactpy.core.types.EventHandlerFunc

reactpy.core.events.merge_event_handlers(event_handlers)[source]#

Merge multiple event handlers into one

Raises a ValueError if any handlers have conflicting stop_propagation or prevent_default attributes.

Parameters

event_handlers (collections.abc.Sequence[reactpy.core.types.EventHandlerType]) –

Return type

reactpy.core.types.EventHandlerType

reactpy.core.events.merge_event_handler_funcs(functions)[source]#

Make one event handler function from many

Parameters

functions (collections.abc.Sequence[reactpy.core.types.EventHandlerFunc]) –

Return type

reactpy.core.types.EventHandlerFunc

hooks#

reactpy.core.hooks.use_state(initial_value: Callable[[], reactpy.core.hooks._Type]) β†’ reactpy.core.types.State[reactpy.core.hooks._Type][source]#
reactpy.core.hooks.use_state(initial_value: reactpy.core.hooks._Type) β†’ reactpy.core.types.State[reactpy.core.hooks._Type]

See the full Use State docs for details

Parameters

initial_value – Defines the initial value of the state. A callable (accepting no arguments) can be used as a constructor function to avoid re-creating the initial value on each render.

Returns

A tuple containing the current state and a function to update it.

reactpy.core.hooks.use_effect(function: None = None, dependencies: collections.abc.Sequence[Any] | ellipsis | None = Ellipsis) β†’ Callable[[_EffectApplyFunc], None][source]#
reactpy.core.hooks.use_effect(function: _EffectApplyFunc, dependencies: collections.abc.Sequence[Any] | ellipsis | None = Ellipsis) β†’ None

See the full Use Effect docs for details

Parameters
  • function – Applies the effect and can return a clean-up function

  • dependencies – Dependencies for the effect. The effect will only trigger if the identity of any value in the given sequence changes (i.e. their id() is different). By default these are inferred based on local variables that are referenced by the given function.

Returns

If not function is provided, a decorator. Otherwise None.

reactpy.core.hooks.use_debug_value(message, dependencies=Ellipsis)[source]#

Log debug information when the given message changes.

Note

This hook only logs if REACTPY_DEBUG_MODE is active.

Unlike other hooks, a message is considered to have changed if the old and new values are !=. Because this comparison is performed on every render of the component, it may be worth considering the performance cost in some situations.

Parameters
  • message (Union[Any, Callable[[], Any]]) – The value to log or a memoized function for generating the value.

  • dependencies (collections.abc.Sequence[Any] | ellipsis | None) – Dependencies for the memoized function. The message will only be recomputed if the identity of any value in the given sequence changes (i.e. their id() is different). By default these are inferred based on local variables that are referenced by the given function.

Return type

None

reactpy.core.hooks.create_context(default_value)[source]#

Return a new context type for use in use_context()

Parameters

default_value (reactpy.core.hooks._Type) –

Return type

reactpy.core.types.Context[reactpy.core.hooks._Type]

reactpy.core.hooks.use_context(context)[source]#

Get the current value for the given context type.

See the full Use Context docs for more information.

Parameters

context (reactpy.core.types.Context[reactpy.core.hooks._Type]) –

Return type

reactpy.core.hooks._Type

reactpy.core.hooks.use_connection()[source]#

Get the current Connection.

Return type

reactpy.backend.types.Connection[Any]

reactpy.core.hooks.use_scope()[source]#

Get the current Connection’s scope.

Return type

collections.abc.MutableMapping[str, Any]

reactpy.core.hooks.use_location()[source]#

Get the current Connection’s location.

Return type

reactpy.backend.types.Location

reactpy.core.hooks.use_reducer(reducer, initial_value)[source]#

See the full Use Reducer docs for details

Parameters
  • reducer (Callable[[reactpy.core.hooks._Type, reactpy.core.hooks._ActionType], reactpy.core.hooks._Type]) – A function which applies an action to the current state in order to produce the next state.

  • initial_value (reactpy.core.hooks._Type) – The initial state value (same as for use_state())

Returns

A tuple containing the current state and a function to change it with an action

Return type

tuple[~_Type, Callable[[~_ActionType], NoneType]]

reactpy.core.hooks.use_callback(function: None = None, dependencies: collections.abc.Sequence[Any] | ellipsis | None = Ellipsis) β†’ Callable[[reactpy.core.hooks._CallbackFunc], reactpy.core.hooks._CallbackFunc][source]#
reactpy.core.hooks.use_callback(function: reactpy.core.hooks._CallbackFunc, dependencies: collections.abc.Sequence[Any] | ellipsis | None = Ellipsis) β†’ reactpy.core.hooks._CallbackFunc

See the full Use Callback docs for details

Parameters
  • function – The function whose identity will be preserved

  • dependencies – Dependencies of the callback. The identity the function will be updated if the identity of any value in the given sequence changes (i.e. their id() is different). By default these are inferred based on local variables that are referenced by the given function.

Returns

The current function

reactpy.core.hooks.use_memo(function: None = None, dependencies: collections.abc.Sequence[Any] | ellipsis | None = Ellipsis) β†’ reactpy.core.hooks._LambdaCaller[source]#
reactpy.core.hooks.use_memo(function: Callable[[], reactpy.core.hooks._Type], dependencies: collections.abc.Sequence[Any] | ellipsis | None = Ellipsis) β†’ reactpy.core.hooks._Type

See the full Use Memo docs for details

Parameters
  • function – The function to be memoized.

  • dependencies – Dependencies for the memoized function. The memo will only be recomputed if the identity of any value in the given sequence changes (i.e. their id() is different). By default these are inferred based on local variables that are referenced by the given function.

Returns

The current state

reactpy.core.hooks.use_ref(initial_value)[source]#

See the full Use State docs for details

Parameters

initial_value (reactpy.core.hooks._Type) – The value initially assigned to the reference.

Returns

A Ref object.

Return type

reactpy.utils.Ref[reactpy.core.hooks._Type]

reactpy.core.hooks.strictly_equal(x, y)[source]#

Check if two values are identical or, for a limited set or types, equal.

Only the following types are checked for equality rather than identity:

  • int

  • float

  • complex

  • str

  • bytes

  • bytearray

  • memoryview

Parameters
  • x (Any) –

  • y (Any) –

Return type

bool

layout#

class reactpy.core.layout.Layout(root)[source]#

Bases: object

Responsible for β€œrendering” components. That is, turning them into VDOM.

Parameters

root (ComponentType) –

Return type

None

async deliver(event)[source]#

Dispatch an event to the targeted handler

Parameters

event (reactpy.core.types.LayoutEventMessage) –

Return type

None

serve#

reactpy.core.serve.SendCoroutine#

Send model patches given by a dispatcher

alias of Callable[[reactpy.core.types.LayoutUpdateMessage], collections.abc.Awaitable[None]]

reactpy.core.serve.RecvCoroutine#

Called by a dispatcher to return a reactpy.core.layout.LayoutEventMessage

The event will then trigger an reactpy.core.proto.EventHandlerType in a layout.

alias of Callable[[], collections.abc.Awaitable[reactpy.core.types.LayoutEventMessage]]

exception reactpy.core.serve.Stop[source]#

Bases: BaseException

Deprecated

Stop serving changes and events

Raising this error will tell dispatchers to gracefully exit. Typically this is called by code running inside a layout to tell it to stop rendering.

async reactpy.core.serve.serve_layout(layout, send, recv)[source]#

Run a dispatch loop for a single view instance

Parameters
Return type

None

types#

class reactpy.core.types.State(value, set_value)[source]#

Bases: NamedTuple, Generic[reactpy.core.types._Type]

Parameters
  • value (reactpy.core.types._Type) –

  • set_value (Callable[[Union[reactpy.core.types._Type, Callable[[reactpy.core.types._Type], reactpy.core.types._Type]]], None]) –

value: reactpy.core.types._Type#

Alias for field number 0

set_value: Callable[[Union[reactpy.core.types._Type, Callable[[reactpy.core.types._Type], reactpy.core.types._Type]]], None]#

Alias for field number 1

reactpy.core.types.ComponentConstructor#

Simple function returning a new component

alias of Callable[[…], ComponentType]

reactpy.core.types.RootComponentConstructor#

The root component should be constructed by a function accepting no arguments.

alias of Callable[[], ComponentType]

class reactpy.core.types.ComponentType(*args, **kwargs)[source]#

Bases: Protocol

The expected interface for all component-like objects

key: Key | None#

An identifier which is unique amongst a component’s immediate siblings

type: Any#

The function or class defining the behavior of this component

This is used to see if two component instances share the same definition.

render()[source]#

Render the component’s view model.

Return type

reactpy.core.types.VdomDict | reactpy.core.types.ComponentType | str | None

class reactpy.core.types.LayoutType(*args, **kwargs)[source]#

Bases: Protocol[reactpy.core.types._Render_co, reactpy.core.types._Event_contra]

Renders and delivers, updates to views and events to handlers, respectively

async render()[source]#

Render an update to a view

Return type

reactpy.core.types._Render_co

async deliver(event)[source]#

Relay an event to its respective handler

Parameters

event (reactpy.core.types._Event_contra) –

Return type

None

reactpy.core.types.VdomAttributes#

Describes the attributes of a VdomDict

alias of collections.abc.Mapping[str, Any]

reactpy.core.types.VdomChild: TypeAlias = 'ComponentType | VdomDict | str | None | Any'#

A single child element of a VdomDict

reactpy.core.types.VdomChildren: TypeAlias = 'Sequence[VdomChild] | VdomChild'#

Describes a series of VdomChild elements

class reactpy.core.types.VdomDict[source]#

Bases: reactpy.core.types._VdomDictRequired, reactpy.core.types._VdomDictOptional

A VDOM dictionary

class reactpy.core.types.ImportSourceDict[source]#

Bases: typing_extensions.TypedDict

class reactpy.core.types.VdomJson[source]#

Bases: reactpy.core.types._RequiredVdomJson, reactpy.core.types._OptionalVdomJson

A JSON serializable form of VdomDict matching the VDOM_JSON_SCHEMA

reactpy.core.types.EventHandlerMapping#

A generic mapping between event names to their handlers

alias of collections.abc.Mapping[str, EventHandlerType]

reactpy.core.types.EventHandlerDict: TypeAlias = 'dict[str, EventHandlerType]'#

A dict mapping between event names to their handlers

class reactpy.core.types.EventHandlerFunc(*args, **kwargs)[source]#

Bases: Protocol

A coroutine which can handle event data

class reactpy.core.types.EventHandlerType(*args, **kwargs)[source]#

Bases: Protocol

Defines a handler for some event

prevent_default: bool#

Whether to block the event from propagating further up the DOM

stop_propagation: bool#

Stops the default action associate with the event from taking place.

function: reactpy.core.types.EventHandlerFunc#

A coroutine which can respond to an event and its data

target: str | None#

Typically left as None except when a static target is useful.

When testing, it may be useful to specify a static target ID so events can be triggered programmatically.

Note

When None, it is left to a LayoutType to auto generate a unique ID.

class reactpy.core.types.VdomDictConstructor(*args, **kwargs)[source]#

Bases: Protocol

Standard function for constructing a VdomDict

class reactpy.core.types.LayoutUpdateMessage[source]#

Bases: typing_extensions.TypedDict

A message describing an update to a layout

type: Literal['layout-update']#

The type of message

path: str#

JSON Pointer path to the model element being updated

model: reactpy.core.types.VdomJson#

The model to assign at the given JSON Pointer path

class reactpy.core.types.LayoutEventMessage[source]#

Bases: typing_extensions.TypedDict

Message describing an event originating from an element in the layout

type: Literal['layout-event']#

The type of message

target: str#

The ID of the event handler.

data: collections.abc.Sequence[Any]#

A list of event data passed to the event handler.

class reactpy.core.types.Context(*args, **kwargs)[source]#

Bases: Protocol[reactpy.core.types._Type]

Returns a ContextProvider component

class reactpy.core.types.ContextProviderType(*args, **kwargs)[source]#

Bases: reactpy.core.types.ComponentType, Protocol[reactpy.core.types._Type]

A component which provides a context value to its children

type: Context[_Type]#

The context type

property value: reactpy.core.types._Type#

Current context value

vdom#

reactpy.core.vdom.VDOM_JSON_SCHEMA = {'$ref': '#/definitions/element', '$schema': 'http://json-schema.org/draft-07/schema', 'definitions': {'element': {'dependentSchemas': {'error': {'properties': {'tagName': {'maxLength': 0}}}}, 'properties': {'attributes': {'type': 'object'}, 'children': {'$ref': '#/definitions/elementChildren'}, 'error': {'type': 'string'}, 'eventHandlers': {'$ref': '#/definitions/elementEventHandlers'}, 'importSource': {'$ref': '#/definitions/importSource'}, 'key': {'type': ['string', 'number', 'null']}, 'tagName': {'type': 'string'}}, 'required': ['tagName'], 'type': 'object'}, 'elementChildren': {'items': {'$ref': '#/definitions/elementOrString'}, 'type': 'array'}, 'elementEventHandlers': {'patternProperties': {'.*': {'$ref': '#/definitions/eventHandler'}}, 'type': 'object'}, 'elementOrString': {'if': {'type': 'object'}, 'then': {'$ref': '#/definitions/element'}, 'type': ['object', 'string']}, 'eventHandler': {'properties': {'preventDefault': {'type': 'boolean'}, 'stopPropagation': {'type': 'boolean'}, 'target': {'type': 'string'}}, 'required': ['target'], 'type': 'object'}, 'importSource': {'properties': {'fallback': {'if': {'not': {'type': 'null'}}, 'then': {'$ref': '#/definitions/elementOrString'}, 'type': ['object', 'string', 'null']}, 'source': {'type': 'string'}, 'sourceType': {'enum': ['URL', 'NAME']}, 'unmountBeforeUpdate': {'type': 'boolean'}}, 'required': ['source'], 'type': 'object'}}}#

JSON Schema describing serialized VDOM - see VDOM for more info

reactpy.core.vdom.validate_vdom_json(value)[source]#

Validate serialized VDOM - see VDOM_JSON_SCHEMA for more info

Parameters

value (Any) –

Return type

reactpy.core.types.VdomJson

reactpy.core.vdom.is_vdom(value)[source]#

Return whether a value is a VdomDict

This employs a very simple heuristic - something is VDOM if:

  1. It is a dict instance

  2. It contains the key "tagName"

  3. The value of the key "tagName" is a string

Note

Performing an isinstance(value, VdomDict) check is too restrictive since the user would be forced to import VdomDict every time they needed to declare a VDOM element. Giving the user more flexibility, at the cost of this check’s accuracy, is worth it.

Parameters

value (Any) –

Return type

bool

reactpy.core.vdom.vdom(tag: str, *children: VdomChildren) β†’ reactpy.core.types.VdomDict[source]#
reactpy.core.vdom.vdom(tag: str, attributes: collections.abc.Mapping[str, Any], *children: VdomChildren) β†’ reactpy.core.types.VdomDict

A helper function for creating VDOM elements.

Parameters
  • tag – The type of element (e.g. β€˜div’, β€˜h1’, β€˜img’)

  • attributes_and_children – An optional attribute mapping followed by any number of children or iterables of children. The attribute mapping must precede the children, or children which will be merged into their respective parts of the model.

  • key – A string indicating the identity of a particular element. This is significant to preserve event handlers across updates - without a key, a re-render would cause these handlers to be deleted, but with a key, they would be redirected to any newly defined handlers.

  • event_handlers – Maps event types to coroutines that are responsible for handling those events.

  • import_source – (subject to change) specifies javascript that, when evaluated returns a React component.

reactpy.core.vdom.make_vdom_constructor(tag, allow_children=True, import_source=None)[source]#

Return a constructor for VDOM dictionaries with the given tag name.

The resulting callable will have the same interface as vdom() but without its first tag argument.

Parameters
Return type

reactpy.core.types.VdomDictConstructor

reactpy.core.vdom.custom_vdom_constructor(func)[source]#

Cast function to VdomDictConstructor

Parameters

func (reactpy.core.vdom._CustomVdomDictConstructor) –

Return type

reactpy.core.types.VdomDictConstructor

testing#

backend#

class reactpy.testing.backend.BackendFixture(host='127.0.0.1', port=None, app=None, implementation=None, options=None, timeout=None)[source]#

Bases: object

A test fixture for running a server and imperatively displaying views

This fixture is typically used alongside async web drivers like playwight.

Example

async with BackendFixture() as server:
    server.mount(MyComponent)
Parameters
  • host (str) –

  • port (int | None) –

  • app (Any | None) –

  • implementation (BackendType[Any] | None) –

  • options (Any | None) –

  • timeout (float | None) –

Return type

None

property log_records: list[logging.LogRecord]#

A list of captured log records

url(path='', query=None)[source]#

Return a URL string pointing to the host and point of the server

Parameters
  • path (str) – the path to a resource on the server

  • query (Any | None) – a dictionary or list of query parameters

Return type

str

list_logged_exceptions(pattern='', types=<class 'Exception'>, log_level=40, del_log_records=True)[source]#

Return a list of logged exception matching the given criteria

Parameters
  • log_level (int) – The level of log to check

  • exclude_exc_types – Any exception types to ignore

  • del_log_records (bool) – Whether to delete the log records for yielded exceptions

  • pattern (str) –

  • types (type[Any] | tuple[type[Any], ...]) –

Return type

list[BaseException]

common#

reactpy.testing.common.clear_reactpy_web_modules_dir()[source]#

Clear the directory where ReactPy stores registered web modules

Return type

None

class reactpy.testing.common.poll(function, *args, **kwargs)[source]#

Bases: Generic[reactpy.testing.common._R]

Wait until the result of an sync or async function meets some condition

Parameters
  • function (Callable[_P, Awaitable[_R] | _R]) –

  • args (_P.args) –

  • kwargs (_P.kwargs) –

Return type

None

async until(condition, timeout=10.0, delay=0.1, description='condition to be true')[source]#

Check that the coroutines result meets a condition within the timeout

Parameters
  • condition (Callable[[reactpy.testing.common._R], bool]) –

  • timeout (float) –

  • delay (float) –

  • description (str) –

Return type

None

async until_is(right, timeout=10.0, delay=0.1)[source]#

Wait until the result is identical to the given value

Parameters
  • right (reactpy.testing.common._R) –

  • timeout (float) –

  • delay (float) –

Return type

None

async until_equals(right, timeout=10.0, delay=0.1)[source]#

Wait until the result is equal to the given value

Parameters
  • right (reactpy.testing.common._R) –

  • timeout (float) –

  • delay (float) –

Return type

None

class reactpy.testing.common.HookCatcher(index_by_kwarg=None)[source]#

Bases: object

Utility for capturing a LifeCycleHook from a component

Example

hooks = HookCatcher(index_by_kwarg="thing")

@reactpy.component
@hooks.capture
def MyComponent(thing):
    ...

...  # render the component

# grab the last render of where MyComponent(thing='something')
hooks.index["something"]
# or grab the hook from the component's last render
hooks.latest

After the first render of MyComponent the HookCatcher will have captured the component’s LifeCycleHook.

Parameters

index_by_kwarg (str | None) –

capture(render_function)[source]#

Decorator for capturing a LifeCycleHook on each render of a component

Parameters

render_function (Callable[[...], Any]) –

Return type

Callable[[…], Any]

class reactpy.testing.common.StaticEventHandler[source]#

Bases: object

Utility for capturing the target of one event handler

Example

static_handler = StaticEventHandler()

@reactpy.component
def MyComponent():
    state, set_state = reactpy.hooks.use_state(0)
    handler = static_handler.use(lambda event: set_state(state + 1))
    return reactpy.html.button({"onClick": handler}, "Click me!")

# gives the target ID for onClick where from the last render of MyComponent
static_handlers.target

If you need to capture event handlers from different instances of a component the you should create multiple StaticEventHandler instances.

static_handlers_by_key = {
    "first": StaticEventHandler(),
    "second": StaticEventHandler(),
}

@reactpy.component
def Parent():
    return reactpy.html.div(Child(key="first"), Child(key="second"))

@reactpy.component
def Child(key):
    state, set_state = reactpy.hooks.use_state(0)
    handler = static_handlers_by_key[key].use(lambda event: set_state(state + 1))
    return reactpy.html.button({"onClick": handler}, "Click me!")

# grab the individual targets for each instance above
first_target = static_handlers_by_key["first"].target
second_target = static_handlers_by_key["second"].target
Return type

None

display#

class reactpy.testing.display.DisplayFixture(backend=None, driver=None, url_prefix='')[source]#

Bases: object

A fixture for running web-based tests using playwright

Parameters
  • backend (BackendFixture | None) –

  • driver (Browser | BrowserContext | Page | None) –

  • url_prefix (str) –

Return type

None

logs#

exception reactpy.testing.logs.LogAssertionError[source]#

Bases: AssertionError

An assertion error raised in relation to log messages.

reactpy.testing.logs.assert_reactpy_did_log(match_message='', error_type=None, match_error='')[source]#

Assert that ReactPy produced a log matching the described message or error.

Parameters
  • match_message (str) – Must match a logged message.

  • error_type (type[Exception] | None) – Checks the type of logged exceptions.

  • match_error (str) – Must match an error message.

Return type

collections.abc.Iterator[None]

reactpy.testing.logs.assert_reactpy_did_not_log(match_message='', error_type=None, match_error='')[source]#

Assert the inverse of assert_reactpy_logged()

Parameters
  • match_message (str) –

  • error_type (type[Exception] | None) –

  • match_error (str) –

Return type

collections.abc.Iterator[None]

reactpy.testing.logs.list_logged_exceptions(log_records, pattern='', types=<class 'Exception'>, log_level=40, del_log_records=True)[source]#

Return a list of logged exception matching the given criteria

Parameters
  • log_level (int) – The level of log to check

  • exclude_exc_types – Any exception types to ignore

  • del_log_records (bool) – Whether to delete the log records for yielded exceptions

  • log_records (list[logging.LogRecord]) –

  • pattern (str) –

  • types (type[Any] | tuple[type[Any], ...]) –

Return type

list[BaseException]

reactpy.testing.logs.capture_reactpy_logs()[source]#

Capture logs from ReactPy

Any logs produced in this context are cleared afterwards

Return type

collections.abc.Iterator[list[logging.LogRecord]]

web#

module#

reactpy.web.module.NAME_SOURCE = 'NAME'#

A named source - usually a Javascript package name

reactpy.web.module.URL_SOURCE = 'URL'#

A source loaded from a URL, usually a CDN

reactpy.web.module.module_from_url(url, fallback=None, resolve_exports=None, resolve_exports_depth=5, unmount_before_update=False)[source]#

Load a WebModule from a URL_SOURCE

Parameters
  • url (str) – Where the javascript module will be loaded from which conforms to the interface for Custom Javascript Components

  • fallback (Any | None) – What to temporarily display while the module is being loaded.

  • resolve_imports – Whether to try and find all the named exports of this module.

  • resolve_exports_depth (int) – How deeply to search for those exports.

  • unmount_before_update (bool) – Cause the component to be unmounted before each update. This option should only be used if the imported package fails to re-render when props change. Using this option has negative performance consequences since all DOM elements must be changed on each render. See #461 for more info.

  • resolve_exports (bool | None) –

Return type

reactpy.web.module.WebModule

reactpy.web.module.module_from_template(template, package, cdn='https://esm.sh', fallback=None, resolve_exports=None, resolve_exports_depth=5, unmount_before_update=False)[source]#

Create a WebModule from a framework template

This is useful for experimenting with component libraries that do not already support ReactPy’s Custom Javascript Components interface.

Warning

This approach is not recommended for use in a production setting because the framework templates may use unpinned dependencies that could change without warning. It’s best to author a module adhering to the Custom Javascript Components interface instead.

Templates

  • react: for modules exporting React components

Parameters
  • template (str) – The name of the framework template to use with the given package.

  • package (str) – The name of a package to load. May include a file extension (defaults to .js if not given)

  • cdn (str) – Where the package should be loaded from. The CDN must distribute ESM modules

  • fallback (Any | None) – What to temporarily display while the module is being loaded.

  • resolve_imports – Whether to try and find all the named exports of this module.

  • resolve_exports_depth (int) – How deeply to search for those exports.

  • unmount_before_update (bool) – Cause the component to be unmounted before each update. This option should only be used if the imported package fails to re-render when props change. Using this option has negative performance consequences since all DOM elements must be changed on each render. See #461 for more info.

  • resolve_exports (bool | None) –

Return type

reactpy.web.module.WebModule

reactpy.web.module.module_from_file(name, file, fallback=None, resolve_exports=None, resolve_exports_depth=5, unmount_before_update=False, symlink=False)[source]#

Load a WebModule from a given file

Parameters
  • name (str) – The name of the package

  • file (str | pathlib.Path) – The file from which the content of the web module will be created.

  • fallback (Any | None) – What to temporarily display while the module is being loaded.

  • resolve_imports – Whether to try and find all the named exports of this module.

  • resolve_exports_depth (int) – How deeply to search for those exports.

  • unmount_before_update (bool) – Cause the component to be unmounted before each update. This option should only be used if the imported package fails to re-render when props change. Using this option has negative performance consequences since all DOM elements must be changed on each render. See #461 for more info.

  • symlink (bool) – Whether the web module should be saved as a symlink to the given file.

  • resolve_exports (bool | None) –

Return type

reactpy.web.module.WebModule

reactpy.web.module.module_from_string(name, content, fallback=None, resolve_exports=None, resolve_exports_depth=5, unmount_before_update=False)[source]#

Load a WebModule whose content comes from a string.

Parameters
  • name (str) – The name of the package

  • content (str) – The contents of the web module

  • fallback (Any | None) – What to temporarily display while the module is being loaded.

  • resolve_imports – Whether to try and find all the named exports of this module.

  • resolve_exports_depth (int) – How deeply to search for those exports.

  • unmount_before_update (bool) – Cause the component to be unmounted before each update. This option should only be used if the imported package fails to re-render when props change. Using this option has negative performance consequences since all DOM elements must be changed on each render. See #461 for more info.

  • resolve_exports (bool | None) –

Return type

reactpy.web.module.WebModule

class reactpy.web.module.WebModule(source: 'str', source_type: 'SourceType', default_fallback: 'Any | None', export_names: 'set[str] | None', file: 'Path | None', unmount_before_update: 'bool')[source]#

Bases: object

Parameters
  • source (str) –

  • source_type (reactpy.web.module.SourceType) –

  • default_fallback (Any | None) –

  • export_names (set[str] | None) –

  • file (pathlib.Path | None) –

  • unmount_before_update (bool) –

Return type

None

reactpy.web.module.export(web_module: reactpy.web.module.WebModule, export_names: str, fallback: Any | None = None, allow_children: bool = True) β†’ reactpy.core.types.VdomDictConstructor[source]#
reactpy.web.module.export(web_module: reactpy.web.module.WebModule, export_names: list[str] | tuple[str, ...], fallback: Any | None = None, allow_children: bool = True) β†’ list[reactpy.core.types.VdomDictConstructor]

Return one or more VDOM constructors from a WebModule

Parameters
  • export_names – One or more names to export. If given as a string, a single component will be returned. If a list is given, then a list of components will be returned.

  • fallback – What to temporarily display while the module is being loaded.

  • allow_children – Whether or not these components can have children.

utils#

config#

ReactPy provides a series of configuration options that can be set using environment variables or, for those which allow it, a programmatic interface.

reactpy.config.REACTPY_DEBUG_MODE = Option(REACTPY_DEBUG_MODE=False)#

Get extra logs and validation checks at the cost of performance.

This will enable the following:

reactpy.config.REACTPY_CHECK_VDOM_SPEC = Option(REACTPY_CHECK_VDOM_SPEC=False)#

Checks which ensure VDOM is rendered to spec

For more info on the VDOM spec, see here: VDOM JSON Schema

reactpy.config.REACTPY_CHECK_JSON_ATTRS = Option(REACTPY_CHECK_JSON_ATTRS=False)#

Checks that all VDOM attributes are JSON serializable

The VDOM spec is not able to enforce this on its own since attributes could anything.

reactpy.config.REACTPY_WEB_MODULES_DIR = Option(REACTPY_WEB_MODULES_DIR=PosixPath('/tmp/tmpe7b9e_20'))#

The location ReactPy will use to store its client application

This directory MUST be treated as a black box. Downstream applications MUST NOT assume anything about the structure of this directory see reactpy.web.module for a set of publicly available APIs for working with the client.

reactpy.config.REACTPY_TESTING_DEFAULT_TIMEOUT = Option(REACTPY_TESTING_DEFAULT_TIMEOUT=10.0)#

A default timeout for testing utilities in ReactPy

reactpy.config.REACTPY_ASYNC_RENDERING = Option(REACTPY_ASYNC_RENDERING=False)#

Whether to render components asynchronously. This is currently an experimental feature.

future#

logging#

reactpy.logging.ROOT_LOGGER = <Logger reactpy (INFO)>#

ReactPy’s root logger instance

types#

Exports common types from:

utils#

class reactpy.utils.Ref(initial_value=<object object>)[source]#

Bases: Generic[reactpy.utils._RefValue]

Hold a reference to a value

This is used in imperative code to mutate the state of this object in order to incur side effects. Generally refs should be avoided if possible, but sometimes they are required.

Notes

You can compare the contents for two Ref objects using the == operator.

Parameters

initial_value (_RefValue) –

Return type

None

current#

The present value

set_current(new)[source]#

Set the current value and return what is now the old value

This is nice to use in lambda functions.

Parameters

new (reactpy.utils._RefValue) –

Return type

reactpy.utils._RefValue

reactpy.utils.vdom_to_html(vdom)[source]#

Convert a VDOM dictionary into an HTML string

Only the following keys are translated to HTML:

  • tagName

  • attributes

  • children (must be strings or more VDOM dicts)

Parameters

vdom (reactpy.core.types.VdomDict) – The VdomDict element to convert to HTML

Return type

str

reactpy.utils.html_to_vdom(html, *transforms, strict=True)[source]#

Transform HTML into a DOM model. Unique keys can be provided to HTML elements using a key=... attribute within your HTML tag.

Parameters
  • html (str) – The raw HTML as a string

  • transforms (Callable[[reactpy.core.types.VdomDict], Any]) – Functions of the form transform(old) -> new where old is a VDOM dictionary which will be replaced by new. For example, you could use a transform function to add highlighting to a <code/> block.

  • strict (bool) – If True, raise an exception if the HTML does not perfectly follow HTML5 syntax.

Return type

reactpy.core.types.VdomDict

exception reactpy.utils.HTMLParseError[source]#

Bases: lxml.etree.LxmlSyntaxError

Raised when an HTML document cannot be parsed using strict parsing.

reactpy.utils.del_html_head_body_transform(vdom)[source]#

Transform intended for use with html_to_vdom.

Removes <html>, <head>, and <body> while preserving their children.

Parameters

vdom (reactpy.core.types.VdomDict) – The VDOM dictionary to transform.

Return type

reactpy.core.types.VdomDict

widgets#

reactpy.widgets.image(format, value='', attributes=None)[source]#

Utility for constructing an image from a string or bytes

The source value will automatically be encoded to base64

Parameters
Return type

reactpy.core.types.VdomDict

reactpy.widgets.use_linked_inputs(attributes, on_change=<function <lambda>>, cast=<function <lambda>>, initial_value='', ignore_empty=True)[source]#

Return a list of linked inputs equal to the number of given attributes.

Parameters
  • attributes (collections.abc.Sequence[dict[str, Any]]) – That attributes of each returned input element. If the number of generated inputs is variable, you may need to assign each one a key by including a "key" in each attribute dictionary.

  • on_change (Callable[[reactpy.widgets._Value], None]) – A callback which is triggered when any input is changed. This callback need not update the β€˜value’ field in the attributes of the inputs since that is handled automatically.

  • cast (reactpy.widgets._CastFunc[reactpy.widgets._Value]) – Cast the β€˜value’ of changed inputs that is passed to on_change.

  • initial_value (str) – Initialize the β€˜value’ field of the inputs.

  • ignore_empty (bool) – Do not trigger on_change if the β€˜value’ is an empty string.

Return type

list[reactpy.core.types.VdomDict]