9 ms·
The Data Classes Decorator
- greymalik 5y agoData 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?
- gjvc 5y agoNot everyone is up to date.
- Ciantic 5y agoInteresting 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.
- 331c8c71 5y agoLong 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.
- q3k 5y agoYeah, 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.
- Banana699 5y agoI 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.
- formerly_proven 5y agoAnd almost nothing of these are actually language features but in the library.
- angelzen 5y ago"Python is basically slowly becoming a TypeScript." If only.
- JoBrad 5y agoPart 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.
- vsmhn 5y agoNamedTuple 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.
- BurningFrog 5y agoYou can pass frozen=True to the @dataclass decoratot.
- lcnmrn 5y agoNamedTuples work with and without type hints, but Dataclasses only work with type hints: https://subreply.com/reply/lsk https://subreply.com/reply/lsk
- ericvsmith 5y agodataclasses 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]
- lcnmrn 5y agoCan you assign defaults with make_dataclass() but no types?
- pletnes 5y agoDataclasses 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).
- woadwarrior01 5y agoThe `eval()` in the namedtuple factory function[1] makes it a bit kludgy, IMO. [1]: https://github.com/python/cpython/blob/3.10/Lib/collections/__init__.py#L414 https://github.com/python/cpython/blob/3.10/Lib/collections/...
- JoBrad 5y agoIf I recall correctly, NamedTuple doesn’t support calculated properties, but a Data class does (as the first example shows).
- xnaht 5y agoData 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.
- kzrdude 5y agoIt'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.)
- beebeepka 5y agoWhy 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?
- ratorx 5y agoThe ability to see flagged posts can be enabled in settings with the showdead option.
- beebeepka 5y agoThank 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
- dr_zoidberg 5y agoIt's a completely new account that was created specifically to write a negative comment in a post. Maybe that's enough for the flagging?
- Noumenon72 5y agoThink 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".
- nitred 5y agoIn 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.
- 331c8c71 5y ago> 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.
- eirki 5y agoI just wish I could disable the type coercion. E.g. 1 becomes "1" if the attribute is annotated str.
- kkirsche 5y agoIsn’t that the allow_mutation parameter of the field function? https://pydantic-docs.helpmanual.io/usage/schema/#field-customisation https://pydantic-docs.helpmanual.io/usage/schema/#field-cust...
- eirki 5y agoDisabling mutation prevents you from changing attributes after instantiation, no?
- nitred 5y agoMy 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.
- the__alchemist 5y agoI 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.
- avidphantasm 5y agoI recently started using [Pyserde](https://pypi.org/project/pyserde/ https://pypi.org/project/pyserde/) for easily serializing dataclasses to MsgPack format. You can even serialize dataclasses that contain numpy arrays using [msgpack-numpy](https://pypi.org/project/msgpack-numpy/ https://pypi.org/project/msgpack-numpy/). This is a good option for mixed/nested data where you can’t easily just dump your data as a Parquet file.