←back to thread

620 points tambourine_man | 3 comments | | HN request time: 0s | source
Show context
serbuvlad ◴[] No.43750075[source]
All things considered, this is pretty cool. Basically, this replaces

    db.execute("QUERY WHERE name = ?", (name,))
with

    db.execute(t"QUERY WHERE name = {name}")
Does the benefit from this syntactic sugar outweigh the added complexity of a new language feature? I think it does in this case for two reasons:

1. Allowing library developers to do whatever they want with {} expansions is a good thing, and will probably spawn some good uses.

2. Generalizing template syntax across a language, so that all libraries solve this problem in the same way, is probably a good thing.

replies(12): >>43750226 #>>43750250 #>>43750260 #>>43750279 #>>43750513 #>>43750750 #>>43752117 #>>43752173 #>>43752293 #>>43754738 #>>43756560 #>>43763190 #
amelius ◴[] No.43750279[source]
One thing it misses is compile-time checks for e.g. the format spec.
replies(2): >>43750311 #>>43759637 #
karamanolev ◴[] No.43750311[source]
Doesn't all of Python miss that, having (close to) no compile time?
replies(1): >>43750359 #
amelius ◴[] No.43750359[source]
Python does some checks before it runs code. E.g.:

    print("hello")

    def f():
        nonlocal foo
gives:

    SyntaxError: no binding for nonlocal 'foo' found
before printing hello, and note that f() wasn't even called.
replies(1): >>43754533 #
nomel ◴[] No.43754533[source]
I think it's just giving an error because a valid AST can't be made, which means valid bytecode can't be made. "<word> <word>" is only valid syntax if one is a reserved word. `nonlocal(foo)` is just fine, of course.
replies(2): >>43756609 #>>43756932 #
1. zahlman ◴[] No.43756932[source]
No, it gives an error because `nonlocal foo` requests that the name `foo` be looked up in a closure, but `f` doesn't have such a closure (the `foo` defined outside the function is global instead). `nonlocal` is the same sort of keyword as `global` but for enclosing functions instead of the global namespace; see also https://stackoverflow.com/questions/1261875 .
replies(1): >>43764621 #
2. nomel ◴[] No.43764621[source]
Here's the statement checking code, which I believe is pre-AST [1]. I would have to dig more to see if that check is there to prevent invalid AST or to just "help the user" (would depend on how they reference the original variable I suppose).

But wow, that's the first time I've seen "nonlocal". In the ~100 packages I have installed, I see 0 usages!

[1] https://github.com/python/cpython/blob/a6a3dbb7db0516a72c5ef...

replies(1): >>43770427 #
3. zahlman ◴[] No.43770427[source]
Well, yes, not a lot of people write closures except perhaps when they implement decorators. So there's ordinarily no non-local scope to worry about. People tend to write classes instead, because that's what's familiar.