how to get the list form dictionary's values

Chris Angelico rosuav at gmail.com
Sun Feb 21 09:04:06 EST 2016


On Mon, Feb 22, 2016 at 12:34 AM,  <davidbenny2000 at gmail.com> wrote:
>   File "mainpy.py", line 81
>     for functionlistelement in functionlist0
>                                            ^
> SyntaxError: invalid syntax

Your actual syntax problem here is simply a missing colon. That's
easily fixed. But please, PLEASE, don't do this:

> def workingthreadpool(currentnumber1, machine1):
>  try:
>   functionlist0 = machine1.get(currentnumber1)
>
>   loop = asyncio.get_event_loop()
>   tesks = []
>
>   j = 1
>   for functionlistelement in functionlist0
>    tesks.append(asyncio.ensure_future(mappedfunc.get(functionlistelement)()))
>    if j > 1:
>     workingthreadpool(functionlistelement)
>    j = j + 1
>
>   loop.run_until_complete(asyncio.wait(tesks))
>   loop.close()
>  except:
>   print "workingthreadpool exception"

1) Indenting by a single space makes it hard to skim and see what's at
what indentation level. Indent by at least four spaces (I've seen two,
and it's still very narrow), or one tab.

2) Carrying a counter through a 'for' loop is much better done with
enumerate(). But the counter's sole purpose is to ignore the first
element, so you might want to find a completely different approach.

3) Why does this recurse anyway? Your function appends one future to
'tesks' (should that be 'tasks'?), then appends another... and then
calls itself recursively. What's that doing, exactly?

4) Bare except clauses are almost always a bad idea. In fact, if a
future version of Python raises a SyntaxWarning or even SyntaxError on
the bare except, I would see it as no loss. As of Python 2.7, it's
possible to raise an old-style class, which then won't be caught by
"except Exception:" or even "except BaseException:", but I'm pretty
sure there's nothing you can raise in Python 3 that isn't caught by
"except BaseException:". Proper exception handling generally means
either (a) catching a specific exception or list of exceptions, and
handling them; or (b) catching everything, logging them in some way,
and returning to some sort of main loop. Your code is simply reporting
the presence of an exception, nothing more, and then bailing out. Let
those exceptions bubble up to top level and be printed out!

5) Asynchronous code is way better supported in Python 3.5 than in
2.7. I strongly recommend upgrading your Python.

These considerations are less simple than the syntax issue you were
asking about, but they're also non-trivial problems. You might get
your code to _run_, but can you get it to do the right thing, even
after you tinker with it later on? Good code saves you time in the
long run.

ChrisA



More information about the Python-list mailing list