pythonpython-3.xclasspython-bytearray

bytearray.reverse() not working within a class, is working when called on object


I have a class where in the initialization I set one member to a bytearray, and then another to its reverse by using the bytearray.reverse() function.

When I instantiate the class, the "reversed" array is not reversed. If I then call reverse on the member after instantiation, it reverses fine. What is happening? class and ipython output is below

class Cipher():
  def __init__(self, key=bytearray(b'abc123y;')):
    self.setKeys(key)

  def setKeys(self, key):
    if isinstance(key, bytearray) and len(key) >= 8:
      self.encrKey = key[:8]
      self.decrKey = self.encrKey
      self.decrKey.reverse()
      print("Encrypt: ", self.encrKey)
      print("Decrypt: ", self.decrKey)
      return True
    else:
      return False

In [13]: cipher = Cipher()
Encrypt:  bytearray(b';y321cba')
Encrypt:  bytearray(b';y321cba')

In [14]: cipher.decrKey.reverse()

In [15]: cipher.decrKey
Out[15]: bytearray(b'abc123y;')

Solution

  • You are acting on the same reference when you call .reverse on self.decrKey because you previously made the assignment:

    self.decrKey = self.encrKey
    

    As a result, you're reversing both encrKey and decrKey. Instead, copy decrKey with [:] and then call .reverse:

    self.encrKey = key[:8]
    self.decrKey = self.encrKey[:]
    self.decrKey.reverse()