lark icon indicating copy to clipboard operation
lark copied to clipboard

Run code on every attribute

Open nikableh opened this issue 1 year ago • 7 comments

What is your question?

How do I run code inside a Visitor class on every attribute? Something like __default__(tree), but in case the attribute exists.

nikableh avatar Feb 12 '25 23:02 nikableh

As always, the answer comes 10 milliseconds after I post the question. I modified the grammar to group each attribute in another attribute (line in my case). Not sure if this is a way to go, but it works for me.

nikableh avatar Feb 12 '25 23:02 nikableh

No, actually, not fixed. How do I run code before and after each attribute?

nikableh avatar Feb 12 '25 23:02 nikableh

Why do you need to run on every attribute?

And maybe you can just solve it with decorators?

erezsh avatar Feb 12 '25 23:02 erezsh

And maybe you can just solve it with decorators?

Most likely. I'll look into that.

Why do you need to run on every attribute?

I parse file line by line. I want to do certain action if previous line was a specific attribute. Setting variable previous_atteibute_was_the_one is not possible since I'd have to set it to False in every tag that's not the one I want..

nikableh avatar Feb 12 '25 23:02 nikableh

Then you don't need every attribute, you only need the attribute that marks a new line.

Btw you can use @v_args(wrapper=...) on the class to decorate every method in the class with one line. But maybe it's better to keep it simple.

erezsh avatar Feb 13 '25 00:02 erezsh

Btw you can use @v_args(wrapper=...) on the class to decorate every method in the class with one line.

I tried really hard to make it work, but to no avail. Could you please provide an example? There is currently no one in the documentation.

Then you don't need every attribute, you only need the attribute that marks a new line.

That's really smart. I'd try that, thanks. Thought, I would still like to know how to achieve that with @v_args(wrapper=...).

nikableh avatar Feb 13 '25 00:02 nikableh

Sorry, I made a mistake. v_args only applies to Transformer, not Visitor.

erezsh avatar Feb 13 '25 09:02 erezsh