Live data from Hacker News

Python developers are embracing type hints

pyrefly.org

421–430 of 581 posts

Re: Python developers are embracing type hints

#421
post #262

Earlier quoted context omitted.

I didn't. I've been mainly a Python, PHP and JavaScript programmer for ~25 years and my experience with typed languages was mostly pre-type-inference Java which felt wildly less productive than my main languages.

> I didn't. I've been mainly a Python, PHP and JavaScript programmer for ~25 years Maybe its time you expanded your horizons, then. Try a few statically typed languages. Even plain C gives you a level of confidence in deployed code that you will not get in Python, PHP or Javascript.

Maybe if your C has aggressive test coverage and you’re using Valgrind religiously and always checking errno when you’re supposed to and you’re checking the return value of everything. Otherwise lol. C as it’s written by middling teams is a soup of macros, three-star variables, and questionable data structure implementations, where everybody fiddles with everybody else’s data. I’ll take good C over bad Python, but good C is rare.

Re: Python developers are embracing type hints

#422

Earlier quoted context omitted.

> Not bolt on a sort of type system which actively fights against the way I use the language on a day to day basis. Can you help me out with an example of a Python usage pattern against which the type system seems to be fighting?

Ok, so this is just one of many examples but the most immediate one is where I don't care about the immutable sanctity of the variable I have just declared. I often use Python for data munging and I'll frequently write code that goes foo = initial_value ... foo = paritally_cleaned_up_value ... if check: foo = fianllylikethis else: foo = orlikethis Where the type of the value being assigned to foo is different each ti…

Thanks, now I get why you feel like the type system is fighting your style of programming.

> all of those options are unnecessary busy work for what should be a few simple lines of code

If you re-type your variable often, then how do you make sure you’re really keeping track of all those types?

If you re-type it only a few times, then I’m not entirely convinced that declaring a few additional variables really constitutes busywork.

Small example with additional variables instead of re-typing the same variable:

    # pylint: disable=disallowed-name, missing-function-docstring, missing-module-docstring, redefined-outer-name

    from typing import NewType

    NEEDS_CHECKING = True

    NotCleaned = NewType("NotCleaned", str)
    Checked = NewType("Checked", str)
    Cleaned = NewType("Cleaned", str)

    original_foo = ["SOME  ", "dirty ", " Data"]

    annotated_foo = [NotCleaned(item) for item in original_foo]

    cleaned_foo = [
        Cleaned(item.lower().strip().replace("dirty", "tidy"))
        for item in annotated_foo
    ]

    foo: list[Checked | Cleaned]

    if NEEDS_CHECKING:
        for idx, item in enumerate(cleaned_foo):
            if item and (item[0] == " " or item[-1] == " "):
                raise RuntimeError(f"Whitespace found in item #{idx}: {item=}")
            if "dirt" in item:
                raise RuntimeError(f"Item #{idx} is dirty: {item=}")
        foo = [Checked(item) for item in cleaned_foo]
    else:
        foo = list(cleaned_foo)

    print(foo)
    # => ['some', 'tidy', 'data']
This survives strict type checking (`mypy --strict`). I don’t feel that renaming the variables introduces much noise or busywork here? One might argue that renaming even adds clarity?

Re: Python developers are embracing type hints

#423

I actually don’t like python type hints! At my work we have a jit compiler that requires type hints under some conditions. Aside from that, I avoid them as much as possible. The reason is that they are not really a part of the language, they violate the spirit of the language, and in high-usage parts of code they quickly become a complete mess. For example a common failure mode in my work’s codebase is that some func…

> you better believe that every single admissible type will eventually be fed to this function That's your problem right there. Why are random callers sending whatever different input types to that function? That said, there are a few existing ways to define that property as a type, why not a protocol type "Indexable"?

> That's your problem right there. Why are random callers sending whatever different input types to that function?

Because it’s nice to reuse code. I’m not sure why anyone would think this is a design issue, especially in a language like Python where structural subtyping (duck typing) is the norm. If I wanted inheritance soup, I’d write Java.

