【问题标题】:Preserve CommentedSeq flow_style after in-place assignment就地分配后保留 CommentedSeq flow_style
【发布时间】:2018-09-01 20:05:13
【问题描述】:

我想为 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'

【问题讨论】:

    标签: python yaml ruamel.yaml


    【解决方案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]
    

    【讨论】:

    • 谢谢!我使用的是 0.15.37。更新到最新版本解决了这个问题。
    猜你喜欢
    • 2013-04-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-06-18
    • 2012-04-04
    • 1970-01-01
    • 2011-04-24
    • 1970-01-01
    相关资源
    最近更新 更多