13

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?

2
  • 2
    If you want to define immutable array, using tuple is the answer for it. Commented Apr 20, 2014 at 11:32
  • 1
    @KeiMinagawa Tuples are not an acceptable substitute for numpy arrays because they are not suitable for serious numerical computation. Commented Jan 5, 2023 at 20:30

2 Answers 2

8

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.

Sign up to request clarification or add additional context in comments.

1 Comment

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).
3

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

array.flags.writable=False

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.