const arguments in Python
Asked Answered
E

2

12

I have an object (numpy.ndarray, for example), that should be passed as an argument to several functions. In C++ in such cases I declared such arguments as const, in order to show, that they must not be changed.

How can I do the same in Python?

Envisage answered 20/4, 2014 at 10:44 Comment(2)
If you want to define immutable array, using tuple is the answer for it.Primateship
@KeiMinagawa Tuples are not an acceptable substitute for numpy arrays because they are not suitable for serious numerical computation.Tutorial
S
7

Syntactically, you can't. You have two choices:

  • pass a copy of your object to these functions - this way, you won't have to worry about it being corrupted

  • create a wrapper, that implements the required interface, wraps your object, and doesn't allow modifications

The second option is of course only possible if you know what interface is expected and if it's simple.

Spelter answered 20/4, 2014 at 10:50 Comment(1)
I would add a third option (perhaps expanding on the second) that depending on what's really going on, this whole deal should be managed by a class (with the object as a data member and those functions as methods).Huoh
E
2

Well, there's a trick especially for numpy arrays:

array.flags.writable=False

Envisage answered 8/1, 2023 at 16:54 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.