在就地分配后保留 CommentedSeq flow_style

Preserve CommentedSeq flow_style after in-place assignment

我想就地为 CommentedSeq 对象分配新值以保留其流样式。然而,这样的操作导致TypeError: '<' not supported between instances of 'slice' and 'int'

这是否意味着 CommentedSeq 不支持就地分配,这是 Python 列表的最基本功能?

from ruamel.yaml import YAML

y = YAML()
x = y.seq([1, 2])
x.fa.set_flow_style()
x[:] = [3, 4]


    451         # type: (Any, Any) -> None
    452         # try to preserve the scalarstring type if setting an existing key to a new value
--> 453         if idx < len(self):
    454             if isinstance(value, string_types) and \
    455                not isinstance(value, ScalarString) and \

TypeError: '<' not supported between instances of 'slice' and 'int'

您没有说明您使用的 ruamel.yaml 是哪个(过时的)版本,也没有说明您没有使用最新版本的原因。

CommentedSeq 不是列表或其子类,它是 MutableSequence 的子类(来自 collections.abc),虽然我不会就地调用切片赋值无论如何,Python 列表的最基本功能,肯定不是 MutableSequences.

支持的功能

然而,这并不意味着 CommentedSeq 不支持就地 [slice] 赋值:

$ mktmpenv -p /opt/python/3.6/bin/python
Running virtualenv with interpreter /opt/python/3.6/bin/python
Using base prefix '/opt/python/3.6'
New python executable in /home/venv/tmp-2aaa383875f076d7/bin/python
Installing setuptools, pip, wheel...done.
This is a temporary environment. It will be deleted when you run 'deactivate'.
(tmp-2aaa383875f076d7) $ pip install ruamel.yaml
Looking in indexes: https://pypi.org/simple, http://localhost:4040/anthon/dev/+simple/
Collecting ruamel.yaml
  Downloading https://files.pythonhosted.org/packages/77/51/f4314ebd8a3ec4989a3b3339a47382d87f251e5b82f2b7852a67649bc862/ruamel.yaml-0.15.64-cp36-cp36m-manylinux1_x86_64.whl (645kB)
    100% |████████████████████████████████| 655kB 3.5MB/s 
Installing collected packages: ruamel.yaml
Successfully installed ruamel.yaml-0.15.64
(tmp-2aaa383875f076d7) $ python
Python 3.6.6 (default, Jul 28 2018, 11:00:00) 
[GCC 4.8.4] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> from ruamel.yaml import YAML
>>> 
>>> y = YAML()
>>> x = y.seq([1, 2])
>>> x.fa.set_flow_style()
>>> x[:] = [3, 4]
>>> print(x)
[3, 4]
>>> import sys
>>> y.dump(x, sys.stdout)
[3, 4]