对于PEP 484和585中指定的类型提示语法,是否有任何方法可以指示函数的参数应该是可由函数修改的可变引用
例如,C#有ref
个参数,所以在Python中,是否有任何等价物?e、 g
>>> def foo(spam: "Mutable[List[int]]"):
... spam.append(sum(spam))
...
>>> a = [1, 2, 3]
>>> foo(a)
>>> a
[1, 2, 3, 6]
或者如果不是,我如何定义这样一个类型而不使检查逻辑认为它是一个特殊的Mutable
类而不是List[int]
?显然,这将被用作开发人员更容易理解方法的工具,而不是用来从根本上改变程序的工具
为了清楚起见,我知道列表的定义是可变的,但我想知道是否有一种方法可以定义,例如,当发生变异时
>>> def bar(sandwich: Mutable[List[str]], fridge: List[str]):
... sandwich.extend(random.sample(fridge, k=3))
默认情况下,列表被视为始终是可变的。因此,如果您想表明某些列表永远不会更改,最好使用一些只读接口或协议(如
typing.Sequence
或typing.Collection
)来明确表示这两种类型的语义与相应的collections.abc类型相同。我想你可以把它们看作与C#的IReadOnlyCollection大致相同
如果您想要一个通用的可变序列,请使用
MutableSequence
。请注意,列表同时满足Sequence和MutableSequence协议列表在Python中是可变的,因此不需要显式的
Mutable
类引用:相关问题 更多 >
编程相关推荐