TL;DR

I think Python's distinction between code (e.g. classes) and data (e.g. dicts) is a good distinction to keep -- if you want code, define code, and datcalasses make that very easy these days.

And now the detailed version:

On Sun, Feb 6, 2022 at 6:05 AM Chris Angelico <rosuav@gmail.com> wrote:
> This feature is far more useful in JS because JS objects double up as mappings -

Exactly. And because of this the behaviour is well defined. However, I think that there's alway as issue with "data", e.g. mappings, and "code", e.g. classes with attributes. 

Given how dynamic Python is, it can be a fuzzy boundary, but I don't think we should make it even fuzzier. (and it JS, there is no boundary at all).

Using Chris's example:

for {codec_type, width, height} in info["streams"]:
    if codec_type == "video":
        ...
This would be extremely convenient, and it doesn't really work with dataclasses.

First, how does this work now? This?

for  stream in info["streams"]:
    if stream['codec_type'] == "video":
        ....

Is that so bad? as you have hard_coded codec_type, I suppose it's a bit more kludgy, but if the codec_type was in a variable, it would be more convenient.

As for dataclasses, this is what i mean by "code" vs "data" -- if you know when you are writing the code exactly what key (fields, etc) you expect , and you want to be able to work with that data model as code (e.g. attribute access, maybe some methods, then you do:

In [10]: @dataclass
    ...: class Stream:
    ...:     codec_type : str
    ...:     width: int
    ...:     height: int

And if you have that data in a dict (say, from JSON, then you can extract it like this:

In [11]: stream_info = {'codec_type': 'video',
    ...:                'width': 1024,
    ...:                'height': 768,
    ...:                }

In [12]: stream = Stream(**stream_info)

In [13]: stream
Out[13]: Stream(codec_type='video', width=1024, height=768)

That only works if you dict is in exactly the right form, but that would be the case anyway.

Granted, that's a lot of code for a quickscript, but if it's a quick script, just work with the dict.

IN practice, it's not so simple when you have a more nested data structure, but I don't think this proposal would help with that, and it's not hard to build that on top of dataclasses either, see Pydantic, or attrs, or my own half-baked flexi project:

https://github.com/PythonCHB/flexi

(note: half-baked because the public project is not well tested nor documented, but I am using this very code in a pretty substantial system with a very highly nested structure:

https://adios.orr.noaa.gov

(and the code: https://github.com/NOAA-ORR-ERD/adios_oil_database)

-CHB

--
Christopher Barker, PhD (Chris)

Python Language Consulting
  - Teaching
  - Scientific Software Development
  - Desktop GUI and Web Development
  - wxPython, numpy, scipy, Cython