
On 12/28/2013 05:10 PM, Chris Angelico wrote:
On Sun, Dec 29, 2013 at 1:59 AM, spir <denis.spir@gmail.com> wrote:
This would also be allowed:
from this or that or another import spam
We'd also, or rather, need:
from this import foo or that import bar or another import baz as spam
which starts to be a bit complicated... Maybe (or perhaps) with parens:
from ((this import foo) or (that import bar) or (another import baz)) as spam
Can't say I like that variant - getting complicated and hard to read, even with parens. If you're importing different names from different modules, it's going to get very long, and then people are going to want to split it across lines, and then the obvious question is: what's been gained over the try/except variant?
There is one thing, though, that I'm seeing of all this. Exception throwing is asymmetrical: you can attempt a series of statements until one fails, but there's no convenient syntax to attempt a series of statements until one succeeds.
This is the logic of ordered choice (in parsing) I evoked in previous post, isn't it? Also same logic as 'find_first' funcs or the like (or of python's 'any' I guess).
I wonder, could the more general case be solved? Is there a way to, without stupid stuff like eval, wrap up a few statements so they can be executed in a loop:
def import_any(statement_list): for try_me in statement_list: try: # uhh, this is the bit I'm not sure about... try_me() # this would work if they're functions instead! return except ImportError: pass raise ImportError
This works for a set of functions, but not for a bunch of "from this import that" statements. Would it be worth mangling the top of your script until it can be done with importlib or __import__? Doesn't seem nearly as clean, somehow.
You seem to be asking for kinds of ruby blocks (or procs?), aren't you? Very practicle at times (while I'm not a fan of them, abuse leads to less readable code, as in FP). I'd enjoy them in python to encode conditional actions, like game events: a kind of pair (cause_state, effect_action) with a generic logic. In Python, one has to encode every cause and every action as separate functions, because they are distinct pieces of (named) data, while typically they're both one-liners (eg: if a unit steps on this very hex, add 15% to its health points). Denis