Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Support struct #148

Open
n87 opened this issue Feb 26, 2023 · 4 comments
Open

Support struct #148

n87 opened this issue Feb 26, 2023 · 4 comments

Comments

@n87
Copy link

n87 commented Feb 26, 2023

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
Copy link
Contributor

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

@jordemort
Copy link
Contributor

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

@n87
Copy link
Author

n87 commented Mar 16, 2023

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

@miracle2k
Copy link

miracle2k commented Mar 12, 2024

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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

4 participants