JavaScript

domonic includes a JavaScript-like runtime surface for practical scripting and porting.

It is useful for quickly porting familiar JS code to Python while staying close to web-platform concepts:

It is also useful for learning JavaScript from the Python side. Many APIs keep their browser names and behaviour where practical, so Array.map(), String.includes(), Math.random(), Date.now(), Promise and URL feel familiar when you later meet them in JavaScript.

For JavaScript developers using Python, this module gives you familiar tools while you translate browser or Node habits into Python scripts. It is handy for ports, teaching material, tests, scraping utilities, and codebases where web developers need to contribute Python without losing every familiar API at once.

from domonic.javascript import Math
print(Math.random())

from domonic.javascript import Array
myArr = Array(1, 2, 3)
print(myArr.splice(1))

from domonic.javascript import URL
url = URL('https://somesite.com/blog/article-one#some-hash')
print(url.protocol)
print(url.host)
print(url.pathname)
print(url.hash)

# from domonic.javascript import Global
# Global.decodeURIComponent(...
# Global.encodeComponent(...

# from domonic.javascript import Date, String, Number
# etc..

Alongside the global helpers, there are familiar String, Number, Array, Date, URL, and timing APIs.

Port JavaScript-Like Code

The goal is not to replace JavaScript. The goal is to make JavaScript-shaped code easier to read, test, port and teach inside Python projects.

from domonic.javascript import Array, Math, Object, String

items = Array("HTML", "DOM", "Web APIs")
items.push("BeautifulSlop")

meta = Object()
meta.name = String("domonic")
meta.score = Math.round(9.6)

print(items.join(", "))
print(meta.name.toUpperCase(), meta.score)

Promises and Timers

from domonic.javascript import Promise, setTimeout

def work(resolve, reject):
    setTimeout(lambda: resolve("done"), 50)

Promise(work).then(lambda value: print(value))

Date class

The Date class is available:

from domonic.javascript import Date
print(Date.now())

Array methods

Many of the familiar JavaScript array methods are available in Python form:

myarr = Array("1", "2", 3, {"4": "four"}, 5, [6])

print(myarr.length)
print(myarr.includes("1"))
print(myarr.includes(3))
print(myarr.includes(10))
print(myarr.indexOf(10))
print(myarr.indexOf("1"))
print(myarr.indexOf([6]))
print(myarr[1])
print(len(myarr))
print(myarr.join('---'))
print(myarr.lastIndexOf("1"))
print(myarr.lastIndexOf(3))
print(myarr.reverse())
print(myarr.slice(0, 1))
print(myarr.splice(1))
# print(myarr.splice(2))
# print(myarr.splice(3))
# print(myarr.splice(4))
print(myarr.splice(3, 3, "a", "b", "c"))
print(myarr)
print(myarr.pop())
print(myarr)
myarr.push(7)
print(myarr)
print(myarr.unshift('z'))
print(myarr)
print(myarr.shift())
print(myarr)
# print(myarr.concat())

# myarr.sort()
# myarr.fill()
# myarr.isArray()?
# myarr.map()
# myarr.reduce()
# myarr.reduceRight()
# myarr.some()

String methods

String subclasses str (like Number subclasses float), so String(x) is a real string primitive – isinstance(String(5), str) is True, it hashes, sorts, and drops into any API that expects a str – while still carrying the JavaScript method surface below.

A wide set of familiar string methods is available:

mystr = String("Some String")

mystr.toLowerCase() # "some string"
mystr.toUpperCase() # "SOME STRING"
# print(mystr.length)
mystr.repeat(2) # "Some StringSome String"
print(mystr.startsWith('S'))
# mystr.endsWith('g'))

# JavaScript substr in Python.
mystr.substr(1) # 'ome String'

# JavaScript slice in Python.
# print(mystr.slice(1, 3))
mystr.slice(1, 3) # 'om')

# trim
mystr = String("   Some String   ")
mystr.trim() # "Some String")

# charAt
mystr = String("Some String")
mystr.charAt(1) # 'o'
mystr.charAt(5) # 'S'

# charCodeAt
mystr.charCodeAt(1) # 111
mystr.fromCharCode(111) # 'o'

# test
# mystr.test('a') # True
# mystr.test('b') # False

# replace
# print(mystr.replace('S', 'X'))
mystr.replace('S', 'X') # "Xome String"
mystr.replace(' ', 'X') # "SomeXString"
mystr.replace('S', 'X') != "Xome Xtring"

# search
mystr = String("Some String")
mystr.search('a') # -1 (not found)
mystr.search('o') # 1  (index of the first match)

# substr
print(mystr.substr(1, 2))
mystr.substr(1, 2) # 'om')
mystr.substr(1, 3) # 'ome')
mystr.substr(1, 4) # 'ome ')
mystr.substr(1, 5) # 'ome S')

# toLocaleLowerCase
mystr.toLocaleLowerCase() # 'some string'
mystr.toLocaleLowerCase() # 'some string'

# toLocaleUpperCase
# print(mystr.toLocaleUpperCase())
mystr.toLocaleUpperCase() # 'SOME STRING'

# lastIndex
# print(mystr.lastIndexOf('o'))
mystr.lastIndexOf('o') # 1

assert mystr.padEnd(13) # "Some String  "
assert mystr.padStart(13) # "  Some String"
assert mystr.padStart(13, '-') # "--Some String"

mystr.includes('a') # False
mystr.includes('Some') # True

Some obsolete JavaScript string helpers are also available:

>>> test = String("Hello World!")
>>> test.blink()
'<blink>Hello World!</blink>'
>>> test.sub()
'<sub>Hello World!</sub>'
>>> test.sup()
'<sup>Hello World!</sup>'
>>> test.div() # ?? hang on?
'<div>Hello World!</div>'
>>> test.webpage() # ??? err... wait what!!!
'<html><head><title>Hello World!</title>...</head><body><h1>Hello World!</h1></body></html>'

You can actually transform a type String into any tag.

Call () on a string value to transform it into a node:

>>> test = String("time to take a mo")
>>> test('div', _style="font-color:red;")
<div style="font-color:red;">time to take a mo</div>
>>> str(test('div', _style="font-color:red;"))
'<div style="font-color:red;">time to take a mo</div>'

Pass the tag name and attributes.

Regular expressions

RegExp translates JavaScript regex syntax to Python’s re so patterns copied from JS code keep working:

from domonic.javascript import RegExp, String

# \p{...} Unicode property escapes
String("a, b. c!").replace(RegExp(r"\p{P}+", "gu"), "")   # "a b c"

# named groups, JS spelling
RegExp(r"(?<year>\d{4})-(?<month>\d{2})").exec("2026-09").groups
# {'year': '2026', 'month': '09'}

# sticky (y) flag honours lastIndex
r = RegExp(r"\d+", "y"); r.lastIndex = 3
r.exec("abc123")                                          # ['123']

# RegExp.replace with $1..$n / $& / $` / $', or a JS-style callback
RegExp(r"(\w+)@(\w+)").replace("user@host", "$2:$1")      # "host:user"
String("a1b2").replace(RegExp(r"\d", "g"), lambda m, *a: f"[{m}]")

\p{...} accepts long category names and Script=<name> for common scripts, and the JS idiom [^] (any character, newlines included) is translated. String.search returns the match index, String.match returns an exec-style array (or a list of matches with /g), and matchAll yields match arrays – all matching the browser.

Strings are UTF-16

Like JavaScript, String length and indexing are UTF-16 code-unit based, so an astral-plane character (an emoji, rare CJK, …) counts as two.

from domonic.javascript import String

s = String("a\U0001F600b")
s.length            # 4  -- the emoji is two code units
s.charCodeAt(1)     # 55357  (0xD83D, the lead surrogate)
s.codePointAt(1)    # 128512 (the recombined scalar)
s.slice(1, 3)       # "😀"

Pure-BMP text behaves exactly as a plain Python str would.

Object methods

Object is useful for making dictionaries a bit more JS-like:

o = Object()
o.prop = 'hi'
str(o)

It also contains a growing list of methods you may know from JavaScript.

Object.assign is variadic and returns the target; Object.freeze returns a version of a dict that raises on any mutation (use the return value, the way you would in JS – a plain Python dict can’t be frozen in place):

from domonic.javascript import Object

config = Object.assign({}, {"a": 1}, {"b": 2}, {"a": 3})
print(config)               # {'a': 3, 'b': 2}

config = Object.freeze(config)
print(Object.isFrozen(config))   # True
config["a"] = 99             # raises TypeError: cannot modify a frozen object

Array.from_ (JS Array.from) applies an optional map callback, and reads an array-like {"length": n} by index:

from domonic.javascript import Array

print(Array.from_([1, 2, 3], lambda x, *_: x * 2))   # [2, 4, 6]
print(Array.from_({"length": 3}, lambda _, i: i))    # [0, 1, 2]

JSON.parse / JSON.stringify honour a reviver / replacer, the way JavaScript’s do:

from domonic.javascript import JSON

# replacer function: returning None (JS undefined) omits the key
print(JSON.stringify({"a": 1, "b": 2}, lambda k, v: None if k == "b" else v))
# {"a":1}

# replacer array: a key whitelist
print(JSON.stringify({"a": 1, "b": 2, "c": 3}, ["a", "c"]))
# {"a":1,"c":3}

# reviver: bottom-up transform while parsing
print(JSON.parse('{"a":1,"b":2}', lambda k, v: v * 10 if isinstance(v, int) else v))
# {'a': 10, 'b': 20}

setInterval

You can use setInterval and clearInterval with parameters:

from domonic.javascript import window

x=0

def hi(inc):
    global x
    x = x+inc
    print(x)

