[HN Gopher] The Data Classes Decorator
       ___________________________________________________________________
        
       The Data Classes Decorator
        
       Author : nothrowaways
       Score  : 52 points
       Date   : 2021-12-09 10:41 UTC (3 days ago)
        
 (HTM) web link (docs.python.org)
 (TXT) w3m dump (docs.python.org)
        
       | xnaht wrote:
       | 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.
        
         | kzrdude wrote:
         | 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.)
        
           | beebeepka wrote:
           | 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?
        
             | ratorx wrote:
             | The ability to see flagged posts can be enabled in settings
             | with the showdead option.
        
               | beebeepka wrote:
               | 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
        
               | dr_zoidberg wrote:
               | 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?
        
       | greymalik wrote:
       | 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?
        
         | gjvc wrote:
         | Not everyone is up to date.
        
       | selimnairb wrote:
       | I recently started using
       | [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/). This is a good
       | option for mixed/nested data where you can't easily just dump
       | your data as a Parquet file.
        
       | Ciantic wrote:
       | 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.
        
         | 331c8c71 wrote:
         | 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.
        
           | q3k wrote:
           | 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.
        
             | angelzen wrote:
             | "Python is basically slowly becoming a TypeScript." If
             | only.
        
               | JoBrad wrote:
               | 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.
        
             | Banana699 wrote:
             | 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.
        
               | formerly_proven wrote:
               | And almost nothing of these are actually language
               | features but in the library.
        
         | lcnmrn wrote:
         | NamedTuples work with and without type hints, but Dataclasses
         | only work with type hints: https://subreply.com/reply/lsk
        
           | ericvsmith wrote:
           | 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]
        
         | pletnes wrote:
         | 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).
        
         | woadwarrior01 wrote:
         | The `eval()` in the namedtuple factory function[1] makes it a
         | bit kludgy, IMO.
         | 
         | [1]:
         | https://github.com/python/cpython/blob/3.10/Lib/collections/...
        
         | BurningFrog wrote:
         | You can pass _frozen=True_ to the @dataclass decoratot.
        
         | JoBrad wrote:
         | If I recall correctly, NamedTuple doesn't support calculated
         | properties, but a Data class does (as the first example shows).
        
         | vsmhn wrote:
         | 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.
        
       | nitred wrote:
       | 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.
        
         | 331c8c71 wrote:
         | > 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 wrote:
         | I just wish I could disable the type coercion. E.g. 1 becomes
         | "1" if the attribute is annotated str.
        
           | kkirsche wrote:
           | Isn't that the allow_mutation parameter of the field
           | function?
           | 
           | https://pydantic-docs.helpmanual.io/usage/schema/#field-
           | cust...
        
             | eirki wrote:
             | Disabling mutation prevents you from changing attributes
             | after instantiation, no?
        
           | nitred wrote:
           | 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.
        
         | jayc7 wrote:
         | 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
        
       | the__alchemist wrote:
       | 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.
        
       ___________________________________________________________________
       (page generated 2021-12-12 23:02 UTC)