Skip to content
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
28 changes: 27 additions & 1 deletion www/src/Lib/_operator.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
"""Brython-specific.
Only implements _compare_digest because it is used in hmac module."""

def _compare_digest(a, b):
def _compare_digest_impl(a, b):
"""Return 'a == b'.
This function uses an approach designed to prevent
timing analysis, making it appropriate for cryptography.
Expand All @@ -19,6 +19,32 @@ def _compare_digest(a, b):
return a == b
raise TypeError("unsupported operand types")


# CPython exposes `_compare_digest` as a C builtin — assigning it as a class
# attribute (`class T: compare_digest = hmac.compare_digest`) does NOT bind
# to the instance, because builtin functions skip the descriptor protocol.
# A plain `def` is a regular function whose `__get__` binds to the instance,
# so `self.compare_digest(a, b)` ends up calling `_compare_digest(self, a,
# b)` — one extra argument that breaks `test_hmac.HMACCompareDigestTestCase`.
# The wrapper below mimics CPython's no-bind behaviour by implementing a
# `__get__` that returns itself unbound.
class _NonBindingFunction:
"""Behave like a callable but skip method-binding when accessed via
a class instance — mirrors a CPython builtin function's descriptor
behaviour. Used by `_compare_digest` so that
`class T: compare_digest = hmac.compare_digest; T().compare_digest(a, b)`
calls the underlying function with exactly `(a, b)`, not `(self, a, b)`.
"""
def __init__(self, f):
self._f = f
self.__name__ = getattr(f, '__name__', '<unbound>')
def __call__(self, *args, **kwargs):
return self._f(*args, **kwargs)
def __get__(self, obj, owner=None):
return self

_compare_digest = _NonBindingFunction(_compare_digest_impl)

def index(a):
# See https://stackoverflow.com/questions/65551469/operator-index-with-custom-class-instance
# for the reason this implementation is necessary.
Expand Down