Live data from Hacker News

Python developers are embracing type hints

pyrefly.org

521–530 of 581 posts

Re: Python developers are embracing type hints

#521
Is it me or is everything slowly moving to strong types but don't want to commit?

For PHP it slowly got introduced in php5.4 and now it's expected to type hint everything and mark the file strict with linters complaining left and right that "you're doing a bad job by having mixed-type variables"

In Ruby you get Sorbet or RBS.

What is JavaScript? Oh, you mean TypeScript.

and so on ..

My take is that if you need strong types switch to a language with strong types so you can enjoy some "private static final Map> getAttemptsBatches(...)"

Re: Python developers are embracing type hints

#522
post #396
post #331

Earlier quoted context omitted.

In my experience, the right tooling makes Python typing a big win. Modern IDEs give comprehensive real-time feedback on type errors, which is a big productivity boost and helps catch subtle bugs early (still nowhere near Rust, but valuable nonetheless). Push it too far though, and you end up with monsters like Callable[[Callable[P, Awaitable[T]]], TaskFunction[P, T]]. The art is knowing when to sprinkle types just en…

When you hit types like that type aliases come to the rescue; a type alias combined with a good docstring where the alias is used goes a long way

On the far end of this debate you end up with types like _RelationshipJoinConditionArgument which I'd argue is almost more useless than no typing at all. Some people claim it makes their IDE work better, but I don't use an IDE and I don't like the idea of doing extra work to make the tool happy. The opposite should be true.

    sqlalchemy.orm.relationship(argument: _RelationshipArgumentType[Any] | None = None, secondary: _RelationshipSecondaryArgument | None = None, *, uselist: bool | None = None, collection_class: Type[Collection[Any]] | Callable[[], Collection[Any]] | None = None, primaryjoin: _RelationshipJoinConditionArgument | None = None, secondaryjoin: _RelationshipJoinConditionArgument | None = None, back_populates: str | None = None, order_by: _ORMOrderByArgument = False, backref: ORMBackrefArgument | None = None, overlaps: str | None = None, post_update: bool = False, cascade: str = 'save-update, merge', viewonly: bool = False, init: _NoArg | bool = _NoArg.NO_ARG, repr: _NoArg | bool = _NoArg.NO_ARG, default: _NoArg | _T = _NoArg.NO_ARG, default_factory: _NoArg | Callable[[], _T] = _NoArg.NO_ARG, compare: _NoArg | bool = _NoArg.NO_ARG, kw_only: _NoArg | bool = _NoArg.NO_ARG, lazy: _LazyLoadArgumentType = 'select', passive_deletes: Literal['all'] | bool = False, passive_updates: bool = True, active_history: bool = False, enable_typechecks: bool = True, foreign_keys: _ORMColCollectionArgument | None = None, remote_side: _ORMColCollectionArgument | None = None, join_depth: int | None = None, comparator_factory: Type[RelationshipProperty.Comparator[Any]] | None = None, single_parent: bool = False, innerjoin: bool = False, distinct_target_key: bool | None = None, load_on_pending: bool = False, query_class: Type[Query[Any]] | None = None, info: _InfoType | None = None, omit_join: Literal[None, False] = None, sync_backref: bool | None = None, **kw: Any) → Relationship[Any]

Re: Python developers are embracing type hints

#523
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.

It's not duck typing if you have to declare the type...

Re: Python developers are embracing type hints

#524
post #140

Earlier quoted context omitted.

