Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to force data immutability in a python function?

Say I define a list object and only want it to be read-only in a function I define. In C++, you'd do this with a const reference. Is there any way to do this with a python function? Does this make sense with respect to writing "pythonic" code or am I just trying to apply a C++ paradigm incorrectly?

like image 800
Skorpius Avatar asked Jan 26 '26 03:01

Skorpius


2 Answers

Use a tuple, instead:

>>> hash([1,2,3])
Traceback (most recent call last):
  File "<pyshell#7>", line 1, in <module>
    hash([1,2,3])
TypeError: unhashable type: 'list'
>>> hash((1,2,3))
2528502973977326415
>>> 

hash can define whether it is mutable or not, and produces an error of TypeError: unhashable type if it's mutable, such as lists, OTOH tuple will return some large numbers (don't need to care in this particular case), we can use a try except if you want to:

try:
    hash((1,2,3))
    print('Immutable object')
except:
    print('Mutable object')

Which outputs:

Immutable object
like image 192
U12-Forward Avatar answered Jan 28 '26 17:01

U12-Forward


In Python, all variables are references, so having an equivalent of C's const wouldn't really do anything. If the pointed-to object is mutable, you can mutate it; if it's immutable, you can't.

However, there are some types that are mutable, and some that aren't. Lists are mutable, but tuples are not. So if you pass your data as a tuple, you're guaranteed the function can't do anything to it.

To use a C metaphor, a list of integers is somewhat like an int[], and a tuple of integers is a const int[]. When you pass them to a function, it doesn't matter if you're passing a const reference or a non-const reference; what matters is whether the thing it references is const or not.

like image 21
Draconis Avatar answered Jan 28 '26 16:01

Draconis