test = window.setInterval(hi, 1000, 2)
import time
time.sleep(5)
window.clearInterval(test)
print(f"Final value of x:{x}")
# 2
# 4
# 6
# 8
# Final value of x:8

fetch

There is a fetch implementation that uses promises, with threaded and pooled variants.

from domonic.webapi.fetch import fetch

response = fetch("https://example.com")
print(response.text())

from domonic.javascript import *

urls = ['http://google.com', 'http://linkedin.com', 'http://eventual.technology']  # use your own domains

print('run 1')
results = window.fetch(urls[0])
results.then(lambda r: print(r.text))
print('run 1 FINISHED')

def somefunc(response):
        print("I'm a callback", response.ok)
        return response

mydata = window.fetch(urls[0]).then(somefunc)
print(mydata)
print(mydata.data)
print(mydata.data.text)

# fetch more than one
results = window.fetch_set(urls)
print(results)
print(list(results))
for r in results:
        if r is not None:
                print(r.ok)
                # print(r.text)

# multi-threaded
results = window.fetch_threaded(urls)
print(results)
print(list(results))
for r in results:
        if r is not None:
                print(r.ok)
                # print(r.text)

# pooled
results = window.fetch_pooled(urls, timeout=2)
print(results)
for r in results:
        if r is not None:
                print(r.ok)
                # print(r.text)

print('run 4')
results = window.fetch(urls[0])
print(results)
results.then(lambda r: print(r.text) if r is not None else None)

All fetch methods use requests and pass keyword arguments through when you need to modify behaviour.

Keywords

If you import *, you get the JS-style keywords:

print(true)  # True
print(false) # False
print(undefined) # None
print(null) # None

You also get a function that evaluates Python strings:

sup = function('''print("hi")''')
sup()

Typed arrays

JS-style typed arrays are also available.

Styling

Styling gets passed to the style tag on render.

mytag = div("hi", _id="test")
mytag.style.backgroundColor = "black"
mytag.style.fontSize = "12px"
print(mytag)
# <div id="test" style="background-color: black; font-size: 12px;">hi</div>

There are many other features. Take a look at the module docs below.

class domonic.javascript.Any(*args, **kwargs)[source]

Bases: object

Special type indicating an unconstrained type.

  • Any is compatible with every type.

  • Any assumed to have all methods.

  • All values assumed to be instances of Any.

Note that all the above statements are true from the point of view of static type checkers. At runtime, Any should not be used with instance checks.

class domonic.javascript.Array(*args)[source]

Bases: object

javascript array

static from_(obj, mapFn=None, thisArg=None)[source]

Creates a new Array instance from an array-like or iterable object.

The optional mapFn(value, index) is applied to each element as the array is built, exactly like Array.from(iterable, fn) in JS.

Return type:

Array

static of(*args)[source]

A new array with exactly the given elements – unlike Array(n), Array.of(7) is [7], not a length-7 array.

Return type:

Array

prototype

alias of Array

toString()[source]

Converts an array to a JavaScript-style comma-separated string.

Return type:

str

toSource()[source]

Returns the source array.

Return type:

list[Any]

property length: int

Sets or returns the number of elements in an array

concat(*args)[source]

A new array = this array plus each argument, with array arguments spread one level deep and everything else appended (JavaScript). The original array is not modified.

Return type:

Array

flat(depth=1)[source]

Flattens an array into a single-dimensional array or a depth of arrays

Return type:

list[Any]

flatMap(fn=None)[source]

Maps a function over an array and flattens the result

Return type:

Array

fill(value=None, start=None, end=None)[source]

Fills elements of an array from a start index to an end index with a static value

Return type:

list[Any]

groupBy(callback)[source]

Groups the elements of an array according to the result of calling a callback function on each element

Parameters:

callback (callable) – the callback recieves the following paramters(value, index, target)

Returns:

a dictionary of arrays

Return type:

dict

findLast(callback=None)[source]

Returns the last element in an array that passes a test

Return type:

Any

findLastIndex(callback=None)[source]

Returns the last index of an element in an array that passes a test

Return type:

int

includes(value)[source]

