python-starlark-go icon indicating copy to clipboard operation
python-starlark-go copied to clipboard

Support struct

Open n87 opened this issue 3 years ago • 4 comments

It'd be great to have struct datatype supported. The implementation is in starlark-go repo, but seems not enabled by default: https://github.com/google/starlark-go/tree/master/starlarkstruct

Conversion to/from Python values can be done either by writing new class, or reusing namedtuple. With namedtuple, you have to take care of builtin index() and count() methods. Also to check that object is a named tuple, you can check that it's an instance of tuple and has _fields:

isinstance(x, tuple) and hasattr(x, '_fields')

Go is not my area of competence, but I could help with Python side of things.

n87 avatar Feb 26 '23 09:02 n87

I'd like to have this, too, as I'm moving toward using structs in one of my projects.

colindean avatar Mar 06 '23 17:03 colindean

I'm not sure namedtuple is the right way to go here; I've mostly abandoned it in favor of dataclasses in my other projects. It looks like there's a factory function to make those on the fly too, but they are a bit heavier.

There's also types.SimpleNamespace, which seems to be the closest in spirit to a Starlark struct; namedtuple and dataclass also imply the generation of a new type; it seems like in Starlark, struct is the type, regardless of what members the struct may have.

My current plan is:

  • Python namedtuple, dataclass, and SimpleNamespace all convert to Starlark struct
    • (should we also have a helper method to make Starlark struct from Python dict, or is that just SimpleNamespace?)
  • Converting a Starlark struct to Python results in a SimpleNamespace

I am planning on implementing this soon, so if this sounds unpalatable to you, please let me know quickly

jordemort avatar Mar 15 '23 16:03 jordemort

Thanks for introducing me to SimpleNamespace. The plan looks good so far. I don't think helper function for dict is important.

n87 avatar Mar 16 '23 01:03 n87

There is a fork with struct support:

https://github.com/romain-h/python-starlark-go/tree/build-support-struct

It does only work on Python 3.10 and below though due to https://bugs.python.org/issue45482

miracle2k avatar Mar 12 '24 19:03 miracle2k