OTH I only came to realize that I actually like duck typing in some situations when I tried to add type hints to one of my Python projects (and then removed them again because the actually important types consisted almost entirely of sum types, and what's the point of static typing if anything is a variant anyway). E.g. when Python is used as a 'scripting language' instead of a 'programming language' (like for writin…

Note1: Type hints are hints for the reader. If you cleverly discovered that your function is handling any type of data, hint that! Note2: From my experience, in Java, i have NEVER seen a function that consumes explicitely an Object. In Java, you always name things. Maybe with parametric polymorphism, to capture complex typing patterns. Note 3: unfortunately, you cannot subclass String, to capture the semantic of its…

An example of a function in Java that consumes a parameter of type Object is System.out.println(Object o)

Many such cases.

Re: Python developers are embracing type hints

#525

I was extremely skeptical when typing was introduced. What's the point if runtime ignores them. I forced myself to use them as documentation and now I'm on the other side of the spectrum, all code should have them. It already helped me a lot during refactors and I always wished more code had types. I think the same is true for AIs, they will benefit from having the types explicitly said. It's a shame they currently d…

> What's the point if runtime ignores them. Ideally, with static checking, the runtime shouldnn’t need to care about types because cide that typechecks shouldn’t be capable of not behaving according to the types declared. Python, even with the most restrictive settings in nost typecheckers, may not quite achieve that, but it certainly reeuces the chance of surprises lf that kind compared to typing information in docs…

The thing is, when typing was being discussed, I was hoping it would lead to JavaScript-like evolution, where the dynamic nature of Python could be restricted if I use the right types, and a JIT compiler could optimize parts of the code, expecting u32 ints instead of PyObjects.

Re: Python developers are embracing type hints

#526
post #391

Earlier quoted context omitted.

Sounds like the ecosystem needs an "indexable" type annotation. Make it an "indexable " for good measure.

Right, this was my thought. Can’t you just use a typing.Protocol on __getitem__ here? https://typing.python.org/en/latest/spec/protocol.html Something like from typing import Protocol class Indexable(Protocol): def __getitem__(self, i: int) -> Self: ... Though maybe numpy slicing needs a bit more work to support

Slicing is totally hintable as well.

Change the declaration to:

def __getitem__(self, i: int | slice)

Though to be honest I am more concerned about that function that accepts a wild variety of objects that seem to be from different domains...

I'd guess inside the function is a HUGE ladder of 'if isinstance()' to handle the various types and special processing needed. Which is totally reeking of code smell.

Re: Python developers are embracing type hints

#527

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…

    And you better believe that every single admissible type
This is exactly why I hate using Python.

Re: Python developers are embracing type hints

#528
post #510

Earlier quoted context omitted.

Why can’t you re-use it with limited types? If the types are too numerous/hard to maintain it seems like the same would apply to the runtime code.

Because it’s nice to reuse code. It’s virtually never the case that a function being compatible with too many types is an issue. The issue is sometimes that it isn’t clear what types will be compatible with a function, and people make mistakes. Python’s type system is overall pretty weak, but with any static language at least one of the issues is that the type system can’t express all useful and safe constructs. This…

>It’s virtually never the case that a function being compatible with too many types is an issue

This kind of accidental compatibility is a source of many hard bugs. Things appear to work perfectly, then at some point it does something subtly different, until it blows up a month later

Re: Python developers are embracing type hints

#529
post #347

Earlier quoted context omitted.

>why not a protocol type it was a sin that python's type system was initially released as a nominal type system. they should have been the target from day one. being unable to just say "this takes anything that you can call .hello() and .world() on" was ridiculous, as that was part of the ethos of the dynamically typed python ecosystem. typechecking was generally frowned upon, with the idea that you should accept any…

I disagree. I think, if the decision was made today, it probably would have ended up being structural, but the fact that it isn't enables (but doesn't necessarily force) Python to be more correct than if it weren't (whereas forced structural typing has a certain ceiling of correctness). Really it enabled the Python type system to work as well as it does, as opposed to TypeScript, where soundness is completely thrown…

>The use for protocols in Python in general I've found in practice to be limited (the biggest usefulness of them come from the iterable types)

Most Python's dunder methods make it so you can make "behave alike" objects for all kinds of behaviors, not just iterables

Re: Python developers are embracing type hints

#530
post #445

Earlier quoted context omitted.

This is a strange and aggressive bit of pedantry. Yes, you'd also need `__radd__` for classes that participate in heterogenous-type addition, but it's clear what was meant in context. The fundamentals are not all "beginner" level and beginners wouldn't be implementing operator overloads in the first place (most educators hold off on classes entirely for quite a while; they're pure syntactic sugar after all, and the u…

> This is a strange and aggressive bit of pedantry. There's nothing pedantic about it. That's how Python works, and getting into the nuts and bolts of how Python works is precisely why the linked article makes type hinting appear so difficult. > The entire point is that we have an intuition about what can be "added", but can't express it in the type system in any meaningful way. As the post explores, your intuition i…

> your intuition is also incorrect.

No, it definitionally isn't. The entire point is that `+` is being used to represent operations where `+` makes intuitive sense. When language designers are revisiting the decision to use the `+` symbol to represent string concatenation, how many of them are thinking about algebraic fields, seriously?

And all of this is exactly why you can't just say that it's universally bad API design to "accept all types". Because the alternative may entail rejecting types for no good reason. Again, dynamically typed languages exist for a reason and have persisted for a reason (and Python in particular has claimed the market share it has for a reason) and are not just some strictly inferior thing.

Post reply on HN