caketop / python-starlark-go

🐍 Python bindings for starlark-go 🐍
https://python-starlark-go.readthedocs.io/
Apache License 2.0
26 stars 8 forks source link

Support struct #148

Open n87 opened 1 year ago

n87 commented 1 year ago

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.

colindean commented 1 year ago

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

jordemort commented 1 year ago

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:

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

n87 commented 1 year ago

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

miracle2k commented 8 months ago

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