flexxui / pscript

Python to JavaScript compiler
http://pscript.readthedocs.io
BSD 2-Clause "Simplified" License
256 stars 25 forks source link

Using math functionality #65

Closed gareins closed 2 years ago

gareins commented 2 years ago

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?

gareins commented 2 years ago

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!

almarklein commented 2 years ago

I think something like this should work too:


import math as Math

def does_ceil_work():
  print(3 == Math.ceil(2.5))
gareins commented 2 years ago

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