Method for implementing isnumeric() in PsychoJS

I thought I’d share a solution here that I found for a problem I encountered in my experiment that may be useful to others. I had a Python code component that ran the following test:

if c.isnumeric():
    do_stuff()

Auto->JS translation just kept this literal syntax, and this threw an error when running online, because apparently strings in JS do not have an .isnumeric() method.

My fix was the following. I did not want to have to manually edit only this line in JS, because I would have to redo that whenever I edit the Python code and have it auto-translated. So I decided to define a new function isnumeric() separately in both Python and JS. For Python, I added this function to a separate file ‘helpers.py’, and then included some python-only initialization code at the top of my experiment (in a “before experiment” code component):

from helpers import isnumeric

With that function defined as simply:

def isnumeric(x):
    return x.isnumeric()

Then, I added some JS-only initialization code as well, defining:

function isnumeric(n) {
    return !isNaN(parseFloat(n)) && isFinite(n);
}

(Taken from here.)

This then allowed me to use the syntax isnumeric(c) in my Python code, which gets auto-translated to again isnumeric(c) in JS, which now works as both the Python and JS environments have correctly working functions by that name.

2 Likes

Cool. I’ll add this to my crib sheet for code_JS (my alternative to your helpers method).

Lovely implementation. Chapeau!

This could work for other manual translations, e.g.

def upper(x):
     return x.upper()

function upper(x) {
return x.toUpperCase();
}

Added isnumeric and upper on a (very unstructured) list we use to keep track of Python → JS features for future releases.

Update there is now a pull request in for both upper()toUppercase() and lower()toLowerCase subject to review