PScript API¶
Convert Python to JavaScript¶
-
pscript.
py2js
(ob=None, new_name=None, **parser_options)¶ Convert Python to JavaScript.
Parameters: - ob (str, module, function, class) – The code, function or class to transpile.
- new_name (str, optional) – If given, renames the function or class. This can be used to simply change the name and/or add a prefix. It can also be used to turn functions into methods using “MyClass.prototype.foo”. Double-underscore name mangling is taken into account in the process.
- parser_options – Additional options, see
Parser class
for details.
Returns: The JavaScript code as a str object that has a
meta
attribute with the following fields:- filename (str): the name of the file that defines the object.
- linenr (int): the starting linenr for the object definition.
- pycode (str): the Python code used to generate the JS.
- pyhash (str): a hash of the Python code.
- vars_defined (set): names defined in the toplevel namespace.
- vars_unknown (set): names used in the code but not defined in it. This includes namespaces, e.g. “foo.some_function”.
- vars_global (set): names explicitly declared global.
- std_functions (set): stdlib functions used in this code.
- std_method (set): stdlib methods used in this code.
Return type: str
Notes
The Python source code for a class is acquired by name. Therefore one should avoid decorating classes in modules where multiple classes with the same name are defined. This is a consequence of classes not having a corresponding code object (in contrast to functions).
-
pscript.
script2js
(filename, namespace=None, target=None, module_type='umd', **parser_options)¶ Export a .py file to a .js file.
Parameters: - filename (str) – the filename of the .py file to transpile.
- namespace (str) – the namespace for this module. (optional)
- target (str) – the filename of the resulting .js file. If not given
or None, will use the
filename
, but with a.js
extension. - module_type (str) – the type of module to produce (if namespace is given), can be ‘hidden’, ‘simple’, ‘amd’, ‘umd’, default ‘umd’.
- parser_options – additional options for the parser. See Parser class for details.
Evaluate JavaScript or Python in Node¶
-
pscript.
evaljs
(jscode, whitespace=True, print_result=True, extra_nodejs_args=None)¶ Evaluate JavaScript code in Node.js.
Parameters: - jscode (str) – the JavaScript code to evaluate.
- whitespace (bool) – if whitespace is False, the whitespace is removed from the result. Default True.
- print_result (bool) – whether to print the result of the evaluation. Default True. If False, larger pieces of code can be evaluated because we can use file-mode.
- extra_nodejs_args (list) – Extra command line args to pass to nodejs.
Returns: the last result as a string.
Return type: str
-
pscript.
evalpy
(pycode, whitespace=True)¶ Evaluate PScript code in Node.js (after translating to JS).
Parameters: - pycode (str) – the PScript code to evaluate.
- whitespace (bool) – if whitespace is False, the whitespace is removed from the result. Default True.
Returns: the last result as a string.
Return type: str
More functions¶
-
pscript.
js_rename
(jscode, cur_name, new_name, type=None)¶ Rename a function or class in a JavaScript code string.
The new name can be prefixed (i.e. have dots in it). Functions can be converted to methods by prefixing with a name that starts with a capital letter (and probably “.prototype”). Double-underscore-mangling is taken into account.
Parameters: - jscode (str) – the JavaScript source code
- cur_name (str) – the current name (must be an identifier, e.g. no dots).
- new_name (str) – the name to replace the current name with
- type (str) – the Python object type, can be ‘class’ or ‘def’. If None, the type is inferred from the object name based on PEP8
Returns: the modified JavaScript source code
Return type: str
-
pscript.
get_full_std_lib
(indent=0)¶ Get the code for the full PScript standard library.
The given indent specifies how many sets of 4 spaces to prepend. If the full stdlib is made available in JavaScript, multiple snippets of code can be transpiled without inlined stdlib parts by using
py2js(..., inline_stdlib=False)
.
-
pscript.
get_all_std_names
()¶ Get list if function names and methods names in std lib.
-
pscript.
create_js_module
(name, code, imports, exports, type='umd')¶ Wrap the given code in an AMD module.
Note that “use strict” is added to the top of the module body. PScript does not deal with license strings; the caller should do that.
Parameters: - name (str) – the name of the module.
- code (str) – the JS code to wrap.
- imports (list) – the imports for this module, as string names of the dependencies. Optionally, ‘as’ can be used to make a dependency available under a specific name (e.g. ‘foo.js as foo’).
- exports (str, list) – the result of this module (i.e. what other modules get when they import this module. Can be a JS expression or a list of names to export.
- type (str) – the type of module to export, valid values are ‘hidden’, ‘simple’ (save module on root), ‘amd’ , ‘amd-flexx’ and ‘umd’ (case insensitive). Default ‘umd’.
The parser class¶
Most users probably want to use the above functions, but you can also get closer to the metal by using and/or extending the parser class.
-
class
pscript.
Parser
(code, pysource=None, indent=0, docstrings=True, inline_stdlib=True)¶ Parser to convert Python to JavaScript.
Instantiate this class with the Python code. Retrieve the JS code using the dump() method.
In a subclass, you can implement methods called “function_x” or “method_x”, which will then be called during parsing when a function/method with name “x” is encountered. Several methods and functions are already implemented in this way.
While working on ast parsing, this resource is very helpful: https://greentreesnakes.readthedocs.org
Parameters: - code (str) – the Python source code.
- pysource (tuple) – the filename and line number that contain the source.
- indent (int) – the base indentation level (default 0). One indentation level means 4 spaces.
- docstrings (bool) – whether docstrings are included in JS (default True).
- inline_stdlib (bool) – whether the used stdlib functions are inlined (default True). Set to False if the stdlib is already loaded.
Embedding raw JavaScript¶
PScript allows embedding raw JavaScript using the RawJS
class.
-
class
pscript.
RawJS
(code, _resolve_defining_module=True)¶ An object to wrap verbatim code to be included in the generated JavaScript. This serves a number of purposes:
- Using code in PScript that is not valid Python syntax, like regular
expressions or the jQuery object
$
. - Write high performance code that avoids Pythonic features like operator overloading.
- In Flexx’s module system it can be used to create a stub variable in Python that does have a value in JS. This value can imported in other modules, leading to a shared value also in JS.
PScript does not verify the syntax of the code, so write carefully! To allow the features in the 3d point, this object has a magic touch: the
__module__
attribute of an instance refers to the module in which it was instantiated, and if it’s a global, its defining name can be obtained.Example:
# Syntax not usable in Py myre = RawJS('/ab+c/') # Code that should only execute on JS foo = RawJS('require("some.module")') # Performance def bar(n): res = [] RawJS(''' for (var i=0; i<n; i++) { if (is_ok_num(i)) { res.push(i); } } ''')
- Using code in PScript that is not valid Python syntax, like regular
expressions or the jQuery object
Dummy variables¶
The PScript module has a few dummy constants that can be imported and
used in your code to let e.g. pyflakes know that the variable exists. E.g.
from pscript import undefined, window Infinity, NaN
.
Arbitrary dummy variables can be imported using
from pscript.stubs import JSON, foo, bar
.
Marking a variable as global is also a good approach to tell pyflakes that the variable exists.