Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Have exception hit two except blocks in python

Here is an example of something I want to do 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 my class will cache some results based on an input x. However I don't want to start creating the cache until it's needed. So the first time I pass any x into this, I want it to create the cache, and fill it with something. Is there a way to make it hit both except blocks? Right now it currently only hits the first

like image 719
sedavidw Avatar asked Sep 21 '25 05:09

sedavidw


2 Answers

As I suggested in a comment, just make cache a class attribute when you create the class. Unless you have a really good reason not to, you're just needlessly complicating your 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 you do that, you don't even need try statement; you can just use setdefault.

@classmethod
def test_func(cls, x):
    return cls.cache.setdefault(x, "CACHE STORE")
like image 170
chepner Avatar answered Sep 22 '25 20:09

chepner


I would go for recursion here:

class MyClass(object):

    @classmethod
    def test_func(cls, x):

        try:
            return cls.cache[x]

        except AttributeError:
            cls.cache = {}
            return cls.test_func(x)  # Add this line

        except KeyError:
            cls.cache[x] = "CACHE STORE"
            return cls.cache[x]
like image 31
Kevin Avatar answered Sep 22 '25 20:09

Kevin