Ironically, that’s support for structural subtyping is why Protocols exist. It’s too bad they aren’t better and the primary way to type Python code. It’s also too bad that TypedDict actively fought duck typing for years.

Re: Python developers are embracing type hints

#424

I really love Python for it's expedience, but type hints still feel like they don't belong in the language. They don't seem to come with the benefits of optimisation that you get with static typed languages. As someone who uses C and Julia (and wishes they had time for Rust), introducing solid typing yields better end results at a minimum, or is a requirement at the other end of the scale. The extra typing clarificat…

> The extra typing clarification in python makes the code harder to read. It depends what you mean by "read". If you literally mean you're doing a weird Python poetry night then sure they're sort of "extra stuff" that gets in the way of your reading of `fib`. But most people think of "reading code" and reading and understanding code, and in that case they definitely make it easier.

As someone who has read code as easily as English for decades (which is apparently rare, if my co-workers are any indication), too many type annotations clutter it up and make it a lot harder to read. And this is after having used Typescript a lot in the past year and liking that system - it works well because so much can be inferred.

Re: Python developers are embracing type hints

#425
post #410
post #225

Earlier quoted context omitted.

That's the same complaints people had about TypeScript in the beginning, when libraries such as Express used to accept a wide range of input options that would be a pain to express in types properly. If you look at where the ecosystem is now, though, you'll see proper type stubs, and most libraries get written in TS in the first place anyway. When editing TS code, you get auto-completion out of the box, even for deep…

Except Typescript embraces duck typing. You can say "accept any object with a quack() method", for example, and it'll accept an unexpected quacking parrot. It can even tell when two type definitions are close enough and merge them.

Doesn't Go also use structural typing?

Re: Python developers are embracing type hints

#426
post #275

I like the type hints. The're not perfect and they've changed a lot between versions, but they really help catch issues early that you'd usually need to write unit tests for. Adding type hints is easier than writing those unit tests. Then you can focus your tests on more interesting things You just need to set your build up to actually do the checking as type hints by default are just documentation

My main complaint about them is no first-party support for type checking, you need external packages like beartype decorators.

Yeah, it would have been much better to have them be default enforces if present. Keeping them optional is fine, but I don't get the use-case for "you can add them but not check them"... that just leads to actively misleading hints

Re: Python developers are embracing type hints

#427

I actually don’t like python type hints! At my work we have a jit compiler that requires type hints under some conditions. Aside from that, I avoid them as much as possible. The reason is that they are not really a part of the language, they violate the spirit of the language, and in high-usage parts of code they quickly become a complete mess. For example a common failure mode in my work’s codebase is that some func…

[deleted]

Re: Python developers are embracing type hints

#428
post #410
post #225

Earlier quoted context omitted.

That's the same complaints people had about TypeScript in the beginning, when libraries such as Express used to accept a wide range of input options that would be a pain to express in types properly. If you look at where the ecosystem is now, though, you'll see proper type stubs, and most libraries get written in TS in the first place anyway. When editing TS code, you get auto-completion out of the box, even for deep…

Except Typescript embraces duck typing. You can say "accept any object with a quack() method", for example, and it'll accept an unexpected quacking parrot. It can even tell when two type definitions are close enough and merge them.

So does Python. They're called protocols. [0]

[0]: https://typing.python.org/en/latest/spec/protocol.html

Re: Python developers are embracing type hints

#429
post #410
post #225

Earlier quoted context omitted.

That's the same complaints people had about TypeScript in the beginning, when libraries such as Express used to accept a wide range of input options that would be a pain to express in types properly. If you look at where the ecosystem is now, though, you'll see proper type stubs, and most libraries get written in TS in the first place anyway. When editing TS code, you get auto-completion out of the box, even for deep…

Except Typescript embraces duck typing. You can say "accept any object with a quack() method", for example, and it'll accept an unexpected quacking parrot. It can even tell when two type definitions are close enough and merge them.

> Except Typescript embraces duck typing.

So does Python:

https://typing.python.org/en/latest/spec/protocol.html

Post reply on HN