Have exception hit two except blocks in python -
here example of want in code:
class myclass(object): @classmethod def test_func(cls, x): try: return cls.cache[x] except attributeerror: cls.cache = {} except (attributeerror, keyerror): cls.cache[x] = "cache store" return cls.cache[x]
the idea here being class cache results based on input x
. don't want start creating cache until it's needed. first time pass x
this, want create cache, , fill something. there way make hit both except
blocks? right hits first
as suggested in comment, make cache
class attribute when create class. unless have really reason not to, you're needlessly complicating implementation
class myclass(object): cache = {} @classmethod def test_func(cls, x): try: return cls.cache[x] except keyerror: cls.cache[x] = "cache store" return cls.cache[x]
once that, don't need try
statement; can use setdefault
.
@classmethod def test_func(cls, x): return cls.cache.setdefault(x, "cache store")
Comments
Post a Comment