[Check if an array contains the specified item

Parameters:

value (any) – any value

Returns:

a boolean

Return type:

bool

indexOf(value, fromIndex=0)[source]

Search the array for an element and returns its position

Return type:

int

static isArray(thing)[source]

Checks whether an object is an array.

Parameters:

thing (Any) – The thing to check.

Returns:

True if the object is a list, tuple or Array.

Return type:

bool

join(value=',')[source]

Joins all elements of an array into a string.

Return type:

str

lastIndexOf(value, fromIndex=None)[source]

Search the array for an element, starting at the end, and returns its position

Return type:

int

pop()[source]

Removes and returns the last element, or undefined when empty.

Return type:

Any

push(value)[source]

Adds new elements to the end of an array, and returns the new length

Return type:

int

reverse()[source]

Reverses the order of the elements in an array

Return type:

list[Any]

slice(start=0, stop=None, step=1)[source]

Selects a part of an array, and returns the new array.

Parameters:
  • start (int) – Index to slice from.

  • stop (int, optional) – Index to slice to. Defaults to the end of the array.

  • step (int, optional) – The step between elements. Defaults to 1.

Returns:

The new array.

Return type:

list

splice(start, delete_count=None, *items)[source]

Selects a part of an array, and returns the new array

Return type:

list[Any]

unshift(*args)[source]

Adds new elements to the beginning of an array, and returns the new length.

Returns:

The length of the array.

Return type:

int

shift()[source]

Removes and returns the first element, or undefined when empty.

Return type:

Any

map(func=None)[source]

Creates a new array with the result of calling a function for each array element.

Parameters:

func (callable) – A function to call on each array element.

Returns:

A new array.

Return type:

list

some(func=None)[source]

Checks if any of the elements in an array pass a test

Return type:

bool

sort(func=None)[source]

Sorts the elements of an array

Return type:

list[Any]

toReversed()[source]

A reversed copy (the original array is left unchanged) – ES2023.

Return type:

Array

toSorted(func=None)[source]

A sorted copy (the original array is left unchanged) – ES2023.

Return type:

Array

toSpliced(start, deleteCount=None, *items)[source]

A copy with a splice applied (the original is unchanged) – ES2023.

Return type:

Array

with_(index, value)[source]

A copy with index replaced by value – ES2023 Array#with (with is a Python keyword).

Return type:

Array

reduce(cb=None, initialValue=None)[source]

Reduces the array to a single value (going left-to-right) callback recieve theses parameters: previousValue, currentValue, currentIndex, array

Return type:

Any

reduceRight(callback=None, initialValue=None)[source]

Reduces the array to a single value (going right-to-left) callback recieve theses parameters: previousValue, currentValue, currentIndex, array

Return type:

Any

filter(func=None)[source]

Creates a new array with every element in an array that pass a test i.e. even_numbers = someArr.filter( lambda x: x % 2 == 0 )

Return type:

list[Any]

find(func=None)[source]

Returns the value of the first element in an array that pass a test

Return type:

Any

findIndex(predicate)[source]

Index of the first element for which predicate is truthy (a bare value is also accepted, as a domonic convenience), or -1.

Return type:

int

forEach(func=None)[source]

Calls a function for each array element

keys()[source]

Returns a Array Iteration Object, containing the keys of the original array

Return type:

Iterator[Any]

values()[source]

Returns a new array iterator object that yields each element’s value.

Return type:

Iterator[Any]

copyWithin(target, start=0, end=None)[source]

Shallow-copy the [start, end) slice to target within the same array (indices may be negative), and return the array.

Return type:

list[Any]

entries()[source]

Returns a key/value pair Array Iteration Object.

Yields:

list[Any] – A [index, value] pair.

Return type:

Iterator[list[Any]]

every(func=None)[source]

Checks if every element in an array pass a test.

Return type:

bool

at(index)[source]

Takes an integer value and returns the item at that index, allowing for positive and negative integers. Negative integers count back from the last item in the array.

Parameters:

index (int) – Position of the item.

Returns:

The item at the given position.

Return type:

Any

with(index, value)

A copy with index replaced by value – ES2023 Array#with (with is a Python keyword).

Return type:

Array

class domonic.javascript.ArrayBuffer(length)[source]

Bases: object

buffer: Any
property byteLength: int
property length: int
slice(start, end)[source]
Return type:

array

getUint8(index)[source]
Return type:

int

getInt8(index)[source]
Return type:

int

getUint16(index, littleEndian=False)[source]
Return type:

int

getInt16(index, littleEndian=False)[source]
Return type:

int

getUint32(index, littleEndian=False)[source]
Return type:

int

getInt32(index, littleEndian=False)[source]
Return type:

int

getFloat32(index, littleEndian=False)[source]
Return type:

Any

getFloat64(index, littleEndian=False)[source]
Return type:

Any

setUint8(index, value)[source]
setInt8(index, value)[source]
setUint16(index, value, littleEndian=False)[source]
setInt16(index, value, littleEndian=False)[source]
setUint32(index, value, littleEndian=False)[source]
setInt32(index, value, littleEndian=False)[source]
setFloat32(index, value, littleEndian=False)[source]
setFloat64(index, value, littleEndian=False)[source]
class domonic.javascript.Boolean(value=False)[source]

Bases: object

Creates a Boolean Object. Warning this is NOT a boolean type. for that use Global.Boolean()

value: bool
valueOf()[source]
Return type:

bool

toString()[source]
Return type:

str

class domonic.javascript.DataView(buffer, byteOffset=0, byteLength=None)[source]

Bases: ArrayBuffer

property byteLength: int
getUint8(index)[source]
Return type:

Any

getInt8(index)[source]
Return type:

Any

getUint16(index, littleEndian=False)[source]
Return type:

Any

getInt16(index, littleEndian=False)[source]
Return type:

Any

getUint32(index, littleEndian=False)[source]
Return type:

Any

getInt32(index, littleEndian=False)[source]
Return type:

Any

getFloat32(index, littleEndian=False)[source]
Return type:

Any

getFloat64(index, littleEndian=False)[source]
Return type:

Any

setUint8(index, value)[source]
setInt8(index, value)[source]
setUint16(index, value, littleEndian=False)[source]
setInt16(index, value, littleEndian=False)[source]
setUint32(index, value, littleEndian=False)[source]
setInt32(index, value, littleEndian=False)[source]
setFloat32(index, value, littleEndian=False)[source]
setFloat64(index, value, littleEndian=False)[source]
class domonic.javascript.Date(date=None, *args, formatter='python', **kwargs)[source]

Bases: Object

javascript date

static parse(date_string)[source]

Parses a date string and returns the number of milliseconds since January 1, 1970

Return type:

int

toString()[source]

Returns a string representation of the date

Return type:

str

parse_date(date_string)[source]
Return type:

datetime

getDate()[source]

Returns the day of the month (from 1-31)

Return type:

int

getDay()[source]

Returns the day of the week (from 0-6 : Sunday-Saturday)

Returns:

An integer number, between 0 and 6, corresponding to the day of the week for the given date, according to local time: 0 for Sunday, 1 for Monday, 2 for Tuesday, and so on

Return type:

int

getFullYear()[source]

Returns the year

Return type:

int

getHours()[source]

Returns the hour (from 0-23)

Return type:

int

getMilliseconds()[source]

Returns the milliseconds (from 0-999)

Return type:

int

getMinutes()[source]

Returns the minutes (from 0-59)

Return type:

int

getMonth()[source]

Returns the month (from 0-11)

Return type:

int

getSeconds()[source]

Returns the seconds (from 0-59)

Return type:

int

getTime()[source]

Returns A number representing the milliseconds elapsed between 1 January 1970 00:00:00 UTC and self.date

Return type:

int

getTimezoneOffset()[source]

Returns the difference, in minutes, between a date as evaluated in the UTC time zone, and the same date as evaluated in the local time zone

Return type:

int

getUTCDate()[source]

Returns the day of the month, according to universal time (from 1-31)

Return type:

int

getUTCDay()[source]

Returns the day of the week, according to universal time (from 0-6)

Return type:

int

getUTCFullYear()[source]

Returns the year, according to universal time

Return type:

int

getUTCHours()[source]

Returns the hour, according to universal time (from 0-23)

Return type:

int

getUTCMilliseconds()[source]

Returns the milliseconds, according to universal time (from 0-999)

Return type:

int

getUTCMinutes()[source]

Returns the minutes, according to universal time (from 0-59)

Return type:

int

getUTCMonth()[source]

Returns the month, according to universal time (from 0-11)

Return type:

int

getUTCSeconds()[source]

Returns the seconds, according to universal time (from 0-59)

Return type:

int

getYear()[source]

Deprecated. Use the getFullYear() method instead

Return type:

int

static now()[source]

Returns the number of milliseconds since midnight Jan 1, 1970

Return type:

int

setDate(day)[source]

Sets the day of the month of a date object

Parameters:

day (int) – An integer representing the day of the month.

Returns:

milliseconds between epoch and updated date.

Return type:

int

setFullYear(yearValue, monthValue=None, dateValue=None)[source]

Sets the year of a date object

Parameters:
  • yearValue (int) – The year to set.

  • monthValue (int, optional) – The month to set (0-11). Defaults to None.

  • dateValue (int, optional) – The day of the month to set. Defaults to None.

Returns:

milliseconds between epoch and updated date.

Return type:

int

setHours(hoursValue, minutesValue=None, secondsValue=None, msValue=None)[source]

Sets the hour of a date object

Parameters:
  • hoursValue (int) – an integer between 0 and 23

  • minutesValue (int, optional) – an integer between 0 and 59

  • secondsValue (int, optional) – an integer between 0 and 59,

  • msValue (int, optional) – a number between 0 and 999,

Returns:

milliseconds between epoch and updated date.

Return type:

int

setMilliseconds(milliseconds)[source]

Sets the milliseconds of a date object

Parameters:

milliseconds (int) – Milliseconds to set i.e 123

Returns:

milliseconds between epoch and updated date.

Return type:

int

setMinutes(minutesValue, secondsValue=None, msValue=None)[source]

Set the minutes of a date object

Parameters:
  • minutesValue (int, optional) – an integer between 0 and 59

  • secondsValue (int, optional) – an integer between 0 and 59,

  • msValue (int, optional) – a number between 0 and 999,

Returns:

milliseconds between epoch and updated date.

Return type:

int

setMonth(monthValue, dayValue=None)[source]

Sets the month of a date object

Parameters:
  • monthValue (int) – a number from 0 to 11 indicating the month.

  • dayValue (int, optional) – an optional day of the month. Defaults to 0.

Returns:

milliseconds between epoch and updated date.

Return type:

int

setSeconds(secondsValue, msValue=None)[source]

Sets the seconds of a date object

Parameters:
  • secondsValue (int) – The seconds to set.

  • msValue (int, optional) – The milliseconds to set. Defaults to None.

Returns:

milliseconds between epoch and updated date.

Return type:

int

setTime(milliseconds=None, tz=None)[source]

Sets the date and time of a date object

Parameters:
  • milliseconds (int, optional) – Milliseconds since the epoch. Defaults to None (uses now).

  • tz (optional) – The timezone to use. Defaults to None.

Returns:

milliseconds between epoch and updated date.

Return type:

int | None

setUTCDate(day)[source]

Sets the day of the month of a date object, according to universal time

Return type:

int

setUTCFullYear(year)[source]

Sets the year of a date object, according to universal time

Return type:

int

setUTCHours(hour)[source]

Sets the hour of a date object, according to universal time

Return type:

int

setUTCMilliseconds(milliseconds)[source]

Sets the milliseconds of a date object, according to universal time

Return type:

int

setUTCMinutes(minutes)[source]

Set the minutes of a date object, according to universal time

Return type:

int

setUTCMonth(month)[source]

Sets the month of a date object, according to universal time

Return type:

int

setUTCSeconds(seconds)[source]

Set the seconds of a date object, according to universal time

Return type:

int

setYear(year)[source]

Deprecated. Use the setFullYear() method instead

Return type:

int

toDateString()[source]

Converts the date portion of a Date object into a readable string

Return type:

str

toUTCString()[source]

Converts a Date object to a string, according to universal time

Return type:

str

toGMTString()[source]

Deprecated. Use the toUTCString() method instead

Return type:

str

toJSON()[source]

Returns the date as a string, formatted as a JSON date (same as toISOString)

Return type:

str

toISOString()[source]

Returns the date as a string, using the ISO standard: YYYY-MM-DDTHH:mm:ss.sssZ, always in UTC.

Return type:

str

toLocaleDateString()[source]

Returns the date portion of a Date object as a string, using locale conventions

Return type:

str

toLocaleString()[source]

Converts a Date object to a string, using locale conventions

Return type:

str

toLocaleTimeString()[source]

Returns the time portion of a Date object as a string, using locale conventions

Return type:

str

toTimeString()[source]

Converts the time portion of a Date object to a string

Return type:

str

static UTC(year, month=0, day=1, hours=0, minutes=0, seconds=0, ms=0)[source]

Date.UTC(year, monthIndex, ...) – milliseconds since the epoch for the given UTC date. monthIndex is 0-based and fields overflow, as in JavaScript.

Return type:

int

valueOf()[source]

Returns the primitive numeric value of the date.

Return type:

int

exception domonic.javascript.Error(message='', *args, **kwargs)[source]

Bases: Exception

JavaScript Error. name defaults to "Error"; str(err) is "Error: message" (just "Error" when there is no message).

name: str = 'Error'
toString()[source]
Return type:

str

exception domonic.javascript.EvalError(message='', *args, **kwargs)[source]

Bases: Error

name: str = 'EvalError'
class domonic.javascript.FetchedSet(*args, **kwargs)[source]

Bases: object

results: list[Any]
oncomplete(func)[source]
class domonic.javascript.Float32Array(*args)[source]

Bases: TypedArray

name = 'Float32Array'
BYTES_PER_ELEMENT: int = 4
class domonic.javascript.Float64Array(*args)[source]

Bases: TypedArray

name = 'Float64Array'
BYTES_PER_ELEMENT: int = 8
class domonic.javascript.FormData(*args, **kwargs)[source]

Bases: object

Compatibility wrapper for domonic.webapi.xhr.FormData.

Return type:

Any

class domonic.javascript.Function(func, *args, **kwargs)[source]

Bases: Object

a Function object

apply(thisArg=None, args=None, **kwargs)[source]

Calls a function with a given this value, and arguments provided as an array.

Parameters:
  • thisArg (Any) – The value of this provided for the call to func.

  • args (Sequence[Any], optional) – The arguments to pass to func.

Returns:

The result of calling the function.

Return type:

Any

bind(thisArg, *args, **kwargs)[source]

Creates a new function that, when called, has its this keyword set to the provided value, with a given sequence of arguments preceding any provided when the new function is called.

Parameters:

thisArg (Any) – The value to be passed as the this parameter to the target function func when the bound function is called.

Returns:

A copy of the given function with the specified this value, and initial arguments (if provided).

Return type:

Callable

call(thisArg=None, *args, **kwargs)[source]

Calls a function with a given this value and arguments provided individually.

Parameters:

thisArg (Any, optional) – The value of this provided for the call to func.

Returns:

The result of calling the function.

Return type:

Any

toString()[source]

Returns a string representing the source code of the function. Overrides the

Return type:

str

class domonic.javascript.Global[source]

Bases: object

javascript global methods

NaN = 'NaN'
Infinity = inf
performance: Any = Performance(now=67787.013ms)
globalThis

alias of Global

self

alias of Global

window

alias of Window

setInterval(time, *args, **kwargs)
Return type:

Job

clearInterval()
static decodeURI(x)[source]

Decodes a URI

Return type:

str

static decodeURIComponent(x)[source]

Decodes a URI component

Return type:

str

static encodeURI(x)[source]

Encodes a URI

Return type:

str

static encodeURIComponent(x)[source]

Encodes a URI component

Return type:

str

static eval(pythonstring)[source]

Evaluates a string and executes it as if it was script code

Return type:

Any

static isFinite(x)[source]

Returns true if x coerces to a finite number.

Return type:

bool

static isNaN(x)[source]

Determines whether a value coerces to NaN.

Return type:

bool

static Number(x)[source]

Converts a value to a number, JS-style (non-numeric -> NaN).

Return type:

int | float

static Boolean(x)[source]
Return type:

bool

static parseFloat(x)[source]

Parses a string and returns a floating point number

Return type:

float

static parseInt(x, radix=0)[source]

Parses a string and returns an integer

Return type:

int | float

static String(x='')[source]

Converts a value to a string the way JavaScript’s String(x) does.

Return type:

str

undefined()[source]

Indicates that a variable has not been assigned a value

static require(path)[source]

Loads a script from a file

Return type:

Any

static setTimeout(callback, t, *args, **kwargs)[source]

sets a timer which executes a function or evaluates an expression after a specified delay

Parameters:
  • callback (function) – method to be executed after the delay

  • t (int) – milliseconds

Returns:

an identifier for the timer

Return type:

str

static clearTimeout(timeoutID)[source]

cancels a timer set with setTimeout()

Parameters:

timeoutID (str) – the identifier returned by setTimeout()

class domonic.javascript.Int16Array(*args)[source]

Bases: TypedArray

name = 'Int16Array'
BYTES_PER_ELEMENT: int = 2
class domonic.javascript.Int32Array(*args)[source]

Bases: TypedArray

name = 'Int32Array'
BYTES_PER_ELEMENT: int = 4
class domonic.javascript.Int8Array(*args)[source]

Bases: TypedArray

name = 'Int8Array'
BYTES_PER_ELEMENT: int = 1
exception domonic.javascript.InternalError(message='', *args, **kwargs)[source]

Bases: Error

name: str = 'InternalError'
class domonic.javascript.Intl[source]

Bases: object

static getCanonicalLocales(locales)[source]

Returns the canonicalized locales.

Return type:

list[str]

static supportedValuesOf(*args)[source]

Returns a sorted array containing the supported unique calendar, collation, currency, numbering systems, or unit values supported by the implementation.

Return type:

list[str]

Collator

alias of _Collator

DateTimeFormat

alias of _DateTimeFormat

NumberFormat

alias of _NumberFormat

domonic.javascript.IterableABC

alias of Iterable

class domonic.javascript.JSON[source]

Bases: object

JSON.parse / JSON.stringify – JavaScript’s global JSON object.

Thin wrapper over domonic.JSON so ports can from domonic.javascript import JSON and call it the browser way.

static parse(text, reviver=None)[source]
Return type:

Any

static stringify(value, replacer=None, space=None)[source]
Return type:

str | None

class domonic.javascript.Job(interval, execute, *args, **kwargs)[source]

Bases: Thread

stop()[source]
run()[source]

Method representing the thread’s activity.

You may override this method in a subclass. The standard run() method invokes the callable object passed to the object’s constructor as the target argument, if any, with sequential and keyword arguments taken from the args and kwargs arguments, respectively.

class domonic.javascript.Map(collection=None)[source]

Bases: object

Map holds key-value pairs and remembers the original insertion order of the keys.

Keys are compared by SameValueZero, exactly like a real JS Map – 1 and "1" are different keys, objects compare by reference, and every NaN collapses to one key – not by stringifying every key (which would make 1 and "1" collide, and turn an object key into unreliable, possibly non-unique repr() noise).

property size: int

The number of entries (map.size – a property, like JS).

clear()[source]

Removes all key-value pairs from the Map object.

delete(key)[source]

Returns true if an element in the Map object existed and has been removed, or false if the element does not exist. Map.prototype.has(key) will return false afterwards.

Return type:

bool

get(key, default=None)[source]

Returns the value associated to the key, or undefined if there is none.

Return type:

Any

has(key)[source]

Returns a boolean asserting whether a value has been associated to the key in the Map object or not.

Return type:

bool

set(key, value)[source]

Sets the value for the key in the Map object. Returns the Map object.

Return type:

Map

iterkeys()[source]
Return type:

Iterator[Any]

iteritems()[source]
Return type:

Iterator[tuple[Any, Any]]

keys()[source]

Returns a new Iterator object that contains the keys for each element in the Map object in insertion order.

Return type:

list[Any]

values()[source]

Returns a new Iterator object that contains the values for each element in the Map object in insertion order.

Return type:

list[Any]

entries()[source]

Returns a new Iterator object that contains an array of [key, value] for each element in the Map object in insertion order.

Return type:

list[tuple[Any, Any]]

forEach(callbackFn, thisArg=None)[source]

Call callbackFn once for each key/value pair in insertion order.

update(ordered_dict)[source]
domonic.javascript.MappingABC

alias of Mapping

class domonic.javascript.Math(obj=None, *args, **kwargs)[source]

Bases: Object

Math class that mirrors javascript implementation.

i.e. you can pass strings and it will also work, Math.abs(‘-1’)

PI: float = 3.141592653589793
E: float = 2.718281828459045
LN2: float = 0.6931471805599453
LN10: float = 2.302585092994046
LOG2E: float = 1.4426950408889634
LOG10E: float = 0.4342944819032518
SQRT1_2: float = 0.7071067811865476
SQRT2: float = 1.4142135623730951
static abs(x)[source]

Returns the absolute value of a number.

Parameters:

x (float) – number

Returns:

absolute value

Return type:

float

static acos(x)[source]

Returns the arccosine (in radians) of a number.

Parameters:

x (float) – number

Returns:

arccosine

Return type:

float

static acosh(x)[source]

Returns the hyperbolic arccosine of a number.

Return type:

float

static asin(x)[source]

Returns the arcsine (in radians) of a number.

Return type:

float

static asinh(x)[source]

Returns the hyperbolic arcsine of a number.

Return type:

float

static atan(x)[source]

Returns the arctangent (in radians) of a number.

Return type:

float

static atan2(x, y)[source]

Returns the arctangent of the quotient of its arguments.

Return type:

float

static atanh(x)[source]

Returns the hyperbolic arctangent of a number.

Return type:

float

static cbrt(x)[source]

Returns the cube root of a number.

Return type:

float

static ceil(x)[source]

Returns the smallest integer greater than or equal to a number.

Return type:

float

static cos(x)[source]

Returns the cosine of a number. (x is in radians)

Return type:

float

static cosh(x)[source]

Returns the hyperbolic cosine of a number.

Return type:

float

static exp(x)[source]

Returns the value of E^x.

Return type:

float

static floor(x)[source]

Returns the largest integer less than or equal to a number.

Return type:

float

static log(x, base=None)[source]

Returns the natural logarithm (base E) of a number.

Return type:

float

static max(*args)[source]

The largest of the arguments (-Infinity for none, NaN if any is NaN) – variadic, like JavaScript.

Return type:

Any

static min(*args)[source]

The smallest of the arguments (Infinity for none, NaN if any is NaN) – variadic, like JavaScript.

Return type:

Any

static random()[source]

Returns a random number between 0 and 1.

Return type:

float

static round(x)[source]

Nearest integer; ties round toward +Infinity (JavaScript).

Return type:

float

static sign(x)[source]

-1, 0 or 1 according to the sign of x (NaN stays NaN).

Return type:

float

static expm1(x)[source]

exp(x) - 1, accurate for small x.

Return type:

float

static imul(a, b)[source]

C-like 32-bit integer multiplication.

Return type:

int

static pow(x, y)[source]

Returns the value of a number raised to a power.

Return type:

float

static sin(x)[source]

Returns the sine of a number. (x is in radians)

Return type:

float

static sinh(x)[source]

Returns the hyperbolic sine of a number.

Return type:

float

static sqrt(x)[source]

Returns the square root of a number.

Return type:

float

static tan(x)[source]

Returns the tangent of a number. (x is in radians)

Return type:

float

static tanh(x)[source]

Returns the hyperbolic tangent of a number.

Return type:

float

static trunc(x)[source]

Returns the integer part of a number.

Return type:

float

static hypot(*args)[source]

Return the square root of the sum of squares of its arguments.

Return type:

float

static log2(x)[source]

Return the base 2 logarithm of a number.

Return type:

float

static log1p(x)[source]

Return the natural logarithm of 1 plus a number.

Return type:

float

static loglp(x)[source]

Backward-compatible alias for the historical log1p typo.

Return type:

float

static log10(x)[source]

function returns the base 10 logarithm of a number, that is

Return type:

float

static fround(x)[source]

returns the nearest 32-bit single precision float representation of a Number

Return type:

float

static clz32(x)[source]

returns the number of leading zero bits in the 32-bit binary representation of a number.

Return type:

int

class domonic.javascript.Number(x='', *args, **kwargs)[source]

Bases: float

javascript Number methods

Return type:

Number

MAX_VALUE = 1.7976931348623157e+308
MIN_VALUE = 5e-324
NEGATIVE_INFINITY = -inf

Represents negative infinity (returned on overflow) Number

POSITIVE_INFINITY = inf

Represents infinity (returned on overflow) Number

MAX_SAFE_INTEGER: int = 9007199254740991
MIN_SAFE_INTEGER: int = -9007199254740991
EPSILON: float = 2.220446049250313e-16
NaN = nan
static isFinite(value)[source]

Number.isFinite – true only for a real finite number (no coercion).

Return type:

bool

static isNaN(value)[source]

Number.isNaN – true only for an actual NaN number (no coercion).

Return type:

bool

static parseFloat(value)[source]

Alias of the global parseFloat.

Return type:

Any

static parseInt(value, radix=0)[source]

Alias of the global parseInt.

Return type:

Any

x: Any
static isInteger(value)[source]

Number.isInteger – true only for a finite whole-number value.

Return type:

bool

static isSafeInteger(value)[source]

Number.isSafeInteger – an integer value within +/-(2**53 - 1).

Like JavaScript, a non-number (including a numeric string) is False.

Return type:

bool

toExponential(num=None)[source]

Converts a number into an exponential notation

Return type:

str

toFixed(digits)[source]

formats a number using fixed-point notation.

Parameters:

digits (int) – [The number of digits to appear after the decimal point

Returns:

A string representing the given number using fixed-point notation.

Return type:

str

toPrecision(precision)[source]

returns a string representing the Number object to the specified precision.

Parameters:

precision (int) – An integer specifying the number of significant digits.

Returns:

[A string representing a Number object in fixed-point or exponential notation rounded to precision significant digits]

Return type:

str

toString(base=None)[source]

A string for the number in the given radix (2-36; default 10).

Return type:

str

class domonic.javascript.Object(obj=None, *args, **kwargs)[source]

Bases: object

static fromEntries(entries)[source]

transforms a list of lists containing key and value into an object. @param entries: a list containing key and value tuples. The key and value are separated by ‘:’ @type entries: list of tuple(string, string) @returns: a dict object.

>>> fromEntries(entries)
{'a': 1, 'b': 2, 'c': 3}
Return type:

dict[str, Any]

static assign(target, *sources)[source]

Copy the enumerable own properties of each source onto target (left to right) and return target – Object.assign(t, s1, s2, ...).

Return type:

Any

static create(proto, propertiesObject=None)[source]

Creates a new object with the specified prototype object and properties.

Return type:

Any

static defineProperty(obj, prop, descriptor)[source]

Adds the named property described by a given descriptor to an object.

Return type:

Any

static defineProperties(obj, props)[source]

Adds named properties described by descriptors to an object.

Return type:

Any

static entries(obj)[source]

Returns an array containing all of the [key, value] pairs in the object.

Return type:

list[list[Any]]

static keys(obj)[source]

Returns an array containing the names of all of the given object’s own enumerable string properties.

Return type:

list[str]

static values(obj)[source]

Returns an array containing the values that correspond to all of a given object’s own enumerable string properties.

Return type:

list[Any]

static getOwnPropertyDescriptor(obj, prop)[source]

Returns a property descriptor for a named property on an object.

Return type:

Any

static getOwnPropertyNames(obj)[source]

Returns an array containing the names of all of the given object’s own enumerable and non-enumerable properties.

Return type:

list[str] | Any

static getOwnPropertySymbols(obj)[source]

Returns an array of all symbol properties found directly upon a given object.

Return type:

list[str]

static getPrototypeOf(obj)[source]

Returns the prototype (internal [[Prototype]] property) of the specified object.

Return type:

Any

static isExtensible(obj)[source]

Determines if extending an object is allowed.

Return type:

bool

static isSealed(obj)[source]

Determines if an object is sealed.

Return type:

bool

static preventExtensions(obj)[source]

Prevent new properties from being added to an object.

Return type:

Any

static seal(obj)[source]

Prevent extensions and deletion of an object’s existing properties.

Return type:

Any

static isFrozen(obj)[source]

Determines if an object was frozen.

Return type:

bool

static is_(value1, value2)[source]

Object.is – SameValue: like === but NaN equals NaN and +0 differs from -0. (is is a Python keyword.)

Return type:

bool

static hasOwn(obj, key)[source]

Object.hasOwn(obj, key) – a direct (own) property check.

Return type:

bool

static groupBy(items, callback)[source]

Object.groupBy – group items into a dict keyed by callback(item, index).

Return type:

dict

static freeze(obj)[source]

Freeze an object so its properties can no longer be added, removed, or changed. As in JS, the (frozen) object is returned – for a plain dict that is a read-only copy that raises on mutation, so use the return value (cfg = Object.freeze(cfg)).

Return type:

Any

hasOwnProperty(prop)[source]

Returns a boolean indicating whether an object contains the specified property as a direct property of that object and not inherited through the prototype chain.

Return type:

bool

isPrototypeOf(obj)[source]

Returns a boolean indicating whether an object is a copy of this object.

Return type:

bool

toLocaleString()[source]

Calls toString()

Return type:

str

toString()[source]

Returns a string representation of the object.

Return type:

str

valueOf()[source]

Returns the value of the object.

Return type:

Any

is(value2)

Object.is – SameValue: like === but NaN equals NaN and +0 differs from -0. (is is a Python keyword.)

Return type:

bool

class domonic.javascript.Performance[source]

Bases: object

https://developer.mozilla.org/en-US/docs/Web/API/Performance

property timeOrigin: float

Milliseconds since the Unix epoch at which now() read zero.

now()[source]

Milliseconds since timeOrigin, from a monotonic clock.

Return type:

float

mark(name, markOptions=None)[source]
Return type:

PerformanceMark

measure(name, startOrMeasureOptions=None, endMark=None)[source]

measure(name), measure(name, startMark, endMark) or measure(name, {"start": ..., "end": ..., "duration": ..., "detail": ...}).

Return type:

PerformanceMeasure

getEntries()[source]
Return type:

list[PerformanceEntry]

getEntriesByType(entryType)[source]
Return type:

list[PerformanceEntry]

getEntriesByName(name, entryType=None)[source]
Return type:

list[PerformanceEntry]

clearMarks(name=None)[source]
clearMeasures(name=None)[source]
toJSON()[source]
Return type:

dict[str, Any]

exception domonic.javascript.ProgramKilled[source]

Bases: Exception

Raised when a scheduled background job is asked to stop.

class domonic.javascript.Promise(func=None, *args, **kwargs)[source]

Bases: object

data: Any
then(func, onrejected=None)[source]
Return type:

Promise

catch(error)[source]
Return type:

Promise

finally_(onfinally)[source]

promise.finally(fn) – run fn once the promise settles, whichever way. (finally is a Python keyword.)

Return type:

Promise

resolve()
Return type:

Promise

reject()
Return type:

Promise

static all(iterable)[source]

Fulfils with the list of results once every input settles; rejects with the first rejection.

Return type:

Promise

static allSettled(iterable)[source]

Fulfils with a list of {status, value|reason} records.

Return type:

Promise

static race(iterable)[source]

Settles as soon as any input settles.

Return type:

Promise

static any(iterable)[source]

Fulfils with the first fulfilment; rejects with an AggregateError if every input rejects.

Return type:

Promise

finally(onfinally)

promise.finally(fn) – run fn once the promise settles, whichever way. (finally is a Python keyword.)

Return type:

Promise

exception domonic.javascript.RangeError(message='', *args, **kwargs)[source]

Bases: Error, ValueError

name: str = 'RangeError'
exception domonic.javascript.ReferenceError(message='', *args, **kwargs)[source]

Bases: Error, NameError

name: str = 'ReferenceError'
class domonic.javascript.Reflect[source]

Bases: object

The Reflect object provides the following static functions which have the same names as the proxy handler methods. Some of these methods are also the same as corresponding methods on Object, although they do have some subtle differences between them.

static ownKeys(target)[source]

Returns an array of the target object’s own (not inherited) property keys.

Return type:

list[str]

static apply(target, thisArgument, argumentsList)[source]

Calls a target function with arguments as specified by the argumentsList parameter. See also Function.prototype.apply().

Return type:

Any

static construct(target, argumentsList, newTarget=None)[source]

The new operator as a function. Equivalent to calling new target(…argumentsList). Also provides the option to specify a different prototype.

Return type:

Any

static defineProperty(target, propertyKey, attributes)[source]

Similar to Object.defineProperty(). Returns a Boolean that is true if the property was successfully defined.

Return type:

Any

static deleteProperty(target, propertyKey)[source]

The delete operator as a function. Equivalent to calling delete target[propertyKey].

Return type:

Any

static get(target, propertyKey, receiver=None)[source]

Returns the value of the property. Works like getting a property from an object (target[propertyKey]) as a function.

Return type:

Any

static getOwnPropertyDescriptor(target, propertyKey)[source]

Similar to Object.getOwnPropertyDescriptor(). Returns a property descriptor of the given property if it exists on the object, undefined otherwise.

Return type:

Any

getPrototypeOf()

Returns the prototype (internal [[Prototype]] property) of the specified object.

Return type:

Any

static has(target, propertyKey)[source]

Returns a Boolean indicating whether the target has the property. Either as own or inherited. Works like the in operator as a function.

Return type:

Any

static preventExtensions(target)[source]

Similar to Object.preventExtensions(). Returns a Boolean that is true if the update was successful.

Return type:

Any

static set(target, propertyKey, value, receiver=None)[source]

A function that assigns values to properties. Returns a Boolean that is true if the update was successful.

Return type:

Any

static setPrototypeOf(target, prototype)[source]

A function that sets the prototype of an object. Returns a Boolean that is true if the update was successful.

Return type:

Any

class domonic.javascript.RegExp(expression, flags='')[source]

Bases: object

lastIndex

Index at which exec/test resume when the g/y flag is set.

property flags: str

The active flags in canonical order (d g i m s u v y).

property dotAll: bool

Whether . matches newlines or not.

Returns:

True if dot matches newlines, False otherwise

Return type:

bool

property multiline: bool

Whether . matches newlines or not. :returns: True if dot matches newlines, False otherwise :rtype: bool

property source: str

The text of the pattern. :returns: The text of the pattern. :rtype: str

property sticky: bool

Whether the match is anchored at lastIndex (the y flag).

property global_: bool

Whether to test the regular expression against all possible matches in a string, or only against the first.

Returns:

True if global, False otherwise

Return type:

bool

property hasIndices: bool

Whether the regular expression result exposes the start and end indices of captured substrings.

Returns:

True if hasIndices, False otherwise

Return type:

bool

property ignoreCase: bool

Whether to ignore case while attempting a match in a string.

Returns:

True if ignoreCase, False otherwise

Return type:

bool

property unicode: bool

Whether or not Unicode features are enabled.

Returns:

True if unicode, False otherwise

Return type:

bool

compile(expression=None, flags=None)[source]

(Re-)compiles a regular expression during execution of a script.

Return type:

RegExp

exec(s)[source]

Search s for a match.

Returns None on no match. Otherwise a list whose [0] is the full match and [1:] the capture groups, with .index / .input / .groups attributes (JavaScript’s RegExp.exec). When the g or y flag is set, the search resumes from lastIndex and advances it.

replace(string, replacement)[source]

regexp.replace(str, repl) – JavaScript’s RegExp[Symbol.replace].

Equivalent to String(str).replace(self, repl): honours the g flag and expands $1 / $& / $<name> in a string replacement.

Return type:

str

split(string, limit=None)[source]
Return type:

list[str]

test(s)[source]

Tests for a match in its string parameter.

Parameters:

s (str) – a string to match

Returns:

True if match else False

Return type:

bool

toString()[source]

/source/flags – like JavaScript’s RegExp.prototype.toString.

Return type:

str

class domonic.javascript.Screen(width=1024, height=768, *, availWidth=None, availHeight=None, colorDepth=24, pixelDepth=None)[source]

Bases: object

Lightweight representation of the browser Screen object.

class domonic.javascript.Set(*args)[source]

Bases: object

property args: list[Any]

The Set’s values as a list, in insertion order (legacy accessor).

property species: Any

The constructor function that is used to create derived objects.

property size: int

Returns the number of values in the Set object.

add(value)[source]

Append a value and return this Set.

Return type:

Set

clear()[source]

Removes all elements from the Set object.

delete(value)[source]

Removes the element associated to the value returns a boolean asserting whether an element was successfully removed or not.

Return type:

bool

remove(value)[source]

Remove a value using Python set semantics.

has(value)[source]

Returns a boolean asserting whether an element is present with the given value in the Set object or not.

Return type:

bool

contains(value)[source]

Returns a boolean asserting whether an element is present with the given value in the Set object or not.

Return type:

bool

values()[source]

Returns a new iterator object that yields the values for each element in the Set object in insertion order.

Return type:

Iterator[Any]

keys()[source]

Alias for values, matching JavaScript Set.

Return type:

Iterator[Any]

entries()[source]

Returns a new iterator object that contains an array of [value, value] for each element in the Set object, in insertion order.

Return type:

Iterator[list[Any]]

forEach(callbackFn, thisArg=None)[source]

Calls callbackFn once for each value present in the Set object, in insertion order. If a thisArg parameter is provided, it will be used as the this value for each invocation of callbackFn.

class domonic.javascript.SetInterval(function, time, *args, **kwargs)[source]

Bases: object

signal_handler(signum, frame)[source]
class domonic.javascript.Storage(filepath=None)[source]

Bases: object

storage: dict[str, str]
filepath: str
has_file: bool
property length: int

Returns an integer representing the number of data items stored in the Storage object.

getItem(keyName)[source]

Return the stored value for keyName or None.

Return type:

str | None

setItem(keyName, value)[source]

Store value under keyName using Web Storage string coercion.

key(index)[source]

Return the key name at index or None when out of range.

Return type:

str | None

removeItem(keyName)[source]

Remove keyName and its value from storage.

clear()[source]

Removes all items from the storage

keys()[source]
values()[source]
items()[source]
toJSON()[source]
Return type:

dict[str, str]

class domonic.javascript.String(x='', *args, **kwargs)[source]

Bases: str

JavaScript String.

Subclasses str so String(x) is a real string primitive (like Number(float)) – isinstance(String(5), str) is True and it interoperates everywhere a str is expected – while still carrying the JS method surface (charAt, padStart, UTF-16 length, …). self.x is kept as a read-only alias of the string content so the ~180 internal references keep working.

Return type:

String

property x: str
static fromCodePoint(codePoint)[source]

Converts a Unicode code point into a string.

For an astral code point (> 0xFFFF), JS represents the result as a UTF-16 surrogate pair, so .length is 2 even though it’s one character – returning a domonic String (rather than a bare Python str) preserves that via its own UTF-16-aware .length. Python’s builtin len() still reports 1, since Python strings are indexed by code point, not UTF-16 code unit.

Return type:

str

static toCodePoint(char)[source]

Converts a Unicode string into a code point

Return type:

int

static raw(template, *substitutions)[source]

String.raw – the tag function for raw template literals.

template is the strings object ({"raw": [...]} or anything with a raw sequence); the raw segments are interleaved with substitutions. A plain string is returned unchanged, so String.raw(r"a\nb") still works.

Return type:

str

static toCharCode(char)[source]

Converts a Unicode string into a code point

Return type:

int

split(expr=None, limit=None)[source]

String.prototype.split(separator, limit).

A RegExp separator with capture groups keeps the captures in the result (like JS); "" splits into individual characters; limit truncates the result.

Return type:

list[str]

concat(*args, seperator='')[source]

Concatenates the string arguments to the calling string and returns a new string.

Parameters:
  • args (str) – The strings to concatenate.

  • seperator (str, optional) – The separator placed between each string. Defaults to “”.

Returns:

A new string containing the combined text of the strings provided.

Return type:

str

charCodeAt(index)[source]

The UTF-16 code unit at index; NaN (the number) when out of range, so s.charCodeAt(past_end) <= 0xffff is simply False.

Return type:

Any

static fromCharCode(*codes)[source]

A string built from a sequence of UTF-16 code units.

Static, like String.fromCharCode(...) in JavaScript. Adjacent surrogate code units are combined (fromCharCode(0xD83D, 0xDE00) -> "😀"); a lone surrogate is kept as-is.

Return type:

str

property length: int

The number of UTF-16 code units (astral characters count as two).

repeat(count)[source]

Returns a new string with a specified number of copies of an existing string

Return type:

str

startsWith(x, position=None)[source]

String.prototype.startsWith(searchString, position=0).

Return type:

bool

substring(start, end=None)[source]

The code units between two indices (negatives clamp to 0, args swap if out of order) – code-unit based, like JavaScript.

Return type:

str

endsWith(x, endPosition=None)[source]

String.prototype.endsWith(searchString, endPosition=length) – treats the string as if it ended at endPosition.

Return type:

bool

toLowerCase()[source]

Converts a string to lowercase letters

Return type:

str

toUpperCase()[source]

Converts a string to uppercase letters

Return type:

str

slice(start=0, end=None)[source]

A slice of the string in code-unit space (negative indices count from the end), like JavaScript.

Return type:

str

trim()[source]

Removes whitespace from both ends of a string

Return type:

str

at(index)[source]

The code unit at index as a string (negative counts from the end), or undefined when out of range.

Return type:

Any

normalize(form='NFC')[source]

Unicode normalisation (NFC / NFD / NFKC / NFKD).

Return type:

str

charAt(index)[source]

The UTF-16 code unit at index as a one-‘character’ string (a lone surrogate for one half of an astral character); "" when out of range.

Return type:

str

replace(old, new)[source]

Searches a string for a specified value, or a regular expression, and returns a new string where the specified values are replaced. only replaces first one.

Return type:

str

replaceAll(old, new)[source]

returns a new string where the specified values are replaced. ES2021

Parameters:
  • old (str | RegExp) – word or global pattern to remove

  • new (str | Callable) – replacement; $1 etc. work with a RegExp

Returns:

new string with all occurrences of old replaced

Return type:

str

substr(start=0, length=None)[source]

length code units starting at start (negative start counts from the end) – code-unit based, like JavaScript.

Return type:

str

toLocaleLowerCase()[source]

Converts a string to lowercase letters, according to the host’s locale

Return type:

str

toLocaleUpperCase()[source]

Converts a string to uppercase letters, according to the host’s locale

Return type:

str

indexOf(searchValue, fromIndex=0)[source]

Returns the index within the calling String object of the first occurrence of the specified value, starting the search at fromIndex.

Parameters:
  • searchValue (str) – The string value to search for.

  • fromIndex (int) – An integer representing the index at which to start the search.

Returns:

The index of the first occurrence of searchValue, or -1 if not found.

Return type:

int

codePointAt(index)[source]

Returns the Unicode code point at the specified index (position).

Parameters:

index (int) – The index position.

Returns:

The Unicode code point at the specified index, or None.

Return type:

int | None

padEnd(length, padChar=' ')[source]

Pads the end of a string with a specified character (repeated, if needed) to create a new string.

Parameters:
  • length (int) – the length of the resulting string

  • padChar (str, optional) – the character to use for padding. Defaults to “ “.

Returns:

the padded string

Return type:

str

padStart(length, padChar=' ')[source]

Pads the start of a string with a specified character

Parameters:
  • length (int) – the length of the resulting string

  • padChar (str, optional) – the character to use for padding. Defaults to “ “.

Returns:

the padded string

Return type:

str

localeCompare(comparisonString, locale=None, *args)[source]

method returns a number indicating whether a reference string comes before, or after, or is the same as the given string in sort order

Return type:

int

trimStart()[source]

Removes whitespace from the beginning of a string.

Return type:

str

trimEnd()[source]

Removes whitespace from the end of a string.

Return type:

str

includes(searchValue, position=0)[source]

Returns true if the specified string is found within the calling String object.

Parameters:
  • searchValue (str) – The string value to search for.

  • position (int, optional) – The position to search from. Defaults to 0.

Returns:

True if the search value was found, otherwise False.

Return type:

bool

search(value)[source]

String.prototype.search – the index of the first match, or -1.

A non-RegExp value is converted with new RegExp(value) (it is not escaped), matching JavaScript.

Return type:

int

matchAll(pattern)[source]

String.prototype.matchAll – an iterator of match arrays.

Each item is [fullMatch, *groups] with .index / .input / .groups (named groups), like RegExp.exec.

Return type:

Iterator[_RegExpMatch]

match(pattern)[source]

String.prototype.match.

Without the g flag: [fullMatch, *groups] with .index / .input / .groups, or None. With the g flag: a plain list of every full match, or None when there is no match.

Return type:

_RegExpMatch | list[str] | None

compile(pattern)[source]

Searches a string for a specified value, or a regular expression, and returns a new string where the specified values are replaced. only replaces first one.

Return type:

Pattern[str]

lastIndexOf(searchValue, fromIndex=None)[source]

returns the last index within the calling String object of the first occurrence of the specified value, starting the search at fromIndex

Return type:

int

anchor(name)[source]
Return type:

str

big()[source]

wraps the string in big tags

Returns:

the string in big tags

Return type:

str

blink()[source]

wraps the string in blink tags

Returns:

the string in blink tags

Return type:

str

bold()[source]

wraps the string in bold tags

Returns:

the string in bold tags

Return type:

str

fixed()[source]

wraps the string in fixed tags

Returns:

the string in fixed tags

Return type:

str

fontcolor(color)[source]

wraps the string in font tags with a specified color

Parameters:

color (str) – the color to use

Returns:

the string in font tags

Return type:

str

fontsize(size)[source]

wraps the string in font tags with a specified size

Parameters:

size (str) – the size to use

Returns:

the string in font tags

Return type:

str

italics()[source]

wraps the string in italics tags

Returns:

the string in italics tags

Return type:

str

link(url)[source]

wraps the string in a link tag

Parameters:

url (str) – the url to use

Returns:

the string in a link tag

Return type:

str

small()[source]

wraps the string in small tags

Returns:

the string in small tags

Return type:

str

strike()[source]

wraps the string in strike tags

Returns:

the string in strike tags

Return type:

str

sub()[source]

wraps the string in sub tags

Returns:

the string in sub tags

Return type:

str

sup()[source]

wraps the string in sup tags

Returns:

the string in sup tags

Return type:

str

div(*args, **kwargs)[source]

wraps the string in a div tag

Returns:

the string in a div tag

Return type:

str

webpage()[source]

wraps the string in a webpage

Returns:

the string as a webpage

Return type:

str

class domonic.javascript.Symbol(symbol)[source]

Bases: object

registry: list[Symbol] = []
hasInstance(obj)[source]

A method determining if a constructor object recognizes an object as its instance. Used by instanceof.

Parameters:

obj (Symbol) – A constructor object.

Returns:

True if obj is an instance of this symbol, False otherwise.

Return type:

bool

isConcatSpreadable()[source]

A Boolean value indicating if an object should be flattened to its array elements. Used by Array.prototype.concat().

Return type:

bool

iterator(obj)[source]

A method returning the default iterator for an object. Used by for…of.

Return type:

Iterator[Any]

asyncIterator(obj)[source]

A method that returns the default AsyncIterator for an object. Used by for await…of.

Return type:

Iterator[Any]

match(item)[source]

A method that matches the symbol against a string, also used to determine if an object may be used as a regular expression.

Return type:

Any

search(value)[source]
Return type:

int

split(value)[source]
Return type:

list[str]

species()[source]
Return type:

type[Symbol]

toPrimitive()[source]
Return type:

Any

toStringTag()[source]
Return type:

str

unscopables()[source]
Return type:

dict[str, bool]

toSource()[source]

Returns a string containing the source of the Symbol. Overrides the Object.prototype.toSource() method.

Return type:

Any

toString()[source]

Returns a string containing the description of the Symbol. Overrides the Object.prototype.toString() method.

Return type:

Any

valueOf()[source]

Returns the Symbol. Overrides the Object.prototype.valueOf() method.

Return type:

Any

domonic.javascript.ToInt32(v)[source]
Return type:

int

domonic.javascript.ToUint32(v)[source]
Return type:

int

class domonic.javascript.TypedArray(*args)[source]

Bases: object

BYTES_PER_ELEMENT: int = 1
length: int
byteLength: int
buffer: Any
byteOffset: int
property args: Any
static of(*args)[source]
Return type:

Any

static from_(thing)[source]
Return type:

Any

get(index)
Return type:

Any

set(index, value=None)[source]
subarray(start, end)[source]
exception domonic.javascript.URIError(message='', *args, **kwargs)[source]

Bases: Error

name: str = 'URIError'
class domonic.javascript.URL(url='', base=None, *args, **kwargs)[source]

Bases: object

a-tag extends from URL

property href: str
property searchParams: URLSearchParams
property origin: str
toString()[source]
Return type:

str

static canParse(url, base=None)[source]
Return type:

bool

static parse(url, base=None)[source]
Return type:

URL | None

static createObjectURL(obj)[source]
Return type:

str

static revokeObjectURL(url)[source]
property protocol: str
property hostname: str | None
property port: int | None
property username: str
property password: str
property host: str | None
property pathname: str
property search: str
property hash: str

“ hash Sets or returns the anchor part (#) of a URL

static domainToASCII(domain)[source]

Return the Punycode ASCII serialization of a domain.

Return type:

str

static domainToUnicode(domain)[source]

Return the Unicode serialization of a domain.

Return type:

str

static fileURLToPath(url)[source]

Return a local filesystem path for a file: URL.

Return type:

str

static pathToFileURL(path)[source]

Return a file URL for a local filesystem path.

Return type:

URL

class domonic.javascript.URLSearchParams(paramString='', _update=None)[source]

Bases: object

utility methods to work with the query string of a URL

params: dict[str, list[str]]
append(key, value)[source]

Appends a specified key/value pair as a new search parameter

delete(key, value=None)[source]

Deletes the given search parameter, and its associated value, from the list of all search parameters.

has(key, value=None)[source]

Returns a Boolean indicating if such a given parameter exists.

Return type:

bool

entries()[source]

Returns an iterator allowing iteration through all key/value pairs contained in this object.

Return type:

Iterable[tuple[str, list[str]]]

pairs()[source]

Returns each key/value pair, including duplicates.

Return type:

Iterable[tuple[str, str]]

forEach(func)[source]

Allows iteration through all values contained in this object via a callback function.

keys()[source]

Returns an iterator allowing iteration through all keys of the key/value pairs contained in this object.

Return type:

Iterable[str]

get(key)[source]

Returns the first value associated with the given search parameter.

Return type:

str | None

sort()[source]

Sorts all key/value pairs, if any, by their keys.

property size: int
values()[source]

Returns an iterator allowing iteration through all values of the key/value pairs contained in this object.

Return type:

Iterable[list[str]]

toString()[source]

Returns a string containing a query string suitable for use in a URL.

Return type:

str

set(key, value)[source]

Sets the value associated with a given search parameter to the given value. If there are several values, the others are deleted.

getAll(key)[source]

Returns all the values associated with a given search parameter.

Return type:

list[str]

class domonic.javascript.Uint16Array(*args)[source]

Bases: TypedArray

name = 'Uint16Array'
BYTES_PER_ELEMENT: int = 2
class domonic.javascript.Uint32Array(*args)[source]

Bases: TypedArray

name = 'Uint32Array'
BYTES_PER_ELEMENT: int = 4
class domonic.javascript.Uint8Array(*args)[source]

Bases: TypedArray

name = 'Uint8Array'
BYTES_PER_ELEMENT: int = 1
class domonic.javascript.Uint8ClampedArray(*args)[source]

Bases: TypedArray

name = 'Uint8ClampedArray'
BYTES_PER_ELEMENT: int = 1
class domonic.javascript.Window(*args, **kwargs)[source]

Bases: object

window

localStorage = <domonic.webapi.webstorage.Storage object>
location = ''
screen = <domonic.javascript.Screen object>
static alert(msg)[source]

Displays an alert box with a message and an OK button

static prompt(msg, default_text='')[source]

Displays a dialog box that prompts the visitor for input

Return type:

str

setTimeout(t, *args, **kwargs)

sets a timer which executes a function or evaluates an expression after a specified delay

Parameters:
  • callback (function) – method to be executed after the delay

  • t (int) – milliseconds

Returns:

an identifier for the timer

Return type:

str

clearTimeout()

cancels a timer set with setTimeout()

Parameters:

timeoutID (str) – the identifier returned by setTimeout()

static clearInterval(job)[source]
static setInterval(function, time, *args, **kwargs)[source]
Return type:

Job

static fetch(url, **kwargs)[source]
Return type:

Promise

async static fetch_async(url, **kwargs)[source]

Fetch a URL without blocking the current asyncio event loop.

Return type:

Any

static fetch_set(urls, callback_function=None, error_handler=None, **kwargs)[source]
Return type:

FetchedSet

static fetch_threaded(urls, callback_function=None, error_handler=None, **kwargs)[source]
Return type:

FetchedSet

static fetch_pooled(urls, callback_function=None, error_handler=None, **kwargs)[source]
Return type:

FetchedSet

static btoa(dataString)[source]

Encodes a string in base-64

Return type:

bytes

static atob(dataString)[source]

Decodes a base-64 encoded string

Return type:

str

static requestAnimationFrame(callback)[source]

Requests a frame of an animation.

Parameters:

callback (callable) – The callback function, invoked with the current performance time.

Returns:

The callback’s return value.

Return type:

Any

class domonic.javascript.Worker(scriptURL, options=None)[source]

Bases: Worker

Background worker exposed from the legacy domonic.javascript namespace.

domonic.javascript.as_signed(value, bits)[source]

Converts an unsigned integer to a signed integer.

Return type:

int

domonic.javascript.as_unsigned(value, bits)[source]
Return type:

int

domonic.javascript.atob(data)[source]

Decode a base64 string to a binary (Latin-1) string.

Return type:

str

domonic.javascript.btoa(data)[source]

Base64-encode a binary (Latin-1) string.

Return type:

str

domonic.javascript.clearInterval(job)
domonic.javascript.clearTimeout(timeoutID)

cancels a timer set with setTimeout()

Parameters:

timeoutID (str) – the identifier returned by setTimeout()

domonic.javascript.decodeURI(x)

Decodes a URI

Return type:

str

domonic.javascript.decodeURIComponent(x)

Decodes a URI component

Return type:

str

domonic.javascript.encodeURI(x)

Encodes a URI

Return type:

str

domonic.javascript.encodeURIComponent(x)

Encodes a URI component

Return type:

str

domonic.javascript.function(python_str)[source]

[evals a string i.e.

sup = function(‘’’print(hi)’’’) sup()

]

Parameters:

python_str (str) – some valid python code as a string

Return type:

Callable[[], Any]

domonic.javascript.globalThis

alias of Global

domonic.javascript.isFinite(x)

Returns true if x coerces to a finite number.

Return type:

bool

domonic.javascript.isNaN(x)

Determines whether a value coerces to NaN.

Return type:

bool

domonic.javascript.parse(timestr, parserinfo=None, **kwargs)[source]

Parse a string in one of the supported formats, using the parserinfo parameters.

Parameters:
  • timestr – A string containing a date/time stamp.

  • parserinfo – A parserinfo object containing parameters for the parser. If None, the default arguments to the parserinfo constructor are used.

The **kwargs parameter takes the following keyword arguments:

Parameters:
  • default – The default datetime object, if this is a datetime object and not None, elements specified in timestr replace elements in the default object.

  • ignoretz – If set True, time zones in parsed strings are ignored and a naive datetime object is returned.

  • tzinfos –

    Additional time zone names / aliases which may be present in the string. This argument maps time zone names (and optionally offsets from those time zones) to time zones. This parameter can be a dictionary with timezone aliases mapping time zone names to time zones or a function taking two parameters (tzname and tzoffset) and returning a time zone.

    The timezones to which the names are mapped can be an integer offset from UTC in seconds or a tzinfo object.

    This parameter is ignored if ignoretz is set.

  • dayfirst – Whether to interpret the first value in an ambiguous 3-integer date (e.g. 01/05/09) as the day (True) or month (False). If yearfirst is set to True, this distinguishes between YDM and YMD. If set to None, this value is retrieved from the current parserinfo object (which itself defaults to False).

  • yearfirst – Whether to interpret the first value in an ambiguous 3-integer date (e.g. 01/05/09) as the year. If True, the first number is taken to be the year, otherwise the last number is taken to be the year. If this is set to None, the value is retrieved from the current parserinfo object (which itself defaults to False).

  • fuzzy – Whether to allow fuzzy parsing, allowing for string like “Today is January 1, 2047 at 8:21:00AM”.

  • fuzzy_with_tokens – If True, fuzzy is automatically set to True, and the parser will return a tuple where the first element is the parsed datetime.datetime datetimestamp and the second element is a tuple containing the portions of the string which were ignored:

Returns:

Returns a datetime.datetime object or, if the fuzzy_with_tokens option is True, returns a tuple, the first element being a datetime.datetime object, the second a tuple containing the fuzzy tokens.

Raises:
  • ParserError – Raised for invalid or unknown string formats, if the provided tzinfo is not in a valid format, or if an invalid date would be created.

  • OverflowError – Raised if the parsed date exceeds the largest valid C integer on your system.

domonic.javascript.parseFloat(x)

Parses a string and returns a floating point number

Return type:

float

domonic.javascript.parseInt(x, radix=0)

Parses a string and returns an integer

Return type:

int | float

domonic.javascript.parsedate_to_datetime(data)[source]
class domonic.javascript.parserinfo(dayfirst=False, yearfirst=False)[source]

Bases: object

Class which handles what inputs are accepted. Subclass this to customize the language and acceptable values for each parameter.

Parameters:
  • dayfirst – Whether to interpret the first value in an ambiguous 3-integer date (e.g. 01/05/09) as the day (True) or month (False). If yearfirst is set to True, this distinguishes between YDM and YMD. Default is False.

  • yearfirst – Whether to interpret the first value in an ambiguous 3-integer date (e.g. 01/05/09) as the year. If True, the first number is taken to be the year, otherwise the last number is taken to be the year. Default is False.

JUMP = [' ', '.', ',', ';', '-', '/', "'", 'at', 'on', 'and', 'ad', 'm', 't', 'of', 'st', 'nd', 'rd', 'th']
WEEKDAYS = [('Mon', 'Monday'), ('Tue', 'Tuesday'), ('Wed', 'Wednesday'), ('Thu', 'Thursday'), ('Fri', 'Friday'), ('Sat', 'Saturday'), ('Sun', 'Sunday')]
MONTHS = [('Jan', 'January'), ('Feb', 'February'), ('Mar', 'March'), ('Apr', 'April'), ('May', 'May'), ('Jun', 'June'), ('Jul', 'July'), ('Aug', 'August'), ('Sep', 'Sept', 'September'), ('Oct', 'October'), ('Nov', 'November'), ('Dec', 'December')]
HMS = [('h', 'hour', 'hours'), ('m', 'minute', 'minutes'), ('s', 'second', 'seconds')]
AMPM = [('am', 'a'), ('pm', 'p')]
UTCZONE = ['UTC', 'GMT', 'Z', 'z']
PERTAIN = ['of']
TZOFFSET = {}
jump(name)[source]
weekday(name)[source]
month(name)[source]
hms(name)[source]
ampm(name)[source]
pertain(name)[source]
utczone(name)[source]
tzoffset(name)[source]
convertyear(year, century_specified=False)[source]

Converts two-digit years to year within [-50, 49] range of self._year (current local time)

validate(res)[source]
domonic.javascript.queueMicrotask(callback)[source]

Queue a microtask. domonic has no event loop, so it runs synchronously on the next tick-equivalent – immediately.

domonic.javascript.quote('abc def') → 'abc%20def'[source]

Each part of a URL, e.g. the path info, the query, etc., has a different set of reserved characters that must be quoted. The quote function offers a cautious (not minimal) way to quote a string for most of these parts.

RFC 3986 Uniform Resource Identifier (URI): Generic Syntax lists the following (un)reserved characters.

unreserved = ALPHA / DIGIT / “-” / “.” / “_” / “~” reserved = gen-delims / sub-delims gen-delims = “:” / “/” / “?” / “#” / “[” / “]” / “@” sub-delims = “!” / “$” / “&” / “’” / “(” / “)”

/ “*” / “+” / “,” / “;” / “=”

Each of the reserved characters is reserved in some component of a URL, but not necessarily in all of them.

The quote function %-escapes all characters that are neither in the unreserved chars (“always safe”) nor the additional chars set via the safe arg.

The default for the safe arg is ‘/’. The character is reserved, but in typical usage the quote function is being called on a path where the existing slash characters are to be preserved.

Python 3.7 updates from using RFC 2396 to RFC 3986 to quote URL strings. Now, “~” is included in the set of unreserved characters.

string and safe may be either str or bytes objects. encoding and errors must not be specified if string is a bytes object.

The optional encoding and errors parameters specify how to deal with non-ASCII characters, as accepted by the str.encode method. By default, encoding=’utf-8’ (characters are encoded with UTF-8), and errors=’strict’ (unsupported characters raise a UnicodeEncodeError).

domonic.javascript.setInterval(function, time, *args, **kwargs)
Return type:

Job

domonic.javascript.setTimeout(callback, t, *args, **kwargs)

sets a timer which executes a function or evaluates an expression after a specified delay

Parameters:
  • callback (function) – method to be executed after the delay

  • t (int) – milliseconds

Returns:

an identifier for the timer

Return type:

str

domonic.javascript.structuredClone(value, options=None)[source]

A deep clone of value (the structured-clone algorithm, approximated with copy.deepcopy()).

Return type:

Any

class domonic.javascript.timezone

Bases: tzinfo

Fixed offset from UTC implementation of tzinfo.

dst()

Return None.

fromutc()

datetime in UTC -> datetime in local time.

max = datetime.timezone(datetime.timedelta(seconds=86340))
min = datetime.timezone(datetime.timedelta(days=-1, seconds=60))
tzname()

If name is specified when timezone is created, returns the name. Otherwise returns offset as ‘UTC(+|-)HH:MM’.

utc = datetime.timezone.utc
utcoffset()

Return fixed offset.

domonic.javascript.unquote(string, encoding='utf-8', errors='replace')[source]

Replace %xx escapes by their single-character equivalent. The optional encoding and errors parameters specify how to decode percent-encoded sequences into Unicode characters, as accepted by the bytes.decode() method. By default, percent-encoded sequences are decoded with UTF-8, and invalid sequences are replaced by a placeholder character.

unquote(‘abc%20def’) -> ‘abc def’.

domonic.javascript.window

alias of Window