With the type hinting syntax specified in PEP 484 and 585, is there any way to indicate that a function's parameter should be a mutable reference that would be modified by the function?
For instance, C# has ref
paramters, so in Python, is there any equivalent? e.g.
>>> def foo(spam: "Mutable[List[int]]"):
... spam.append(sum(spam))
...
>>> a = [1, 2, 3]
>>> foo(a)
>>> a
[1, 2, 3, 6]
or if not, how could I define such a type without causing the inspection logic to think that it was a special Mutable
class instead of a List[int]
? Obviously this would be used as a tool for the developer to understand a method more easily, instead of one that would be used to fundamentally change the program.
For clarity, I'm aware that Lists by definition are mutable, but I'm wondering if there is a way to define when it will be mutated, for example
>>> def bar(sandwich: Mutable[List[str]], fridge: List[str]):
... sandwich.extend(random.sample(fridge, k=3))
Lists are mutable in Python and thus an explicit Mutable
class reference is not required:
In [3]: from typing import List
In [7]: def foo(spam:List[int]):
...: spam.append(sum(spam))
...: return spam
In [8]: a = [1,2,3]
In [9]: foo(a)
Out[9]: [1, 2, 3, 6]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With