Support struct
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.
I'd like to have this, too, as I'm moving toward using structs in one of my projects.
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, andSimpleNamespaceall convert to Starlarkstruct- (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
Thanks for introducing me to SimpleNamespace. The plan looks good so far. I don't think helper function for dict is important.
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