Live data from Hacker News

Python type hints may not be not for me in practice

utcc.utoronto.ca

41–50 of 209 posts

Re: Python type hints may not be not for me in practice

#41

Sometimes I feel like we need an analog to javascript/typescript. Ptypethon if you will.

Absolutely. The main problem with python typing is that checking types is optional. A dialect with mandatory types (with inference) and runtime/load-time checking would be great.

Re: Python type hints may not be not for me in practice

#42
post #8

The logic of type hint is not bad but sadly I think that type hint are making python source code messy and unreadable. I'm missing a lot simple functions with explicit argument names and docstrings with arguments types and descriptions clearly but discreetly documented. It was one big strength of Python to have so simple and clean code without too much boilerplate. Also, I have the feeling that static typing extremis…

Python has union types, and you can type something as a container type with no type parameters.

You can but it defeats the purpose of typing. Makes a little bit more complicated to code and more verbose for almost no benefit. That is my point.

Re: Python type hints may not be not for me in practice

#43
My objection to strong types in python is philosophical. Python mimics natural language, and natural language rejects strong types for context resolved ambiguity.

In the way we resolve these issues in natural language, we can resolve bugs in python, that is, “do you mean integer ’3’ or string’3’” instead of insisting we define everything always forever.

To me, people who use type hinting are just letting me know they have written code that doesn’t check in line.

Re: Python type hints may not be not for me in practice

#44
post #37
post #21

The Python type system is pretty bad, but it's still 100x better than not using types. We are heavy users of the (Rust) type system at Svix, and it's been a godsend. I wrote about it here https://www.svix.com/blog/strong-typing-hill-to-die-on/ We also use Python in some places, including the shitty Python type-system (and some cool hackery to make SQLAlchemy feel very typed and work nicely with Pydantic).

Looking at that blog post, I find it illustrative in how people who like strong types and people who dislike strong types are addressing different form of bugs. If the main types of issues comes from bugs like 1 + "2" == 12" , then strong types is a big help. It also enables many developers who spend the majority of time in a programming editor to quickly get automatic help with such bugs. The other side is those peo…

I think you're missing the point of the blog a bit, as the `1 + "2" == "12"` type of issues wasn't it. It definitely also sucks and much more common than you make it sound (especially when refactoring) but it's definitely not that.

Anyhow, no need to rehash the same arguments, there was a long thread here on HN about the post, you can read some of it here: https://news.ycombinator.com/item?id=37764326

Re: Python type hints may not be not for me in practice

#45
post #21

The Python type system is pretty bad, but it's still 100x better than not using types. We are heavy users of the (Rust) type system at Svix, and it's been a godsend. I wrote about it here https://www.svix.com/blog/strong-typing-hill-to-die-on/ We also use Python in some places, including the shitty Python type-system (and some cool hackery to make SQLAlchemy feel very typed and work nicely with Pydantic).

> (and some cool hackery to make SQLAlchemy feel very typed and work nicely with Pydantic). Sounds interesting. Can you elaborate on the cool hackery? We introduced SQLModel recently but struggle in a few cases (e.g. multi-level joins). Do you know reference projects for SQLAlchemy and pydantic?

My info is maybe a bit dated, as it's been a while since we wrote this hackery. We also adopted SQLModel at some point but we had to patch it to work well (I think some of my contributions are now in upstream). As for some of the hacks:

    def c(prop: t.Any) -> sa.Column:  # type: ignore
        return prop
To make it possible to access sqlmodel properties as columns for doing things like `in_` but still maintaining type safety.

Added types ourselves to the base model like this:

    __table__: t.ClassVar[sa.Table]
Added functions that help with typing like this:

    @classmethod
    async def _fetch_one(cls: t.Type[BaseT], db: BaseReadOnlySqlSession, query: Select) -> t.Optional[BaseT]:
        try:
            return (await db.execute(query)).scalar_one()
        except NoResultFound:
            return None
