I'm trying to create a small inline object that uses a lambda function but I keep getting a SyntaxError for this line. The syntax as far as I can tell is correct
mock_popen.return_value = type('obj', (object,), {'communicate' : lambda :'hello','world'})
UPDATE:
In case anyone else is trying to create a module object like this ... don't. The code below is a much cleaner and more elegant way of solving the problem.
mock_popen = MagicMock()
mock_popen.return_value = mock_popen
mock_popen.communicate.return_value = ('hello','world')
The problem is the two colons in the last expression; the Python parser doesn't parse the lambda colon followed by the comma-separated list. There's an visual ambiguity about whether that's a parameter-list comma or a dictionary comma.
Put the two parameters in parentheses, and you should be okay:
{'communicate' : lambda :('hello','world')}
Output (changing your assignment, since the ID isn't defined):
>>> type('obj', (object,), {'communicate' : lambda :('hello','world')})
<class '__main__.obj'>
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments