简体   繁体   中英

Invalid syntax trying to create inline python object

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'>

Not quite.

>>> lambda: 'hello', 'world'
(<function <lambda> at 0x7fc13d86e758>, 'world')
>>> lambda: ('hello', 'world')
<function <lambda> at 0x7fc13d86e7d0>

Note the subtle difference in both the input and output.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM