top | item 32277204

(no title)

MapleWalnut | 3 years ago

Your Python example has unnecessary type annotations. Python type checkers like mypy and Pylance can infer the type of `words` automatically.

    def main() -> None:
        words = ["Hello", "World"]
        for word in words:
            print(word)

    if __name__ == '__main__':
        main()

discuss

order

ghostwriter|3 years ago

Yes and no. That particular example can indeed be type-checked without extra annotations (unless I want to indicate that the use-case of the variable is actually immutable). But consider I slightly modify the script:

    def main() -> None:
        words = []
        for word in (words + ["Hello"]):
            print(word)

        if __name__ == '__main__':
            main()
MyPy rejects to infer the type of the iterable. Here's an equivalent Haskell version that does infer the type without manual annotations:

    import Data.Foldable (for_)

    main = do
        let words = []
        for_ (words ++ ["Hello"]) (\word -> print word)

tejinderss|3 years ago

typescript can infer it too:

  function main() {
      let words = [];
      for (const word of [...words, 'Hello']) {
          console.log(word);
      }
  }