Using a bytearray datatype to store a password (in memory) has an advantage over using a string datatype for a password in that a bytearray is mutable and can be overwritten with 0x00 values when the password is no longer needed for processing and until the password variable is garbage collected. It's not clear to me, however, whether overwriting 0x00 values will achieve what is intended. When a password is no longer needed, it should be wiped from memory, prior to GC. Is this possible in python 3.4 using bytearray?


2 Answers 2


At least using CPython, overwriting a bytearray is the way forward. Like most systems, CPython does not clear memory prior to garbage collection, so a manual erase is required. It also does not make copies of data unless specifically requested.

Be wary of other Python implementations, however. They often differ in specifics of how memory is managed and may, for example, use either a copying or compacting garbage collector. In such a case, manually erasing the password may not be enough, as the garbage collector may have moved the object reference, leaving behind a copy of the array's contents at the old location.

  • 1
    IronPython uses the .net GC, which moves objects around when in compacts, it's an example for an implementation where not-erasing might be unsafe (I didn't actually test this, perhaps the GC immediately wipes the freed memory in preparation for handing it out again). Jan 22, 2016 at 11:27

Erasing content in a mutable bytearray is doable. However, depending on your usage, the downstream function which consumes a password may expect only a string, not a bytearray. In that case, you are stuck with using string, and there won't be a real way to erase the password in string.

See also discussions about erasing password in Python string in this Q&A.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.