就地分配后保留CommentedSeq flow_style

时间:2018-09-01 20:05:13

标签: python yaml ruamel.yaml

我想向一个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'

1 个答案:

答案 0 :(得分:1)

您无法指出您正在使用的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]