33 comments

[ 2.8 ms ] story [ 70.9 ms ] thread
Interesting to find this here, if someone else haven't followed Python3, there is also NamedTuple which for all purposes is like immutable record:

    from typing import NamedTuple
    class Coord(NamedTuple):
        x: int
        y: int
I would prefer immutable records over dataclasses on many occasions.
NamedTuple works great for a lot of cases, but not always. For example, when dealing with attribute defaults for mutable collections. Dataclasses have a `default_factory` that is used in these occasions.
Long gone are the days of "There should be one-- and preferably only one --obvious way to do it" from PEP 20 ("Python Zen") and it's a pity IMO.
Yeah, Python is basically slowly becoming a TypeScript.

On one one hand: yay types. On the other hand… yeah, this isn’t Python anymore. What used to be a fairly simple language with some well known quirks evolved into an ungrokable katamari of every single possible language feature, a duct taped mush of pieces from different puzzle sets.

I guess it’s a victim of its own success. I just wish it stayed good old, Python, and people would just use different languages for different needs instead of needing one general purpose language for everything.

I don't see how this is duct-tabing, decorators are very straightforward syntax sugar over Python's everything-is-an-object mentality

@decorator some_func

is simply

some_func = decorator(some_func)

There is no C++style "Here is 100 more arcane rules and 1000 exceptions and meta-rules that govern their interaction and application". It's all consistent additions to the language that does nothing but abstract out what you could do by hand but more verbose-ly and error-prone-ly. In fact, nothing in the above comments except type annotations are "language features" at all, they are libraries, and not even implicitly imported at that.

And almost nothing of these are actually language features but in the library.
"Python is basically slowly becoming a TypeScript." If only.
Part of the reason I wrote my last app in Node/Typescript is because Python’s typing was such crap and MyPy wasn’t mature enough at the time.
You can pass frozen=True to the @dataclass decoratot.
NamedTuples work with and without type hints, but Dataclasses only work with type hints: https://subreply.com/reply/lsk
dataclasses author here.

That's not true. You can use make_dataclass the same way you can use namedtuple:

  >>> from dataclasses import make_dataclass
  >>> A = make_dataclass("A", ["x", "y", "z"])
  >>> A(1, 2, 3)
  A(x=1, y=2, z=3)
It is true that if you want to use @dataclass you have to use annotations, just the way you do with typing.NamedTuple. But as others have noted, the annotation is mostly ignored.

[edited for formatting]

Can you assign defaults with make_dataclass() but no types?
Dataclasses can optionally be «frozen» / immutable IIRC.

Namedtuple is intended for when you need a tuple. I’ve used it for e.g numpy array shapes, so image data has names (imgshape.width instead of imgshape[1]). There, you need an actual tuple (or subclass of tuple if you want).

If I recall correctly, NamedTuple doesn’t support calculated properties, but a Data class does (as the first example shows).
Data classes are another useless, slow Python hack elevated to a language construct. The old boys love these hacks since they think it shows how versatile Python is.
It's not useless. Hack maybe (uses type annotations but they are not checked unless you add something besides vanilla python. I.e they can lie.)
Why is this post flagged? I cannot see what has been said because someone with a bit of power decided for me. I hate it when people do that.

Could you please share the contents?

The ability to see flagged posts can be enabled in settings with the showdead option.
Thank you.

Unsurprisingly, there's nothing wrong with what that person said. Seems like the people who posted this news item were butthurt. Oh so typical

It's a completely new account that was created specifically to write a negative comment in a post. Maybe that's enough for the flagging?
Think about it this way. If a user gets enough upvotes they get a link to "vouch" for a dead post and possibly undelete it. Would you vouch for that post? Would you say "This kind of post is what we need on HN"? I think it adds little value, even if there's "nothing wrong with it".
In my opinion Pydantic is Dataclass++ and NamedTuple+. I use it everywhere performance is not critical. It does type casting and provides an option for strict types. It lets you use custom types where you can define min and max size of a list or tuple etc. Every time I had a weird validation I needed to do, the Pydantic docs already had a built-in way to do it (E.g. conlist).

It has excellent support for JSON and JSON schemas out of the box.

Error messages are excellent! Tells you exactly what went wrong (most of the time) during validation.

I do use Pydantic even when Dataclass and NamedTuples are sufficient, I know that's a bit cargo cultish but it lowers the mental overhead by just having to perfect one of way of doing things.

> it lowers the mental overhead by just having to perfect one of way of doing things.

That's exactly the point. The mental burden of remembering the quirks of (and having to choose between) namedtuples, typeddicts, dataclasses etc is very real.

I just wish I could disable the type coercion. E.g. 1 becomes "1" if the attribute is annotated str.
My recommendation is to get into the habit using StrictStr, StrictInt and StrictFloat as your choice of types to start off with and use str, int, float etc only when coercion is acceptable.

Coercion is quite powerful and saves me quite a bit of work. I write validation for config files that non programmers create. I would happily avoid explaining the difference between a 1 and a "1" to them whenever I can and let coercion do the work. It reduces the mental load on them too.

I'm a fan of Pydantic and also the FastAPI project which builds heavily on it. The OpenAPI integration is just... magical.

The Pydantic page itself provides some pretty nice notes on why it's awesome: https://pydantic-docs.helpmanual.io/#rationale

Data classes were added as a core part of Python three and a half years ago and were available as an option before that. Why is this of interest now?
Not everyone is up to date.
I use these for almost all my Python Classes. In my imaginary Python 4, these are the default. This, along with python's Enum, make up the core of my projects.