HatchJS.com
Cracking the Shell of Mystery
ValueError: Assignment destination is read-only
Have you ever tried to assign a value to a variable that was read-only? If so, you may have encountered a `ValueError` with the message `assignment destination is read-only`. This error occurs when you try to change the value of a variable that is either immutable or has been marked as read-only.
In this article, we’ll take a closer look at what `ValueError` is and what causes it. We’ll also discuss how to avoid this error in your own code.
What is `ValueError`?
A `ValueError` is a type of `Exception` that is raised when a value is invalid for a particular operation. In the case of `assignment destination is read-only`, the value that you are trying to assign to the variable is not compatible with the type of the variable.
For example, you cannot assign a string value to a variable that has been declared as an integer. This will cause a `ValueError` with the message `assignment destination is read-only`.
What causes `ValueError`?
There are a few different things that can cause a `ValueError`. Here are some of the most common causes:
- Trying to assign a value to a variable that is immutable. Immutable variables cannot be changed once they have been created. This includes variables that are declared as `int`, `float`, `bool`, or `tuple`.
- Trying to assign a value to a variable that has been marked as read-only. You can mark a variable as read-only by using the `@property` decorator. This prevents the value of the variable from being changed directly.
- Trying to assign a value to a variable that does not exist. If you try to assign a value to a variable that does not exist, a `ValueError` will be raised.
How to avoid `ValueError`
To avoid `ValueError`, you should make sure that you are not trying to assign an invalid value to a variable. Here are some tips:
- Check the type of the variable before assigning a value to it. If the variable is immutable, you will not be able to change its value.
- Use the `@property` decorator to mark variables as read-only. This will prevent other parts of your code from accidentally changing the value of the variable.
- Check to make sure that the variable exists before assigning a value to it. If the variable does not exist, a `ValueError` will be raised.
By following these tips, you can help to avoid `ValueError` in your code.
| Column 1 | Column 2 | Column 3 | |—|—|—| | Error message | `ValueError: assignment destination is read-only` | `This error occurs when you try to assign a value to a variable that is read-only.` | | Causes | * Trying to assign a value to a constant.
- Trying to assign a value to a property that is read-only.
- Trying to assign a value to a variable that is already assigned to a value. |
| Solutions | * Use a different variable name.
- Use the `readonly` attribute to make the variable read-only.
- Use the `setter` method to assign a value to a property that is read-only. |
In this tutorial, we will discuss the ValueError exception in Python. We will cover what a ValueError is, what the error message “assignment destination is read-only” means, and how to fix this error.
What is a ValueError?
A ValueError is a Python exception that occurs when a value is passed to a function that is not of the correct type or format. For example, trying to assign a string to a variable that is expecting an integer would raise a ValueError.
The error message for a ValueError typically includes the name of the function that raised the error, as well as the value that was passed to the function that caused the error.
>>> a = ‘123’ >>> b = int(a) Traceback (most recent call last): File “ “, line 1, in ValueError: invalid literal for int() with base 10: ‘123’
In this example, we tried to assign the string “123” to the variable `b`, which is expecting an integer. This caused a ValueError to be raised.
What does “assignment destination is read-only” mean?
When you get a ValueError with the message “assignment destination is read-only”, it means that you are trying to assign a value to a variable that is not writable. This can happen for a number of reasons, such as:
- The variable is defined as a constant.
- The variable is read-only by default.
- The variable is being used as a keyword argument in a function call.
The variable is defined as a constant
One common reason for getting a ValueError with the message “assignment destination is read-only” is that the variable is defined as a constant. A constant is a variable that cannot be changed after it has been assigned a value.
To define a variable as a constant, you can use the `const` keyword. For example:
const a = 10
Once a variable has been defined as a constant, you cannot assign a new value to it. If you try to do so, you will get a ValueError with the message “assignment destination is read-only”.
The variable is read-only by default
Some variables are read-only by default. This means that they cannot be assigned a new value after they have been created.
One example of a read-only variable is the `sys.argv` variable. The `sys.argv` variable contains a list of the command-line arguments that were passed to the Python interpreter when the program was started. This variable is read-only because it cannot be changed after the program has been started.
If you try to assign a new value to the `sys.argv` variable, you will get a ValueError with the message “assignment destination is read-only”.
The variable is being used as a keyword argument in a function call
Another common reason for getting a ValueError with the message “assignment destination is read-only” is that the variable is being used as a keyword argument in a function call.
When you use a keyword argument in a function call, the value of the argument is assigned to the corresponding keyword argument in the function definition. This means that the value of the argument is not actually assigned to the variable that you used in the function call.
For example, the following code will not raise a ValueError:
def f(a, b): print(a, b)
In this code, the value of the `a` argument is assigned to the `a` keyword argument in the `f()` function definition. This means that the value of the `a` argument is not actually assigned to the variable `a` that was used in the function call.
However, the following code will raise a ValueError:
def f(a, b): a = b
In this code, the value of the `b` argument is assigned to the `a` variable. This means that the value of the `b` argument is actually assigned to the variable `a` that was used in the function call. This will cause a ValueError to be raised because the `a` variable is read-only.
How to fix the “assignment destination is read-only” error
There are a few ways to fix the “assignment destination is read-only” error.
Change the variable to a mutable type
If the variable is defined as a constant, you can change it to a mutable type. A mutable type is a type of variable that can be changed after it has been
How to fix a ValueError with the message “assignment destination is read-only”
A ValueError with the message “assignment destination is read-only” occurs when you try to assign a value to a variable that is read-only. This can happen for a few reasons:
- The variable may be defined as a constant.
- The variable may be a property of an object that is read-only.
- The variable may be a member of a tuple or a list.
To fix this error, you need to make sure that the variable is not read-only. Here are a few ways to do this:
Make sure that the variable is not defined as a constant
If the variable is defined as a constant, you cannot assign a new value to it. To fix this, you can either remove the `const` keyword from the definition of the variable, or you can use a different variable name.
For example, the following code will raise a ValueError:
python const_value = 10 const_value = 20
To fix this, you can remove the `const` keyword from the definition of `const_value`:
python value = 10 value = 20
Or, you can use a different variable name:
python value = 10 new_value = 20
Make sure that the variable is not read-only by default
Some variables are read-only by default. For example, the `__init__` method of a class is read-only by default. This means that you cannot assign a new value to the `__init__` method.
To fix this, you can either make the variable mutable, or you can use a keyword argument to pass the value to the method.
python class MyClass: def __init__(self, value): self.value = value
my_class = MyClass(10) my_class.value = 20
To fix this, you can make the `value` attribute mutable:
def set_value(self, value): self.value = value
my_class = MyClass(10) my_class.set_value(20)
Or, you can use a keyword argument to pass the value to the `__init__` method:
my_class = MyClass(value=10) my_class.value = 20
Use a mutable object instead of an immutable object
If the variable is an immutable object, you cannot assign a new value to it. For example, the following code will raise a ValueError:
python my_list = [1, 2, 3] my_list[0] = 10
To fix this, you can use a mutable object instead of an immutable object. For example, you can use a list instead of a tuple:
Use a keyword argument instead of a positional argument
If you are passing a value to a function as a positional argument, and the function is expecting a keyword argument, you will get a ValueError with the message “assignment destination is read-only”.
python def my_function(value): value = 10
my_function(10)
To fix this, you can use a keyword argument instead of a positional argument:
my_function(value=10)
A ValueError with the message “assignment destination is read-only” can be a frustrating error to deal with, but it is usually easy to fix. By following the steps in this outline, you should be able to resolve this error and get your code working properly.
Question 1: What is a ValueError?
Answer: A ValueError is a Python exception that is raised when a value is not valid for the operation being performed. For example, trying to assign a string to a variable that is expecting an integer would raise a ValueError.
Question 2: What does the error message “ValueError: assignment destination is read-only” mean?
Answer: This error message means that you are trying to assign a value to a variable that is read-only. This can happen for a few reasons. First, the variable may be defined as read-only using the `readonly` keyword. Second, the variable may be a property of an object that is read-only. Third, the variable may be a global variable that is defined in a module that is being imported with the `readonly` flag.
Question 3: How can I fix the error “ValueError: assignment destination is read-only”?
Answer: There are a few ways to fix this error. First, you can check to make sure that the variable is not defined as read-only. Second, you can check to make sure that the variable is not a property of an object that is read-only. Third, you can check to make sure that the variable is not a global variable that is being imported with the `readonly` flag.
Question 4: What are some common causes of the error “ValueError: assignment destination is read-only”?
Answer: Some common causes of this error include:
- Trying to assign a value to a variable that is defined as read-only.
- Trying to assign a value to a property of an object that is read-only.
- Trying to assign a value to a global variable that is being imported with the `readonly` flag.
Question 5: How can I prevent the error “ValueError: assignment destination is read-only” from happening in the future?
Answer: There are a few things you can do to prevent this error from happening in the future. First, you can be careful not to define variables as read-only. Second, you can be careful not to assign values to properties of objects that are read-only. Third, you can be careful not to import global variables with the `readonly` flag.
In this blog post, we discussed the ValueError: assignment destination is read-only error. We first explained what the error means and then provided several common causes of the error. We then discussed how to fix the error in each of the cases we presented. Finally, we provided some tips for avoiding the error in the future.
We hope that this blog post has been helpful in understanding the ValueError: assignment destination is read-only error. If you have any other questions about the error, please feel free to leave a comment below.
Author Profile
Latest entries
- December 26, 2023 Error Fixing User: Anonymous is not authorized to perform: execute-api:invoke on resource: How to fix this error
- December 26, 2023 How To Guides Valid Intents Must Be Provided for the Client: Why It’s Important and How to Do It
- December 26, 2023 Error Fixing How to Fix the The Root Filesystem Requires a Manual fsck Error
- December 26, 2023 Troubleshooting How to Fix the `sed unterminated s` Command
Similar Posts
5 ways to fix the jinja2 importerror: cannot import name ‘escape’.
Cannot import name ‘escape’ from ‘jinja2’ Jinja2 is a popular Python template engine that is used to create dynamic web pages. However, sometimes you may encounter an error message that says “cannot import name ‘escape’ from ‘jinja2′”. This error can occur for a variety of reasons, but it is usually due to a missing or…
AttributeError: module ‘collections’ has no attribute ‘mutableset’
AttributeError: module ‘collections’ has no attribute ‘mutableset’ Have you ever tried to use the `mutableset` object in Python, only to get an `AttributeError`? If so, you’re not alone. This error is a common one, and it can be caused by a variety of reasons. In this article, we’ll take a look at what the `mutableset`…
USB Core NoBackendError: No Backend Available
USB Core NoBackendError: What It Is and How to Fix It The USB core nobackenderror is a common error that can occur when you try to connect a USB device to your computer. This error can have a variety of causes, but it is usually due to a problem with the USB driver or the…
Raspberry Pi VNC: How to Fix the Cannot Currently Show the Desktop Error
Raspberry Pi VNC Cannot Currently Show the Desktop The Raspberry Pi is a popular single-board computer that is used for a variety of projects, from robotics to home automation. One of the most common uses for the Raspberry Pi is as a media center, and many people use VNC to remotely access their Pi from…
TypeError: window.matchMedia is not a function
Have you ever encountered the error “TypeError: window.matchMedia is not a function”? If so, you’re not alone. This is a common error that can occur when you’re trying to use the `matchMedia` function in JavaScript. In this article, we’ll take a look at what the `matchMedia` function is and how to use it correctly. We’ll…
Version glibcxx_3.4.30 not found: How to fix this error
null Column 1 Column 2 Column 3 Version glibcxx_3.4.30 Not found Description The specified version of glibcxx is not found. Solution Install the required version of glibcxx. What are the causes of the error `version glibcxx_3.4.30′ not found`? There are a few possible causes of the error `version glibcxx_3.4.30′ not found`: The GLibCXX library is…
Interoperability with NumPy #
NumPy’s ndarray objects provide both a high-level API for operations on array-structured data and a concrete implementation of the API based on strided in-RAM storage . While this API is powerful and fairly general, its concrete implementation has limitations. As datasets grow and NumPy becomes used in a variety of new environments and architectures, there are cases where the strided in-RAM storage strategy is inappropriate, which has caused different libraries to reimplement this API for their own uses. This includes GPU arrays ( CuPy ), Sparse arrays ( scipy.sparse , PyData/Sparse ) and parallel arrays ( Dask arrays) as well as various NumPy-like implementations in deep learning frameworks, like TensorFlow and PyTorch . Similarly, there are many projects that build on top of the NumPy API for labeled and indexed arrays ( XArray ), automatic differentiation ( JAX ), masked arrays ( numpy.ma ), physical units ( astropy.units , pint , unyt ), among others that add additional functionality on top of the NumPy API.
Yet, users still want to work with these arrays using the familiar NumPy API and reuse existing code with minimal (ideally zero) porting overhead. With this goal in mind, various protocols are defined for implementations of multi-dimensional arrays with high-level APIs matching NumPy.
Broadly speaking, there are three groups of features used for interoperability with NumPy:
Methods of turning a foreign object into an ndarray;
Methods of deferring execution from a NumPy function to another array library;
Methods that use NumPy functions and return an instance of a foreign object.
We describe these features below.
1. Using arbitrary objects in NumPy #
The first set of interoperability features from the NumPy API allows foreign objects to be treated as NumPy arrays whenever possible. When NumPy functions encounter a foreign object, they will try (in order):
The buffer protocol, described in the Python C-API documentation .
The __array_interface__ protocol, described in this page . A precursor to Python’s buffer protocol, it defines a way to access the contents of a NumPy array from other C extensions.
The __array__() method, which asks an arbitrary object to convert itself into an array.
For both the buffer and the __array_interface__ protocols, the object describes its memory layout and NumPy does everything else (zero-copy if possible). If that’s not possible, the object itself is responsible for returning a ndarray from __array__() .
DLPack is yet another protocol to convert foreign objects to NumPy arrays in a language and device agnostic manner. NumPy doesn’t implicitly convert objects to ndarrays using DLPack. It provides the function numpy.from_dlpack that accepts any object implementing the __dlpack__ method and outputs a NumPy ndarray (which is generally a view of the input object’s data buffer). The Python Specification for DLPack page explains the __dlpack__ protocol in detail.
The array interface protocol #
The array interface protocol defines a way for array-like objects to reuse each other’s data buffers. Its implementation relies on the existence of the following attributes or methods:
__array_interface__ : a Python dictionary containing the shape, the element type, and optionally, the data buffer address and the strides of an array-like object;
__array__() : a method returning the NumPy ndarray copy or a view of an array-like object;
The __array_interface__ attribute can be inspected directly:
The __array_interface__ attribute can also be used to manipulate the object data in place:
We can check that arr and new_arr share the same data buffer:
The __array__() method #
The __array__() method ensures that any NumPy-like object (an array, any object exposing the array interface, an object whose __array__() method returns an array or any nested sequence) that implements it can be used as a NumPy array. If possible, this will mean using __array__() to create a NumPy ndarray view of the array-like object. Otherwise, this copies the data into a new ndarray object. This is not optimal, as coercing arrays into ndarrays may cause performance problems or create the need for copies and loss of metadata, as the original object and any attributes/behavior it may have had, is lost.
The signature of the method should be __array__(self, dtype=None, copy=None) . If a passed dtype isn’t None and different than the object’s data type, a casting should happen to a specified type. If copy is None , a copy should be made only if dtype argument enforces it. For copy=True , a copy should always be made, where copy=False should raise an exception if a copy is needed.
If a class implements the old signature __array__(self) , for np.array(a) a warning will be raised saying that dtype and copy arguments are missing.
To see an example of a custom array implementation including the use of __array__() , see Writing custom array containers .
The DLPack Protocol #
The DLPack protocol defines a memory-layout of strided n-dimensional array objects. It offers the following syntax for data exchange:
A numpy.from_dlpack function, which accepts (array) objects with a __dlpack__ method and uses that method to construct a new array containing the data from x .
__dlpack__(self, stream=None) and __dlpack_device__ methods on the array object, which will be called from within from_dlpack , to query what device the array is on (may be needed to pass in the correct stream, e.g. in the case of multiple GPUs) and to access the data.
Unlike the buffer protocol, DLPack allows exchanging arrays containing data on devices other than the CPU (e.g. Vulkan or GPU). Since NumPy only supports CPU, it can only convert objects whose data exists on the CPU. But other libraries, like PyTorch and CuPy , may exchange data on GPU using this protocol.
2. Operating on foreign objects without converting #
A second set of methods defined by the NumPy API allows us to defer the execution from a NumPy function to another array library.
Consider the following function.
Note that np.exp is a ufunc , which means that it operates on ndarrays in an element-by-element fashion. On the other hand, np.mean operates along one of the array’s axes.
We can apply f to a NumPy ndarray object directly:
We would like this function to work equally well with any NumPy-like array object.
NumPy allows a class to indicate that it would like to handle computations in a custom-defined way through the following interfaces:
__array_ufunc__ : allows third-party objects to support and override ufuncs .
__array_function__ : a catch-all for NumPy functionality that is not covered by the __array_ufunc__ protocol for universal functions.
As long as foreign objects implement the __array_ufunc__ or __array_function__ protocols, it is possible to operate on them without the need for explicit conversion.
The __array_ufunc__ protocol #
A universal function (or ufunc for short) is a “vectorized” wrapper for a function that takes a fixed number of specific inputs and produces a fixed number of specific outputs. The output of the ufunc (and its methods) is not necessarily a ndarray, if not all input arguments are ndarrays. Indeed, if any input defines an __array_ufunc__ method, control will be passed completely to that function, i.e., the ufunc is overridden. The __array_ufunc__ method defined on that (non-ndarray) object has access to the NumPy ufunc. Because ufuncs have a well-defined structure, the foreign __array_ufunc__ method may rely on ufunc attributes like .at() , .reduce() , and others.
A subclass can override what happens when executing NumPy ufuncs on it by overriding the default ndarray.__array_ufunc__ method. This method is executed instead of the ufunc and should return either the result of the operation, or NotImplemented if the operation requested is not implemented.
The __array_function__ protocol #
To achieve enough coverage of the NumPy API to support downstream projects, there is a need to go beyond __array_ufunc__ and implement a protocol that allows arguments of a NumPy function to take control and divert execution to another function (for example, a GPU or parallel implementation) in a way that is safe and consistent across projects.
The semantics of __array_function__ are very similar to __array_ufunc__ , except the operation is specified by an arbitrary callable object rather than a ufunc instance and method. For more details, see NEP 18 — A dispatch mechanism for NumPy’s high level array functions .
3. Returning foreign objects #
A third type of feature set is meant to use the NumPy function implementation and then convert the return value back into an instance of the foreign object. The __array_finalize__ and __array_wrap__ methods act behind the scenes to ensure that the return type of a NumPy function can be specified as needed.
The __array_finalize__ method is the mechanism that NumPy provides to allow subclasses to handle the various ways that new instances get created. This method is called whenever the system internally allocates a new array from an object which is a subclass (subtype) of the ndarray. It can be used to change attributes after construction, or to update meta-information from the “parent.”
The __array_wrap__ method “wraps up the action” in the sense of allowing any object (such as user-defined functions) to set the type of its return value and update attributes and metadata. This can be seen as the opposite of the __array__ method. At the end of every object that implements __array_wrap__ , this method is called on the input object with the highest array priority , or the output object if one was specified. The __array_priority__ attribute is used to determine what type of object to return in situations where there is more than one possibility for the Python type of the returned object. For example, subclasses may opt to use this method to transform the output array into an instance of the subclass and update metadata before returning the array to the user.
For more information on these methods, see Subclassing ndarray and Specific features of ndarray sub-typing .
Interoperability examples #
Example: pandas series objects #.
Consider the following:
Now, ser is not a ndarray, but because it implements the __array_ufunc__ protocol , we can apply ufuncs to it as if it were a ndarray:
We can even do operations with other ndarrays:
Example: PyTorch tensors #
PyTorch is an optimized tensor library for deep learning using GPUs and CPUs. PyTorch arrays are commonly called tensors . Tensors are similar to NumPy’s ndarrays, except that tensors can run on GPUs or other hardware accelerators. In fact, tensors and NumPy arrays can often share the same underlying memory, eliminating the need to copy data.
Note that x_np and x_tensor are different kinds of objects:
However, we can treat PyTorch tensors as NumPy arrays without the need for explicit conversion:
Also, note that the return type of this function is compatible with the initial data type.
While this mixing of ndarrays and tensors may be convenient, it is not recommended. It will not work for non-CPU tensors, and will have unexpected behavior in corner cases. Users should prefer explicitly converting the ndarray to a tensor.
PyTorch does not implement __array_function__ or __array_ufunc__ . Under the hood, the Tensor.__array__() method returns a NumPy ndarray as a view of the tensor data buffer. See this issue and the __torch_function__ implementation for details.
Note also that we can see __array_wrap__ in action here, even though torch.Tensor is not a subclass of ndarray:
PyTorch implements __array_wrap__ to be able to get tensors back from NumPy functions, and we can modify it directly to control which type of objects are returned from these functions.
Example: CuPy arrays #
CuPy is a NumPy/SciPy-compatible array library for GPU-accelerated computing with Python. CuPy implements a subset of the NumPy interface by implementing cupy.ndarray , a counterpart to NumPy ndarrays .
The cupy.ndarray object implements the __array_ufunc__ interface. This enables NumPy ufuncs to be applied to CuPy arrays (this will defer operation to the matching CuPy CUDA/ROCm implementation of the ufunc):
Note that the return type of these operations is still consistent with the initial type:
See this page in the CuPy documentation for details .
cupy.ndarray also implements the __array_function__ interface, meaning it is possible to do operations such as
CuPy implements many NumPy functions on cupy.ndarray objects, but not all. See the CuPy documentation for details.
Example: Dask arrays #
Dask is a flexible library for parallel computing in Python. Dask Array implements a subset of the NumPy ndarray interface using blocked algorithms, cutting up the large array into many small arrays. This allows computations on larger-than-memory arrays using multiple cores.
Dask supports __array__() and __array_ufunc__ .
Dask is lazily evaluated, and the result from a computation isn’t computed until you ask for it by invoking compute() .
See the Dask array documentation and the scope of Dask arrays interoperability with NumPy arrays for details.
Example: DLPack #
Several Python data science libraries implement the __dlpack__ protocol. Among them are PyTorch and CuPy . A full list of libraries that implement this protocol can be found on this page of DLPack documentation .
Convert a PyTorch CPU tensor to NumPy array:
The imported arrays are read-only so writing or operating in-place will fail:
A copy must be created in order to operate on the imported arrays in-place, but will mean duplicating the memory. Do not do this for very large arrays:
Note that GPU tensors can’t be converted to NumPy arrays since NumPy doesn’t support GPU devices:
But, if both libraries support the device the data buffer is on, it is possible to use the __dlpack__ protocol (e.g. PyTorch and CuPy ):
Similarly, a NumPy array can be converted to a PyTorch tensor:
Read-only arrays cannot be exported:
Further reading #
The array interface protocol
Writing custom array containers
Special attributes and methods (details on the __array_ufunc__ and __array_function__ protocols)
Subclassing ndarray (details on the __array_wrap__ and __array_finalize__ methods)
Specific features of ndarray sub-typing (more details on the implementation of __array_finalize__ , __array_wrap__ and __array_priority__ )
NumPy roadmap: interoperability
PyTorch documentation on the Bridge with NumPy
NumPy: Make arrays immutable (read-only) with the WRITEABLE attribute
The NumPy array ( numpy.ndarray ) is mutable by default, which means you can update the values of its elements. By changing the settings of numpy.ndarray , you can make it immutable (read-only).
Making an array immutable can be useful for preventing accidental value updates.
This article covers the following topics.
The flags attribute stores memory layout information of ndarray
Make the ndarray immutable (read-only) with the writeable attribute, situations where the writeable attribute cannot be changed.
Keep in mind that if the original array is writable, you can still update the element values from the original array even if you make its view read-only, as discussed later.
The memory layout information of numpy.ndarray is stored in the flags attribute.
- numpy.ndarray.flags — NumPy v1.24 Manual
The flags attribute returns an object of type numpy.flagsobj . You can access its attribute values using either the .attribute_name (lowercase) or ['ATTRIBUTE_NAME'] (uppercase) notation.
You can make the ndarray immutable (read-only) with the WRITEABLE attribute.
When you create a new numpy.ndarray , the WRITEABLE attribute is set to True by default, allowing you to update its values.
By setting the WRITEABLE attribute to False , the array becomes read-only, and attempting to update its values will result in an error.
You can change the WRITEABLE attribute using either .writeable or ['WRITEABLE'] , or you can alternatively change the setting with the setflags() method. In setflags() , the write argument corresponds to the WRITEABLE attribute.
- numpy.ndarray.setflags — NumPy v1.24 Manual
The WRITEABLE attribute isn't always changeable.
For example, when you create a view of a numpy.ndarray array with a slice, if the original array is read-only ( WRITEABLE is False ), the view will also be read-only.
If the original array is read-only, you cannot change the WRITEABLE attribute of the view to True .
Even if you set the WRITEABLE attribute of the original array to True , the WRITEABLE attribute of the view remains False , but it becomes changeable to True .
If the WRITEABLE attribute of the original array is True , you can update the values from the original array even when the WRITEABLE attribute of the view is False .
In the case of a copy, a new array is created, so you can set the WRITEABLE attribute independently of the original array.
To determine whether an ndarray is a view or a copy and if it shares memory, refer to the following article:
- NumPy: Determine if ndarray is view or copy and if it shares memory
Related Categories
Related articles.
- Convert between pandas DataFrame/Series and NumPy array
- NumPy: Broadcasting rules and examples
- numpy.where(): Manipulate elements depending on conditions
- NumPy: Extract or delete elements, rows, and columns that satisfy the conditions
- NumPy: Add new dimensions to an array (np.newaxis, np.expand_dims)
- NumPy: Split an array with np.split, np.vsplit, np.hsplit, etc.
- Get image size (width, height) with Python, OpenCV, Pillow (PIL)
- NumPy: Create an array with the same value (np.zeros, np.ones, np.full)
- NumPy: squeeze() to remove dimensions of size 1 from an array
- NumPy: Rotate array (np.rot90)
- Matrix operations with NumPy in Python
- NumPy: Save and load arrays in npy and npz files
- Convert 1D array to 2D array in Python (numpy.ndarray, list)
- Binarize image with Python, NumPy, OpenCV
- How to fix "ValueError: The truth value ... is ambiguous" in NumPy, pandas
Navigation Menu
Search code, repositories, users, issues, pull requests..., provide feedback.
We read every piece of feedback, and take your input very seriously.
Saved searches
Use saved searches to filter your results more quickly.
To see all available qualifiers, see our documentation .
- Notifications You must be signed in to change notification settings
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement . We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
[ray] numpy arrays become read-only, and no copy on write (after ray.get()) #5592
seb314 commented Aug 30, 2019
- 👍 1 reaction
- 👀 1 reaction
richardliaw commented Sep 2, 2019
Sorry, something went wrong.
pcmoritz commented Sep 2, 2019
Seb314 commented sep 2, 2019 • edited loading.
brukau commented Jan 31, 2020
stale bot commented Nov 14, 2020
stale bot commented Nov 28, 2020
No branches or pull requests
IMAGES
VIDEO