Search code examples
pythondjangodjango-authentication

Why django hashers are using assert?


I have a question regarding Django implementation of hashers. All of them implement verify method and are doing assert algorithm == self.algorithm.

I know that assertions can be disabled through passing the flag -O to the Python interpreter on production code.

For example, BCryptSHA256PasswordHasher implements verify like that:

def verify(self, password, encoded):
    algorithm, salt, hash = encoded.split('$', 2)
    assert algorithm == self.algorithm
    encoded_2 = self.encode(password, salt)
    return constant_time_compare(encoded, encoded_2)

Is assert statement is meant to be used only during the development phase? Or there are other reasons?


Solution

  • Over the years, I've grown to add asserts in my code as well, similar to this.

    When used like this, having your code raise an AssertionError instead of some side-effect error resulting in the expected condition not being met can help speedup debugging.

    Personally, I don't see a problem with these asserts going into production, but that's a choice to make based on the individual use-case, and how your code is being used, maintained, etc.