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:
objectSpecial 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:
objectjavascript 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 likeArray.from(iterable, fn)in JS.- Return type:
- 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:
- prototype
alias of
Array
- 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:
- flat(depth=1)[source]
Flattens an array into a single-dimensional array or a depth of arrays
- 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
- 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:
- findLast(callback=None)[source]
Returns the last element in an array that passes a test
- Return type:
- findLastIndex(callback=None)[source]
Returns the last index of an element in an array that passes a test
- Return type:
- includes(value)[source]
[Check if an array contains the specified item
- Parameters:
value (any) – any value
- Returns:
a boolean
- Return type:
- indexOf(value, fromIndex=0)[source]
Search the array for an element and returns its position
- Return type:
- static isArray(thing)[source]
Checks whether an object is an array.
- lastIndexOf(value, fromIndex=None)[source]
Search the array for an element, starting at the end, and returns its position
- Return type:
- push(value)[source]
Adds new elements to the end of an array, and returns the new length
- Return type:
- slice(start=0, stop=None, step=1)[source]
Selects a part of an array, and returns the new array.
- splice(start, delete_count=None, *items)[source]
Selects a part of an array, and returns the new array
- 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:
- 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:
- toReversed()[source]
A reversed copy (the original array is left unchanged) – ES2023.
- Return type:
- toSorted(func=None)[source]
A sorted copy (the original array is left unchanged) – ES2023.
- Return type:
- toSpliced(start, deleteCount=None, *items)[source]
A copy with a splice applied (the original is unchanged) – ES2023.
- Return type:
- with_(index, value)[source]
A copy with
indexreplaced byvalue– ES2023Array#with(withis a Python keyword).- Return type:
- 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:
- 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:
- 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 )
- find(func=None)[source]
Returns the value of the first element in an array that pass a test
- Return type:
- findIndex(predicate)[source]
Index of the first element for which
predicateis truthy (a bare value is also accepted, as a domonic convenience), or -1.- Return type:
- 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
- values()[source]
Returns a new array iterator object that yields each element’s value.
- copyWithin(target, start=0, end=None)[source]
Shallow-copy the
[start, end)slice totargetwithin the same array (indices may be negative), and return the array.
- entries()[source]
Returns a key/value pair Array Iteration Object.
- 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.
- with(index, value)
A copy with
indexreplaced byvalue– ES2023Array#with(withis a Python keyword).- Return type:
- class domonic.javascript.ArrayBuffer(length)[source]
Bases:
object- buffer: Any
- property byteLength: int
- property length: int
- 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:
objectCreates a Boolean Object. Warning this is NOT a boolean type. for that use Global.Boolean()
- value: bool
- class domonic.javascript.DataView(buffer, byteOffset=0, byteLength=None)[source]
Bases:
ArrayBuffer- property byteLength: int
- 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:
Objectjavascript date
- static parse(date_string)[source]
Parses a date string and returns the number of milliseconds since January 1, 1970
- Return type:
- 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:
- getTime()[source]
Returns A number representing the milliseconds elapsed between 1 January 1970 00:00:00 UTC and self.date
- Return type:
- 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:
- getUTCDate()[source]
Returns the day of the month, according to universal time (from 1-31)
- Return type:
- getUTCDay()[source]
Returns the day of the week, according to universal time (from 0-6)
- Return type:
- getUTCMilliseconds()[source]
Returns the milliseconds, according to universal time (from 0-999)
- Return type:
- getUTCMinutes()[source]
Returns the minutes, according to universal time (from 0-59)
- Return type:
- getUTCSeconds()[source]
Returns the seconds, according to universal time (from 0-59)
- Return type:
- setDate(day)[source]
Sets the day of the month of a date object
- setFullYear(yearValue, monthValue=None, dateValue=None)[source]
Sets the year of a date object
- setHours(hoursValue, minutesValue=None, secondsValue=None, msValue=None)[source]
Sets the hour of a date object
- Parameters:
- Returns:
milliseconds between epoch and updated date.
- Return type:
- setMilliseconds(milliseconds)[source]
Sets the milliseconds of a date object
- setMinutes(minutesValue, secondsValue=None, msValue=None)[source]
Set the minutes of a date object
- setMonth(monthValue, dayValue=None)[source]
Sets the month of a date object
- setSeconds(secondsValue, msValue=None)[source]
Sets the seconds of a date object
- setTime(milliseconds=None, tz=None)[source]
Sets the date and time of a date object
- setUTCDate(day)[source]
Sets the day of the month of a date object, according to universal time
- Return type:
- setUTCFullYear(year)[source]
Sets the year of a date object, according to universal time
- Return type:
- setUTCHours(hour)[source]
Sets the hour of a date object, according to universal time
- Return type:
- setUTCMilliseconds(milliseconds)[source]
Sets the milliseconds of a date object, according to universal time
- Return type:
- setUTCMinutes(minutes)[source]
Set the minutes of a date object, according to universal time
- Return type:
- setUTCMonth(month)[source]
Sets the month of a date object, according to universal time
- Return type:
- setUTCSeconds(seconds)[source]
Set the seconds of a date object, according to universal time
- Return type:
- toDateString()[source]
Converts the date portion of a Date object into a readable string
- Return type:
- toUTCString()[source]
Converts a Date object to a string, according to universal time
- Return type:
- toJSON()[source]
Returns the date as a string, formatted as a JSON date (same as toISOString)
- Return type:
- toISOString()[source]
Returns the date as a string, using the ISO standard: YYYY-MM-DDTHH:mm:ss.sssZ, always in UTC.
- Return type:
- toLocaleDateString()[source]
Returns the date portion of a Date object as a string, using locale conventions
- Return type:
- toLocaleString()[source]
Converts a Date object to a string, using locale conventions
- Return type:
- toLocaleTimeString()[source]
Returns the time portion of a Date object as a string, using locale conventions
- Return type:
- 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.monthIndexis 0-based and fields overflow, as in JavaScript.- Return type:
- exception domonic.javascript.Error(message='', *args, **kwargs)[source]
Bases:
ExceptionJavaScript
Error.namedefaults to"Error";str(err)is"Error: message"(just"Error"when there is no message).- name: str = 'Error'
- exception domonic.javascript.EvalError(message='', *args, **kwargs)[source]
Bases:
Error- name: str = 'EvalError'
- 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:
objectCompatibility wrapper for
domonic.webapi.xhr.FormData.- Return type:
- class domonic.javascript.Function(func, *args, **kwargs)[source]
Bases:
Objecta Function object
- apply(thisArg=None, args=None, **kwargs)[source]
Calls a function with a given this value, and arguments provided as an array.
- 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.
- class domonic.javascript.Global[source]
Bases:
objectjavascript 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:
- clearInterval()
- static eval(pythonstring)[source]
Evaluates a string and executes it as if it was script code
- Return type:
- static Number(x)[source]
Converts a value to a number, JS-style (non-numeric -> NaN).
- static String(x='')[source]
Converts a value to a string the way JavaScript’s
String(x)does.- Return type:
- undefined()[source]
Indicates that a variable has not been assigned a value
- static setTimeout(callback, t, *args, **kwargs)[source]
sets a timer which executes a function or evaluates an expression after a specified delay
- 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.
- static supportedValuesOf(*args)[source]
Returns a sorted array containing the supported unique calendar, collation, currency, numbering systems, or unit values supported by the implementation.
- Collator
alias of
_Collator
- DateTimeFormat
alias of
_DateTimeFormat
- NumberFormat
alias of
_NumberFormat
- domonic.javascript.IterableABC
alias of
Iterable
- class domonic.javascript.JSON[source]
Bases:
objectJSON.parse/JSON.stringify– JavaScript’s global JSON object.Thin wrapper over
domonic.JSONso ports canfrom domonic.javascript import JSONand call it the browser way.
- 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:
objectMap holds key-value pairs and remembers the original insertion order of the keys.
Keys are compared by SameValueZero, exactly like a real JS
Map–1and"1"are different keys, objects compare by reference, and everyNaNcollapses to one key – not by stringifying every key (which would make1and"1"collide, and turn an object key into unreliable, possibly non-uniquerepr()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:
- get(key, default=None)[source]
Returns the value associated to the key, or undefined if there is none.
- Return type:
- has(key)[source]
Returns a boolean asserting whether a value has been associated to the key in the Map object or not.
- Return type:
- set(key, value)[source]
Sets the value for the key in the Map object. Returns the Map object.
- Return type:
- keys()[source]
Returns a new Iterator object that contains the keys for each element in the Map object in insertion order.
- values()[source]
Returns a new Iterator object that contains the values for each element in the Map object in insertion order.
- entries()[source]
Returns a new Iterator object that contains an array of [key, value] for each element in the Map object in insertion order.
- 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:
ObjectMath 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.
- static acos(x)[source]
Returns the arccosine (in radians) of a number.
- static atan2(x, y)[source]
Returns the arctangent of the quotient of its arguments.
- Return type:
- static ceil(x)[source]
Returns the smallest integer greater than or equal to a number.
- Return type:
- static floor(x)[source]
Returns the largest integer less than or equal to a number.
- Return type:
- static log(x, base=None)[source]
Returns the natural logarithm (base E) of a number.
- Return type:
- static max(*args)[source]
The largest of the arguments (
-Infinityfor none,NaNif any isNaN) – variadic, like JavaScript.- Return type:
- static min(*args)[source]
The smallest of the arguments (
Infinityfor none,NaNif any isNaN) – variadic, like JavaScript.- Return type:
- static round(x)[source]
Nearest integer; ties round toward +Infinity (JavaScript).
- Return type:
- static hypot(*args)[source]
Return the square root of the sum of squares of its arguments.
- Return type:
- static log10(x)[source]
function returns the base 10 logarithm of a number, that is
- Return type:
- static fround(x)[source]
returns the nearest 32-bit single precision float representation of a Number
- Return type:
- class domonic.javascript.Number(x='', *args, **kwargs)[source]
Bases:
floatjavascript Number methods
- Return type:
- 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:
- static isNaN(value)[source]
Number.isNaN– true only for an actual NaN number (no coercion).- Return type:
- x: Any
- static isInteger(value)[source]
Number.isInteger– true only for a finite whole-number value.- Return type:
- 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:
- toFixed(digits)[source]
formats a number using fixed-point notation.
- toPrecision(precision)[source]
returns a string representing the Number object to the specified precision.
- 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}
- static assign(target, *sources)[source]
Copy the enumerable own properties of each source onto
target(left to right) and returntarget–Object.assign(t, s1, s2, ...).- Return type:
- static create(proto, propertiesObject=None)[source]
Creates a new object with the specified prototype object and properties.
- Return type:
- static defineProperty(obj, prop, descriptor)[source]
Adds the named property described by a given descriptor to an object.
- Return type:
- static defineProperties(obj, props)[source]
Adds named properties described by descriptors to an object.
- Return type:
- static entries(obj)[source]
Returns an array containing all of the [key, value] pairs in the object.
- static keys(obj)[source]
Returns an array containing the names of all of the given object’s own enumerable string properties.
- static values(obj)[source]
Returns an array containing the values that correspond to all of a given object’s own enumerable string properties.
- static getOwnPropertyDescriptor(obj, prop)[source]
Returns a property descriptor for a named property on an object.
- Return type:
- static getOwnPropertyNames(obj)[source]
Returns an array containing the names of all of the given object’s own enumerable and non-enumerable properties.
- static getOwnPropertySymbols(obj)[source]
Returns an array of all symbol properties found directly upon a given object.
- static getPrototypeOf(obj)[source]
Returns the prototype (internal [[Prototype]] property) of the specified object.
- Return type:
- static preventExtensions(obj)[source]
Prevent new properties from being added to an object.
- Return type:
- static seal(obj)[source]
Prevent extensions and deletion of an object’s existing properties.
- Return type:
- static is_(value1, value2)[source]
Object.is– SameValue: like===butNaNequalsNaNand+0differs from-0. (isis a Python keyword.)- Return type:
- static hasOwn(obj, key)[source]
Object.hasOwn(obj, key)– a direct (own) property check.- Return type:
- static groupBy(items, callback)[source]
Object.groupBy– groupitemsinto a dict keyed bycallback(item, index).- Return type:
- 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
dictthat is a read-only copy that raises on mutation, so use the return value (cfg = Object.freeze(cfg)).- Return type:
- 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:
- isPrototypeOf(obj)[source]
Returns a boolean indicating whether an object is a copy of this object.
- Return type:
- is(value2)
Object.is– SameValue: like===butNaNequalsNaNand+0differs from-0. (isis a Python keyword.)- Return type:
- class domonic.javascript.Performance[source]
Bases:
objecthttps://developer.mozilla.org/en-US/docs/Web/API/Performance
- property timeOrigin: float
Milliseconds since the Unix epoch at which
now()read zero.
- mark(name, markOptions=None)[source]
- Return type:
- measure(name, startOrMeasureOptions=None, endMark=None)[source]
measure(name),measure(name, startMark, endMark)ormeasure(name, {"start": ..., "end": ..., "duration": ..., "detail": ...}).- Return type:
- getEntries()[source]
- Return type:
- getEntriesByType(entryType)[source]
- Return type:
- getEntriesByName(name, entryType=None)[source]
- Return type:
- clearMarks(name=None)[source]
- clearMeasures(name=None)[source]
- exception domonic.javascript.ProgramKilled[source]
Bases:
ExceptionRaised when a scheduled background job is asked to stop.
- class domonic.javascript.Promise(func=None, *args, **kwargs)[source]
Bases:
object- data: Any
- finally_(onfinally)[source]
promise.finally(fn)– runfnonce the promise settles, whichever way. (finallyis a Python keyword.)- Return type:
- resolve()
- Return type:
- reject()
- Return type:
- static all(iterable)[source]
Fulfils with the list of results once every input settles; rejects with the first rejection.
- Return type:
- static allSettled(iterable)[source]
Fulfils with a list of
{status, value|reason}records.- Return type:
- static any(iterable)[source]
Fulfils with the first fulfilment; rejects with an
AggregateErrorif every input rejects.- Return type:
- finally(onfinally)
promise.finally(fn)– runfnonce the promise settles, whichever way. (finallyis a Python keyword.)- Return type:
- exception domonic.javascript.RangeError(message='', *args, **kwargs)[source]
Bases:
Error,ValueError- name: str = 'RangeError'
- exception domonic.javascript.ReferenceError(message='', *args, **kwargs)[source]
-
- name: str = 'ReferenceError'
- class domonic.javascript.Reflect[source]
Bases:
objectThe 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.
- 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:
- 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:
- static defineProperty(target, propertyKey, attributes)[source]
Similar to Object.defineProperty(). Returns a Boolean that is true if the property was successfully defined.
- Return type:
- static deleteProperty(target, propertyKey)[source]
The delete operator as a function. Equivalent to calling delete target[propertyKey].
- Return type:
- 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:
- 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:
- getPrototypeOf()
Returns the prototype (internal [[Prototype]] property) of the specified object.
- Return type:
- 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:
- static preventExtensions(target)[source]
Similar to Object.preventExtensions(). Returns a Boolean that is true if the update was successful.
- Return type:
- 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:
- 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:
- 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(theyflag).
- 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:
- 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:
- property ignoreCase: bool
Whether to ignore case while attempting a match in a string.
- Returns:
True if ignoreCase, False otherwise
- Return type:
- property unicode: bool
Whether or not Unicode features are enabled.
- Returns:
True if unicode, False otherwise
- Return type:
- compile(expression=None, flags=None)[source]
(Re-)compiles a regular expression during execution of a script.
- Return type:
- exec(s)[source]
Search s for a match.
Returns
Noneon no match. Otherwise a list whose[0]is the full match and[1:]the capture groups, with.index/.input/.groupsattributes (JavaScript’sRegExp.exec). When thegoryflag is set, the search resumes fromlastIndexand advances it.
- replace(string, replacement)[source]
regexp.replace(str, repl)– JavaScript’sRegExp[Symbol.replace].Equivalent to
String(str).replace(self, repl): honours thegflag and expands$1/$&/$<name>in a string replacement.- Return type:
- test(s)[source]
Tests for a match in its string parameter.
- class domonic.javascript.Screen(width=1024, height=768, *, availWidth=None, availHeight=None, colorDepth=24, pixelDepth=None)[source]
Bases:
objectLightweight representation of the browser Screen object.
- class domonic.javascript.Set(*args)[source]
Bases:
object- 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.
- 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:
- 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:
- contains(value)[source]
Returns a boolean asserting whether an element is present with the given value in the Set object or not.
- Return type:
- values()[source]
Returns a new iterator object that yields the values for each element in the Set object in insertion order.
- entries()[source]
Returns a new iterator object that contains an array of [value, value] for each element in the Set object, in insertion order.
- 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- filepath: str
- has_file: bool
- property length: int
Returns an integer representing the number of data items stored in the Storage object.
- setItem(keyName, value)[source]
Store
valueunderkeyNameusing Web Storage string coercion.
- removeItem(keyName)[source]
Remove
keyNameand its value from storage.
- clear()[source]
Removes all items from the storage
- keys()[source]
- values()[source]
- items()[source]
- class domonic.javascript.String(x='', *args, **kwargs)[source]
Bases:
strJavaScript
String.Subclasses
strsoString(x)is a real string primitive (likeNumber(float)) –isinstance(String(5), str)isTrueand it interoperates everywhere astris expected – while still carrying the JS method surface (charAt,padStart, UTF-16length, …).self.xis kept as a read-only alias of the string content so the ~180 internal references keep working.- Return type:
- 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
.lengthis 2 even though it’s one character – returning a domonicString(rather than a bare Python str) preserves that via its own UTF-16-aware.length. Python’s builtinlen()still reports 1, since Python strings are indexed by code point, not UTF-16 code unit.- Return type:
- static raw(template, *substitutions)[source]
String.raw– the tag function for raw template literals.templateis the strings object ({"raw": [...]}or anything with arawsequence); the raw segments are interleaved withsubstitutions. A plain string is returned unchanged, soString.raw(r"a\nb")still works.- Return type:
- split(expr=None, limit=None)[source]
String.prototype.split(separator, limit).A
RegExpseparator with capture groups keeps the captures in the result (like JS);""splits into individual characters;limittruncates the result.
- concat(*args, seperator='')[source]
Concatenates the string arguments to the calling string and returns a new string.
- charCodeAt(index)[source]
The UTF-16 code unit at
index;NaN(the number) when out of range, sos.charCodeAt(past_end) <= 0xffffis simplyFalse.- Return type:
- 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:
- 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:
- startsWith(x, position=None)[source]
String.prototype.startsWith(searchString, position=0).- Return type:
- 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:
- endsWith(x, endPosition=None)[source]
String.prototype.endsWith(searchString, endPosition=length)– treats the string as if it ended atendPosition.- Return type:
- 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:
- at(index)[source]
The code unit at
indexas a string (negative counts from the end), orundefinedwhen out of range.- Return type:
- charAt(index)[source]
The UTF-16 code unit at
indexas a one-‘character’ string (a lone surrogate for one half of an astral character);""when out of range.- Return type:
- 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:
- replaceAll(old, new)[source]
returns a new string where the specified values are replaced. ES2021
- substr(start=0, length=None)[source]
lengthcode units starting atstart(negativestartcounts from the end) – code-unit based, like JavaScript.- Return type:
- toLocaleLowerCase()[source]
Converts a string to lowercase letters, according to the host’s locale
- Return type:
- toLocaleUpperCase()[source]
Converts a string to uppercase letters, according to the host’s locale
- Return type:
- 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.
- codePointAt(index)[source]
Returns the Unicode code point at the specified index (position).
- padEnd(length, padChar=' ')[source]
Pads the end of a string with a specified character (repeated, if needed) to create a new string.
- padStart(length, padChar=' ')[source]
Pads the start of a string with a specified character
- 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:
- includes(searchValue, position=0)[source]
Returns true if the specified string is found within the calling String object.
- search(value)[source]
String.prototype.search– the index of the first match, or -1.A non-
RegExpvalueis converted withnew RegExp(value)(it is not escaped), matching JavaScript.- Return type:
- matchAll(pattern)[source]
String.prototype.matchAll– an iterator of match arrays.Each item is
[fullMatch, *groups]with.index/.input/.groups(named groups), likeRegExp.exec.- Return type:
Iterator[_RegExpMatch]
- match(pattern)[source]
String.prototype.match.Without the
gflag:[fullMatch, *groups]with.index/.input/.groups, orNone. With thegflag: a plain list of every full match, orNonewhen there is no match.
- 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.
- 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:
- fontcolor(color)[source]
wraps the string in font tags with a specified color
- fontsize(size)[source]
wraps the string in font tags with a specified size
- italics()[source]
wraps the string in italics tags
- Returns:
the string in italics tags
- Return type:
- link(url)[source]
wraps the string in a link tag
- strike()[source]
wraps the string in strike tags
- Returns:
the string in strike tags
- Return type:
- div(*args, **kwargs)[source]
wraps the string in a div tag
- Returns:
the string in a div tag
- Return type:
- class domonic.javascript.Symbol(symbol)[source]
Bases:
object- hasInstance(obj)[source]
A method determining if a constructor object recognizes an object as its instance. Used by instanceof.
- isConcatSpreadable()[source]
A Boolean value indicating if an object should be flattened to its array elements. Used by Array.prototype.concat().
- Return type:
- iterator(obj)[source]
A method returning the default iterator for an object. Used by for…of.
- asyncIterator(obj)[source]
A method that returns the default AsyncIterator for an object. Used by for await…of.
- 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:
- toSource()[source]
Returns a string containing the source of the Symbol. Overrides the Object.prototype.toSource() method.
- Return type:
- toString()[source]
Returns a string containing the description of the Symbol. Overrides the Object.prototype.toString() method.
- Return type:
- class domonic.javascript.TypedArray(*args)[source]
Bases:
object- BYTES_PER_ELEMENT: int = 1
- length: int
- byteLength: int
- buffer: Any
- byteOffset: int
- property args: Any
- get(index)
- Return type:
- 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:
objecta-tag extends from URL
- property href: str
- property searchParams: URLSearchParams
- property origin: str
- static revokeObjectURL(url)[source]
- property protocol: str
- property username: str
- property password: str
- 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:
- static domainToUnicode(domain)[source]
Return the Unicode serialization of a domain.
- Return type:
- class domonic.javascript.URLSearchParams(paramString='', _update=None)[source]
Bases:
objectutility methods to work with the query string of a URL
- 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:
- entries()[source]
Returns an iterator allowing iteration through all key/value pairs contained in this object.
- pairs()[source]
Returns each key/value pair, including duplicates.
- 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.
- 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.
- toString()[source]
Returns a string containing a query string suitable for use in a URL.
- Return type:
- 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.
- 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:
objectwindow
- 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:
- setTimeout(t, *args, **kwargs)
sets a timer which executes a function or evaluates an expression after a specified delay
- clearTimeout()
cancels a timer set with setTimeout()
- Parameters:
timeoutID (str) – the identifier returned by setTimeout()
- static clearInterval(job)[source]
- async static fetch_async(url, **kwargs)[source]
Fetch a URL without blocking the current asyncio event loop.
- Return type:
- static fetch_set(urls, callback_function=None, error_handler=None, **kwargs)[source]
- Return type:
- static fetch_threaded(urls, callback_function=None, error_handler=None, **kwargs)[source]
- Return type:
- static fetch_pooled(urls, callback_function=None, error_handler=None, **kwargs)[source]
- Return type:
- class domonic.javascript.Worker(scriptURL, options=None)[source]
Bases:
WorkerBackground worker exposed from the legacy
domonic.javascriptnamespace.
- domonic.javascript.as_signed(value, bits)[source]
Converts an unsigned integer to a signed integer.
- Return type:
- domonic.javascript.atob(data)[source]
Decode a base64 string to a binary (Latin-1) string.
- Return type:
- 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:
- domonic.javascript.decodeURIComponent(x)
Decodes a URI component
- Return type:
- domonic.javascript.encodeURI(x)
Encodes a URI
- Return type:
- domonic.javascript.encodeURIComponent(x)
Encodes a URI component
- Return type:
- domonic.javascript.function(python_str)[source]
[evals a string i.e.
sup = function(‘’’print(hi)’’’) sup()
]
- domonic.javascript.globalThis
alias of
Global
- domonic.javascript.isFinite(x)
Returns true if x coerces to a finite number.
- Return type:
- domonic.javascript.isNaN(x)
Determines whether a value coerces to NaN.
- Return type:
- domonic.javascript.parse(timestr, parserinfo=None, **kwargs)[source]
Parse a string in one of the supported formats, using the
parserinfoparameters.- Parameters:
timestr – A string containing a date/time stamp.
parserinfo – A
parserinfoobject containing parameters for the parser. IfNone, the default arguments to theparserinfoconstructor are used.
The
**kwargsparameter takes the following keyword arguments:- Parameters:
default – The default datetime object, if this is a datetime object and not
None, elements specified intimestrreplace elements in the default object.ignoretz – If set
True, time zones in parsed strings are ignored and a naivedatetimeobject 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 (
tznameandtzoffset) and returning a time zone.The timezones to which the names are mapped can be an integer offset from UTC in seconds or a
tzinfoobject.This parameter is ignored if
ignoretzis 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). Ifyearfirstis set toTrue, this distinguishes between YDM and YMD. If set toNone, this value is retrieved from the currentparserinfoobject (which itself defaults toFalse).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 toNone, the value is retrieved from the currentparserinfoobject (which itself defaults toFalse).fuzzy – Whether to allow fuzzy parsing, allowing for string like “Today is January 1, 2047 at 8:21:00AM”.
fuzzy_with_tokens – If
True,fuzzyis automatically set to True, and the parser will return a tuple where the first element is the parseddatetime.datetimedatetimestamp and the second element is a tuple containing the portions of the string which were ignored:
- Returns:
Returns a
datetime.datetimeobject or, if thefuzzy_with_tokensoption isTrue, returns a tuple, the first element being adatetime.datetimeobject, the second a tuple containing the fuzzy tokens.- Raises:
ParserError – Raised for invalid or unknown string formats, if the provided
tzinfois 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:
- domonic.javascript.parseInt(x, radix=0)
Parses a string and returns an integer
- domonic.javascript.parsedate_to_datetime(data)[source]
- class domonic.javascript.parserinfo(dayfirst=False, yearfirst=False)[source]
Bases:
objectClass 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). Ifyearfirstis set toTrue, this distinguishes between YDM and YMD. Default isFalse.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 isFalse.
- 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:
- domonic.javascript.setTimeout(callback, t, *args, **kwargs)
sets a timer which executes a function or evaluates an expression after a specified delay
- domonic.javascript.structuredClone(value, options=None)[source]
A deep clone of
value(the structured-clone algorithm, approximated withcopy.deepcopy()).- Return type:
- class domonic.javascript.timezone
Bases:
tzinfoFixed 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