Convert the object to JavaScript.
This is similar to toJs(), but for use from
Python. If the object can be implicitly translated to JavaScript, it will be
returned unchanged. If the object cannot be converted into JavaScript, this
method will return a JsProxy of a
PyProxy, as if you had used
create_proxy().
See Python to JavaScript for more information.
- Parameters:
obj (Any) The Python object to convert
depth (int) The maximum depth to do the conversion. Negative numbers are treated as
infinite. Set this to 1 to do a shallow conversion.
pyproxies (Optional[JsProxy]) Should be a JavaScript Array. If provided, any PyProxies
generated will be stored here. You can later use
destroy_proxies() if you want to destroy the proxies from
Python (or from JavaScript you can just iterate over the
Array and destroy the proxies).
create_pyproxies (bool) If you set this to False, to_js() will raise an
error rather than creating any pyproxies.
dict_converter (Optional[Callable[[Iterable[JsArray[Any]]], JsProxy]])
This converter if provided receives a (JavaScript) iterable of
(JavaScript) pairs [key, value]. It is expected to return the desired
result of the dict conversion. Some suggested values for this argument:
js.Object.fromEntries similar to the default behavior
js.Map.new convert to a map
js.Array.from convert to an array of entries
default_converter (Optional[ToJsConverter]) If present will be invoked whenever Pyodide does not have some built in
conversion for the object. If default_converter raises an error, the
error will be allowed to propagate. Otherwise, the object returned will
be used as the conversion. default_converter takes three arguments.
The first argument is the value to be converted.
eager_converter (Optional[ToJsConverter])
If present will be invoked whenever the object is not an int,
float, bool, None, or a JsProxy. It is called before the
default conversions are applied to lists, tuples, dictionaries, and
sets, so it can be used to override these. By contrast,
default_converter is used as a fallback.
If eager_converter raises an error, the error will be allowed to
propagate. Otherwise, the object returned will be used as the
conversion. default_converter takes three arguments. The first
argument is the value to be converted.
- Return type:
Any
Examples
>>> from js import Object, Map, Array
>>> from pyodide.ffi import to_js
>>> js_object = to_js({'age': 20, 'name': 'john'})
>>> js_object
[object Object]
>>> js_object.age == 20
True
>>> js_object.name == 'john'
True
>>> js_object.hasOwnProperty("age")
True
>>> js_object.hasOwnProperty("height")
False
>>> js_object = to_js({'age': 20, 'name': 'john'}, dict_converter=Array.from_)
>>> [item for item in js_object]
[age,20, name,john]
>>> js_object.toString()
'age,20,name,john'
>>> class Bird: pass
>>> converter = lambda value, convert, cache: Object.new(size=1, color='red') if isinstance(value, Bird) else None
>>> js_nest = to_js([Bird(), Bird()], default_converter=converter)
>>> [bird for bird in js_nest]
[[object Object], [object Object]]
>>> [(bird.size, bird.color) for bird in js_nest]
[(1, 'red'), (1, 'red')]
Here are some examples demonstrating the usage of the default_converter
argument.
In addition to the normal conversions, convert JavaScript Date
objects to datetime objects:
from datetime import datetime
from js import Date
def default_converter(value, _ignored1, _ignored2):
if isinstance(value, datetime):
return Date.new(value.timestamp() * 1000)
return value
Dont create any PyProxies, require a complete conversion or raise an error:
def default_converter(_value, _ignored1, _ignored2):
raise Exception("Failed to completely convert object")
The second and third arguments are only needed for converting containers.
The second argument is a conversion function which is used to convert the
elements of the container with the same settings. The third argument is a
cache function which is needed to handle self referential containers.
Consider the following example. Suppose we have a Python Pair class:
class Pair:
def __init__(self, first, second):
self.first = first
self.second = second
We can use the following default_converter to convert Pair to
Array:
from js import Array
def default_converter(value, convert, cache):
if not isinstance(value, Pair):
return value
result = Array.new()
cache(value, result)
result.push(convert(value.first))
result.push(convert(value.second))
return result
Note that we have to cache the conversion of value before converting
value.first and value.second. To see why, consider a self
referential pair:
p = Pair(0, 0); p.first = p;
Without cache(value, result);, converting p would lead to an
infinite recurse. With it, we can successfully convert p to an Array
such that l[0] === l.
Here are some examples demonstrating the usage of the eager_converter
argument. Calling convert(value) does the normal conversion, so setting
eager_converter to the following function is the same as leaving it unset
(except for being slower):
def apply_normal_conversion(value, convert, cacheConversion):
return convert(value)
The following eager_converter will fail the conversion if a tuple is
passed:
from pyodide.ffi import ConversionError
def reject_tuples(value, convert, cacheConversion):
if isinstance(value, tuple):
raise ConversionError("We don't convert tuples!")
return convert(value)
The following eager_converter makes tuples into a PyProxy:
def proxy_tuples(value, convert, cacheConversion):
if isinstance(value, tuple):
return value
return convert(value)