metacraft-labs / py2nim

A Python-to-Nim transpiler
MIT License
136 stars 8 forks source link

Use reference rather than value semantics for objects? #14

Open wizzardx opened 6 years ago

wizzardx commented 6 years ago

Python uses references for everything, rather than values.

This python code:

class A:
    def __init__(self):
        self.x = 300

class B:
    def __init__(self, a):
        self.a = a

def test():
    a = A()
    b = B(a)
    a.x = 200
    print(b.a.x)

if __name__ == '__main__':
    test()

Gets converted to this Nim code:

type
  A* = object
    x*: int

type
  B* = object
    a*: A

proc makeA*(): A =
  result.x = 300

proc test*(): void =
  var
    a = makeA()
    b = B(a: a)
  a.x = 200
  echo b.a.x

when isMainModule:
  test()

Running the python code gives an output of 200, while running the Nim code gives an output of 300.

Conversion logic seems a bit different to what's suggested over here?

https://github.com/nim-lang/Nim/wiki/Nim-for-Python-Programmers#object-orientation

Intentional?

wizzardx commented 6 years ago

I'm not sure, but I think this conversion may be more correct:


type
  A* = ref object of RootObj
    x*: int

type
  B* = ref object of RootObj
    a*: A not nil

proc makeA*(): A =
  new result
  result.x = 300

proc test*(): void =
  var
    a = makeA()
    b = B(a: a)
  a.x = 200
  echo b.a.x

when isMainModule:
  test()

This one gives an output of 200, like the Python example.

alehander92 commented 6 years ago

That's right, those cases should use ref

We wanted to use object for some simpler objects, but my check was obviously too simplistic. Probably removing ref for simple objects with no field assignment elsewhere in the program might work.