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)
  • I think value assignment of a variable inside lambda scope is not possible. Try this link: http://stackoverflow.com/questions/6282042/assignment-inside-lambda-expression-in-python – dpatro Dec 29 '13 at 15:41

1 Answers1

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).

Community
  • 1
  • 1
furins
  • 4,979
  • 1
  • 39
  • 57
  • 2
    `*args` isn't needed, so a simple `pm.button(command=lambda: setattr(uvOpts, 'grid', True))` would suffice. – martineau Dec 29 '13 at 17:45
  • 2
    @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! – furins Dec 29 '13 at 18:00
  • I would suggest answering questions based solely on their content rather than second-guessing what details the OP might be leaving out. – martineau Dec 29 '13 at 18:37
  • @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) :). – furins Dec 29 '13 at 18:52