Skip to content

Commit 683c61c

Browse files
committed
Add new and typeof helpers
1 parent 1db87d8 commit 683c61c

File tree

3 files changed

+52
-2
lines changed

3 files changed

+52
-2
lines changed

python/pythonmonkey/__init__.py

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
# Export public PythonMonkey APIs
22
from .pythonmonkey import *
33
from .require import *
4+
from .helpers import *
45

56
# Expose the package version
67
import importlib.metadata
@@ -24,4 +25,4 @@
2425
Object.defineProperty(Object.prototype, "keys", keysMethod)
2526
Object.defineProperty(Array.prototype, "keys", keysMethod)
2627
}
27-
""")(lambda *args: list(args))
28+
""", { 'filename': __file__, 'fromPythonFrame': True })(lambda *args: list(args))

python/pythonmonkey/helpers.py

Lines changed: 49 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,49 @@
1+
# @file helpers.py - Python->JS helpers for PythonMonkey
2+
# - typeof operator wrapper
3+
# - new operator wrapper
4+
#
5+
# @author Wes Garland, [email protected]
6+
# @date July 2023
7+
#
8+
9+
from . import pythonmonkey as pm
10+
evalOpts = { 'filename': __file__, 'fromPythonFrame': True }
11+
12+
def typeof(jsval):
13+
"""
14+
typeof function - wraps JS typeof operator
15+
"""
16+
return pm.eval("""'use strict'; (
17+
function pmTypeof(jsval)
18+
{
19+
return typeof(jsval)
20+
}
21+
)""", evalOpts)(jsval);
22+
23+
def new(ctor, *args):
24+
"""
25+
new function - wraps JS new operator
26+
"""
27+
if (typeof(ctor) == 'string'):
28+
ctor = pm.eval(ctor)
29+
30+
return pm.eval("""'use strict'; (
31+
function pmNew(ctor, args)
32+
{
33+
if (arguments.length === 1)
34+
args = [];
35+
36+
// work around pm list->Array bug, /wg july 2023
37+
if (!Array.isArray(args))
38+
{
39+
const newArgs = [];
40+
for (let i=0; i < args.length; i++)
41+
newArgs[i] = args[i];
42+
args = newArgs;
43+
}
44+
return new ctor(...args);
45+
}
46+
)""", evalOpts)(ctor, list(args));
47+
48+
# Restrict what symbols are exposed to the pythonmonkey module.
49+
__all__ = ["new", "typeof"]

python/pythonmonkey/require.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -352,5 +352,5 @@ def require(moduleIdentifier: str):
352352
filename = os.path.join(os.getcwd(), "__main__") # use the CWD instead
353353
return createRequire(filename)(moduleIdentifier)
354354

355-
# Restrict what are exposed to the pythonmonkey module.
355+
# Restrict what symbols are exposed to the pythonmonkey module.
356356
__all__ = ["globalThis", "require", "createRequire", "runProgramModule"]

0 commit comments

Comments
 (0)