Can global variable be passed into Python function?
rosuav at gmail.com
Sun Mar 2 17:23:10 CET 2014
On Mon, Mar 3, 2014 at 2:52 AM, Marko Rauhamaa <marko at pacujo.net> wrote:
> Roy Smith <roy at panix.com>:
>> In article <87fvn08vux.fsf at elektro.pacujo.net>,
>> Marko Rauhamaa <marko at pacujo.net> wrote:
>>> 3. TRY-EXCEPT (3500% slower than DICT DISPATCH TABLE)
>> I'm glad to hear that. I hope nobody took me seriously when I
>> suggested this.
> I actually have employed the idea before in a related but slightly
> different use case.
> Anyway, it's extremely close to the switch statement's use case and
> should give some guidance if a proper switch statement is ever worked
> into the language. What's killing the performance is the backtrace
> generation and longjmp trickery. If an analogous syntax could be (A)
> separated from BaseException and (B) compiled into a dict, we could have
> a winner.
The trouble is, try/except fundamentally can't be compiled into a
dict, because Python's exception handling is based on subclasses.
except FileNotFoundError: pass
except OSError: raise RuntimeError("Oops")
except Exception as e: log(e)
except: log("Aborting!"); raise
How would you handle that with a dict? It's inherently ordered - a
FileNotFoundError would be caught by any one of those clauses, and
since there's no sane way to "pick the narrowest", the best way to
handle it is sequential evaluation. (Also, it's worth noting that
exception lists are not constants. It's possible to do downright
insane things like calling a function to figure out what exceptions to
handle. Yeah, that's pretty stupid, right there.)
A switch block that works with constants and equality *can* be turned
into a dict. If the constants are hashable, use them as the keys
directly; if they're not hashable and/or you want to use object
identity as the criterion (effectively like using 'is' rather than
'==' for your case statements), use id(x) as the keys, and make sure
you have other references to the objects. Then it'll be fine as a
If the switch block uses inequalities, then it suffers from the same
problem as the try/except block - it's inherently ordered, in case
(pun intended) there's a switched-on value that matches more than one.
(You could possibly optimize the int case, but that would be way WAY
too specific for a generic language structure.)
More information about the Python-list