quant
quant

Reputation: 2224

Call external Python class function from inside Haxe

Let's assume that I have the following class in Python:

class TestPy:
    def __init__(self):
        pass
    def f(self):
        return("Hello World")

and I want to call the function TestPy.f from within Haxe. I can then tell the compiler of this function by specifing an extern class via

extern class TestPy { 
    public function new():Void;
    public function f():String;
}

and then use this declaration in order to call this function

class Test {
    public static function main():Void {
        var py:TestPy = new TestPy();
        trace(py.f());
    }
}

This compiles, however the generated code looks like this:

# Generated by Haxe 3.4.7
# coding: utf-8
class Text:
    __slots__ = ()
    @staticmethod
    def main():
        py = TestPy()
        print(str(py.f()))
Text.main()

which is not working because the module the with TestPy class never gets imported in the code:

NameError: name 'TestPy' is not defined

So my question is how can I advice Haxe to add an import statement (e.g. from testmodule import TestPy) to the generated code?

Upvotes: 2

Views: 506

Answers (1)

Kronocian
Kronocian

Reputation: 76

Just add a @:pythonImport metadata to your extern. So, something like:

@:pythonImport('testmodule', 'TestPy')
extern class TestPy {...

Disclaimer: haven't tested this, so that may not be the exactly correct answer, but the metadata is documented in the manual.

Upvotes: 4

Related Questions