Hacker News new | ask | show | jobs
by hadcomplained 2065 days ago
This project seems nice, but there's some detail I have trouble wrapping my head around: why is a template string represented as a lambda containing an f-string, instead of as a plain string? Namely, wouldn't the code below suffice?

    Q("""select 1 from {otherQuery}""")
What does the following code enable that the code above cannot do?

    Q(lambda: f"""select 1 from {otherQuery}""")
1 comments

It's impossible to hook into Python's string interpolation system to the degree required for the first to work. JS and Julia can do it, e.g. in JS (with typescript annotations) it'd just be a matter of defining

   function Q(stringBits: string[]): Query {
      for (bit in stringBits) {
         if (bit is string) {
            add to sql
         } else if (bit is Query) {
            add bit to dependencies
            add bit.name to sql
         }
      }
   }
But this cannot be done currently in Python (see PEP-501), so I'm forcing the user to pass a lambda, which I can get the AST of, with which I can implement the machinery to do the above.

Suggestions for improvements are welcome!

I'm pretty confident f-strings use str.format under the hood, so instead of AST mambo-jumbo, you can do just query.format(var1="something") or something.