1

Trying to figure out how to set a object attribute using a lambda function.

i got a case where i need to set the attribute with a UI callBack, that requires a function object.

was trying something like this but it dosnt work, and gives me a syntax error.

pm.button(command=lambda *args: uvOpts.grid = True)
1

1 Answer 1

3

this solves the syntax error (you cannot have a second "=" in pm.button) and works if uvOpts is in the scope.

pm.button(command=lambda *args: setattr(uvOpts, 'grid', True))

to set the object's attribute I'm using setattr, in order to avoid the use of a = symbol in lambda function definition.


I would like to add that if you need to make uvOpts visible inside the lambda scope you may eventually need to make it global, at least at module level (e.g. read the answers in Using global variables in a function other than the one that created them).

Sign up to request clarification or add additional context in comments.

4 Comments

*args isn't needed, so a simple pm.button(command=lambda: setattr(uvOpts, 'grid', True)) would suffice.
@martineau You are right, but since I don't know if args may be needed for any other reason (the OP may have just simplified his/her question), and in order to let cmcPasserby to identify the minimum change needed to solve the error I kept it. If unneeded, the arguments may be removed. Thanks for highlighting this aspect!
I would suggest answering questions based solely on their content rather than second-guessing what details the OP might be leaving out.
@martineau I prefer to keep it because I do not want to let the "distract reader" to think that *args is part of the problem. It's just unneeded in the context, but it does not cause harm as well. I should have mentioned in my answer that the argument is unnecessary, you are right, but now there is your comment to state this additional aspect (and this is why I voted up your comment) :).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.