Better way to allow JS and Py to use a different object with the same name
Sometimes, the JS and Py side of a model, or a piece of code that is used both in Python and JS, uses a name that is intrinsic to JS, like Math or JSON. But in Python you want to use an object that behaves similar enough to make the code work on both Py and JS. Right now there are two ways to work around this problem:
Using this_is_js() in a __pyscript__ module:
_pyscript__ = True
...
if not_this_is_js():
# The Pyscript parser complely ignores this bit, so you can even
# use non-PyScript compatible syntax here, like imports
import math
Math = math
class JSON:
...
Using a fake window object, which works because window is (currently) the only name that Flexx will never try to look up. This approach can only be used in non-pyscript modules. A downside is that every usage of the name in question must be prefixed with window.
class window:
JSON = ...
Math = ...
A note: the reverse could also occur: a common name in Python that you want to (partly) make available in JS.
What this issue comes down to is to allow, in a single module, having a variable with the same name, and the same usage and feature sub-set, but implemented differently in Python and JS.
I have been thinking about this in the context of the VerbatimJS or RawJS feature in #279. I think that for __pyscript__ modules, it makes sense to use this_is_js(), so this issue comes down to solving it for "normal" modules. Some options:
- Put forward the
class windowtrick as "the way" to fix it. - More or less a reverse, allow a
class JSon which variables can be defined that apply to JS, taking preference over variable with the same name present in the module. This looks a bit much likeModel.JSnested classes though, which can be confusing. - Allow a prefix/suffix that maps to the JS "namespace", e.g.
import math; math_JS = RawJS('window.Math'). - Allow marking variables as Python-only using a comment, e.g.
import math as Math # JS-only. This would need changes to the commonast parser and the PyScript parser though. - Maybe another way to mark a Python variable as Py-only? Since I feel the most common use-case is implementing or importing functionality that is natively available in JS.