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

Resolve lambdas in Container __getattr__ #1030

Open
wants to merge 1 commit into
base: master
Choose a base branch
from

Conversation

ev1313
Copy link

@ev1313 ev1313 commented Apr 24, 2023

Currently using Rebuild is only useful when parsing, because the dictionary gets filled with value copys:

    d = Struct(
        "foo" / Int32ul,
        "bar" / Rebuild(Int32ul, lambda ctx: ctx.baz),
        "baz" / Rebuild(Int32ul, lambda ctx: ctx.foo),
    )
    data = b'\x04\x00\x00\x00\x04\x00\x00\x00\x04\x00\x00\x00'
    obj = d.parse(data)
    # Container(foo=4, bar=4, baz=4)

However this isn't useful when building, because you don't know in later stages about the rebuilding, and when the parameters change, you'd need to change all of them.

With this change it is possible to put lambda ctx: ctx.foo into the Container, which get resolved immediately, when accessed. (See the test case)

This could be expanded upon, so that Rebuild itself just add these to the Container when parsing, or that a possible preprocessing step adds these before building.

The inspect hack is necessary to not break the existing behaviour of Lazy adding lambdas into the Container, which get resolved and return not the lambda, but the resulting value directly.

"bar" / Rebuild(Int32ul, lambda ctx: ctx.baz),
"baz" / Rebuild(Int32ul, lambda ctx: ctx.foo),
)
obj = {"foo": 4, "bar": lambda ctx: ctx.baz, "baz": lambda ctx: ctx.foo}

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Why isn't this just {"foo": 4}? Asked differently: Why are "bar" and "baz" functions?

I think it's a bit hacky to allow the data to decide how it should be processed (~ functions). I'm not sure if there's a precedent for this in construct.

Instead, the lambda ctx: ctx.baz in Rebuild should be deferred until ctx.baz is available.

Is there an actual benefit doing it the proposed way (allowing functions in input to build) over deferring Rebuild?

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

Successfully merging this pull request may close these issues.

None yet

2 participants