Weird behaviour with anonymous structures and the Python target

Hi everyone !

I recently started to learn the Haxe language, and I am testing some code with the Python target. Looking at the generated code I found something intriguing. The following code (Haxe 3.4.7):

// test1.hx

class Main 
{
    static public function main()
    {
        var point = {x: 1.0, y: 2.0, z: 3.0};
        trace(point.y);
    } 
}

produces this output:

# Generated by Haxe 3.4.7
# coding: utf-8

class Main:
    __slots__ = ()

    @staticmethod
    def main():
        point_y = None
        point_x = 1.0
        point_y = 2.0
        point_z = 3.0
        print(str(point_y))

Main.main()

This is a valid Python code but is there any reason to have the statement point_y = None here ? If I replace trace(y) by trace(x) there is no point_x = None in the generated file (example bellow).

// test2.hx

class Main 
{
    static public function main()
    {
        var point = {x: 1.0, y: 2.0, z: 3.0};
        // this time I use the first field of the structure (x instead of y)
        trace(point.x);
    } 
}

output:

# Generated by Haxe 3.4.7
# coding: utf-8

class Main:
    __slots__ = ()

    @staticmethod
    def main():
        point_x = 1.0
        point_y = 2.0
        point_z = 3.0
        print(str(point_x))

Main.main()

I have done few tests and the initialization with None only appears for the second field of the structure, y in my case. Last example:

// test3.hx

class Main 
{
    static public function main()
    {
        // the field x is now in second position
        var point = {y: 1.0, x: 2.0, z: 3.0};
        trace(point.x);
    } 
}

output:

# Generated by Haxe 3.4.7
# coding: utf-8

class Main:
    __slots__ = ()

    @staticmethod
    def main():
        point_x = None
        point_x = 1.0
        point_y = 2.0
        point_z = 3.0
        print(str(point_x))

Main.main()

I didn’t find any issue related to this on GitHub, but it seems to be a bug (sorry if it’s a known one ; )… or a black magic spell affecting only the second field of anonymous structures.

Let me know if you have a better explanation, thanks in advance !
Bye

What is happening is that when inlining the point structure the code ends up like this:

var point_x;
var point_y = 1.0;
point_x = 2.0;
var point_z = 3.0;
trace(point_x);

In the python target that uninitialized variable is then translated into point_x = None
However if you enable analyzer optimizations the whole thing will collapse into just print(str(2.0)).

Also, I believe this is fixed in Haxe 4.0.0 even without the analyzer enabled. Give the preview a try: Haxe 4.0.0-preview.3 - Haxe - The Cross-platform Toolkit
It’s fixed by this change.

Ok I see.

I confirm with Haxe 4.0.0-preview.3 the output doesn’t contain the initialization with None:

def main():
    point_x = 1.0
    point_y = 2.0
    point_z = 3.0
    print(str(point_y))

Thanks a lot ; )