and stuff like this for relationships:

    def ezrelationship(
        model: t.Type[T_],
        id_our: t.Union[str, sa.Column],  # type: ignore
        id_other: t.Optional[t.Union[t.Any, sa.Column]] = None,  # type: ignore
    ) -> T_:
        if id_other is None:
            id_other = model.id
        return sqlm.Relationship(sa_relationship=relationship(model, primaryjoin=f"foreign({id_our}) == {id_other}"))


    def ezrelationship_back(
        id_our: t.Union[str, sa.Column],  # type: ignore
        id_other: t.Union[str, sa.Column],  # type: ignore
    ) -> t.Any:
        model, only_id2 = id_other.split(".")
        return sqlm.Relationship(
            sa_relationship=relationship(
                model,
                primaryjoin=f"foreign({id_our}) == {id_other}_id",
                back_populates=only_id2,
            )
        )

I hope this helps, I don't have time to find all the stuff, but we also hacked on SQLAlchemy a bit, and in other places.

Re: Python type hints may not be not for me in practice

#46
post #43

My objection to strong types in python is philosophical. Python mimics natural language, and natural language rejects strong types for context resolved ambiguity. In the way we resolve these issues in natural language, we can resolve bugs in python, that is, “do you mean integer ’3’ or string’3’” instead of insisting we define everything always forever. To me, people who use type hinting are just letting me know they…

Python has always been strongly typed, since the very beginning.

The article and the feature has nothing to do with strong types.

Re: Python type hints may not be not for me in practice

#47
The thing that the author says they would prefer is already in Python, it's called NewType (https://docs.python.org/3/library/typing.html#typing.NewType)

They say "...so I can't create a bunch of different names for eg typing.Any and then expect type checkers to complain if I mix them."

`MyType = NewType('MyType', Any)`

is how you do this.

At the end, they suggest a workflow: "I think my ideal type hint situation would be if I could create distinct but otherwise unconstrained types for things like function arguments and function returns, have mypy or other typing tools complain when I mixed them, and then later go back to fill in the concrete implementation details of each type hint"

That's just doing the above, but then changing the `NewType('MyType', Any)` to something like `NewType('MyType', list[dict[str, int]])` later when you want to fill in the concrete implementation.

Re: Python type hints may not be not for me in practice

#48
post #7

Type hints are nice, until you have to interact with a library that isn't type-hinted, and then it very quickly becomes a mess. I don't know how other IDEs behave, but VScode + the Python extensions try to infer the missing hints and you end up with beauties such as `str | None | Any | Unknown`, which of course are completely meaningless. Even worse, the IDE marks as an error some code that is perfectly correct, beca…

I believe there's a mode for VS Code type checking which ignores untyped code - have you tried that?

Re: Python type hints may not be not for me in practice

#49
post #37
post #21

The Python type system is pretty bad, but it's still 100x better than not using types. We are heavy users of the (Rust) type system at Svix, and it's been a godsend. I wrote about it here https://www.svix.com/blog/strong-typing-hill-to-die-on/ We also use Python in some places, including the shitty Python type-system (and some cool hackery to make SQLAlchemy feel very typed and work nicely with Pydantic).

Looking at that blog post, I find it illustrative in how people who like strong types and people who dislike strong types are addressing different form of bugs. If the main types of issues comes from bugs like 1 + "2" == 12" , then strong types is a big help. It also enables many developers who spend the majority of time in a programming editor to quickly get automatic help with such bugs. The other side is those peo…

It's not about the bugs, it's about designing the layout of the program in types first (ie, laying out all of the data structures required) such that the actual coding of the functionality is fairly trivial. This is known as type driven development: https://blog.ploeh.dk/2015/08/10/type-driven-development/

Re: Python type hints may not be not for me in practice

#50
post #21

The Python type system is pretty bad, but it's still 100x better than not using types. We are heavy users of the (Rust) type system at Svix, and it's been a godsend. I wrote about it here https://www.svix.com/blog/strong-typing-hill-to-die-on/ We also use Python in some places, including the shitty Python type-system (and some cool hackery to make SQLAlchemy feel very typed and work nicely with Pydantic).

Can you give some examples of how the Python type system is disappointing you?

default values! Since type hints are *hints*, it is difficult to set default values for complicated types. For instance, if you have lists, dicts, sets in the type signature, without a library like pydantic, it is difficult and non-standard. This becomes even more problematic when you start doing more complicated data structures. The configuration in this library starts to show the problems. https://koxudaxi.github.io/datamodel-code-generator/custom_t...

The issue very much is a lack of a standard for the entire language; rather than it not being possible.

Post reply on HN