A naive attempt fails:
import hashlib
class fred(hashlib.sha256):
pass
-> TypeError: Error when calling the metaclass bases
cannot create 'builtin_function_or_method' instances
Well, it turns out that hashlib.sha256 is a callable, not a class. Trying something more creative doesn't work either:
import hashlib
class fred(type(hashlib.sha256())):
pass
f = fred
-> TypeError: cannot create 'fred' instances
Hmmm ...
So how do I do this?
Here is what I really want to achieve:
class shad_256(sha256):
"""Double SHA - sha256(sha256(data).digest())
Less susceptible to length extension attacks than sha256 alone."""
def digest(self):
return sha256(sha256.digest(self)).digest()
def hexdigest(self):
return sha256(sha256.digest(self)).hexdigest()
Basically, I want everything to go away, except when someone requires a result, I want to add an extra step. Is there any reasonable way to do this using __new__some kind of metaclass magic?
, , , , - - . , ( update), .
: :
$ python2.7 -m timeit -n 100 -s 'import test_sha, hashlib' 'test_sha._timehash(hashlib.sha256, 20000, 512)'
100 loops, best of 3: 104 msec per loop
$ python2.7 -m timeit -n 100 -s 'import test_sha, hashlib' 'test_sha._timehash(test_sha.wrapper_shad_256, 20000, 512)'
100 loops, best of 3: 108 msec per loop
$ python2.7 -m timeit -n 100 -s 'import test_sha, hashlib' 'test_sha._timehash(test_sha.getattr_shad_256, 20000, 512)'
100 loops, best of 3: 103 msec per loop