flexxui/pscript

Using math functionality

gareins opened this issue · 3 comments

How would I use math functions (or other functionality in JS and Py standard libraries) which would work in both Python source code and compiled Javascript code?

This is a self reply, if there are better ways, I am happy to hear about them!

Anyway, lets make an example use of ceil math function:

def does_ceil_work():
  print(3 == ceil(2.5))

To handle javascript part, lets add raw js code at the top of the script:

from pscript import RawJS
ceil = RawJS("Math.ceil")

Now, to get ceil working for python interpreter, override it at the start of if __name__ == "__main__":

if __name__ == "__main__":
  from math import ceil
  does_ceil_work()

This is useful for me as I do development and tests in Python and then only export "pure functions" to JS. Also, normally, beware of subtle differences!

I think something like this should work too:

import math as Math

def does_ceil_work():
  print(3 == Math.ceil(2.5))

Nice :)

Just to be clear, this needs to be in the if __name__ == "__main__" otherwise you get an error PScript does not support imports..

My current code is without any imports on top and just doing this:

if __name__ == "__main__":
    import math as Math
    Math.PI = Math.pi