Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Indicating that a parameter should be a mutable reference

Tags:

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))
like image 680
Sam Rockett Avatar asked Jan 08 '20 11:01

Sam Rockett


1 Answers

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]
like image 122
amanb Avatar answered Nov 14 '22 23:11

amanb