0

I want to use Python classes and functions I've written in a separate Javascript file. I'm wondering if it's possible to "import" those classes to my JS file?

hao
  • 73
  • 1
  • 9
  • 3
    They are a different language, one cannot port between languages like this. – A.J. Uppal Jun 02 '20 at 23:50
  • There are things like "Brython" or "Transcrypt" to connect these languages. – Michael Butscher Jun 02 '20 at 23:52
  • 2
    Check out [How to call a Python function from Node.js](https://stackoverflow.com/questions/23450534/how-to-call-a-python-function-from-node-js) for server-side JS-Python, or [Import Python Classes to Javascript?](https://stackoverflow.com/q/62163095/2745495) for client-side JS to server-side Python. It's really not clear what's your actual use-case. – Gino Mempin Jun 03 '20 at 00:30

1 Answers1

0

Short answer: No, you can not do that. The problem is, that JavaScript runs on the client while python is server-sided.

Long answer: While you can't directly import python scripts and use their classes and functions in JavaScript, you can actually use server-sided JavaScript implementations like AJAX to call a Python script. This is not what you imagined however, such a request would look like this:

$.ajax({
  type: "POST",
  url: "~/your_script.py",
  data: { param1: value1}
}).done(function( o ) {
   // some more code
});

As you can see, you are able to call a script and even pass some parameters, but that is about it. I mean in theorie sure, you could hack your way around and set up your website like this. But trust me, before you know what is happening you loose track of all the calls and the project becomes virtually impossible to maintain.

GutZuFusss
  • 138
  • 1
  • 2
  • 15
  • 1
    It's also possible to be running server-side JS (node.js) and then call your Python scripts (which are also on the server-side). In this case, AJAX is not required, we can simply use Node's built-in exec/spawn functions. – Gino Mempin Jun 03 '20 at 00:29
  • @Gino Mempin you are right, I should have made more clear that AJAX is just being used as an example, my bad! – GutZuFusss Jun 03 '20 at 00:30