Hacker News new | ask | show | jobs
by amelius 3739 days ago
Related: https://blog.glyphobet.net/essay/2557

By the way, I prefer Javascript's scoping rules over Python's. Also, it is easier to create a lexical block in Javascript than in Python.

2 comments

Yes, it's because idiomac Python don't make use of those concept as much. E.G: asyncio uses await instead of callbacks.
Your post seems quite imprecise about Python's semantics...
The part about `lambda` is certainly imprecise. You can use the ternary form of `a if b else c` and you can use comprehensions and/or functional style with `map` or `filter` or things from itertools if you want iteration in a `lambda`. Instead of putting statements inside the `lambda`, you should write whatever would be a statement as a helper function, and just refactor the `lambda` so that the sequence of statements you wanted will just be some expression.

I didn't check in Python 2, but in Python 3 anyway, `type()` of a `lambda` is definitely `function` and the `lambda` object has a `__code__` attribute with `co_code` containing the actual bytecode, so it's definitely a function.

For raising errors, once again you can just define a helper that does the raising -- the limitation here is the use of statements, not anything inherent to exceptions. For example:

    In [56]: def r():
       ....:     raise TypeError
       ....: 

    In [57]: f = lambda x: x[0] if isinstance(x, list) else r()

    In [58]: f([1])
    Out[58]: 1

    In [59]: f("hi")
    ---------------------------------------------------------------------------
    TypeError                                 Traceback (most recent call last)
    <ipython-input-59-987cd5963ca4> in <module>()
    ----> 1 f("hi")

    <ipython-input-57-b0e388d24fbc> in <lambda>(x)
    ----> 1 f = lambda x: x[0] if isinstance(x, list) else r()

    <ipython-input-56-a540441a09db> in r()
          1 def r():
    ----> 2     raise TypeError
          3 

    TypeError:
The same idea would work with context managers, etc.

FWIW, having used Python for a long time, I see the limitations on `lambda` as very good things. `lambda` should almost never be used for complex, side-effectful logic, and instead should be used when a short expression needs to be encapsulated and it's easier to do so with an anonymous function than a full function definition, and to a lesser extent sometimes for some tricky metaprogramming use cases, like dynamically binding functions at run time.

I'm sure that high-quality Javascript style probably implicitly uses these same kinds of limitations, even if the language itself doesn't make it mandatory.