Question

I'm writing some scripts that will be used by non-python users. I have a Config class that has dictionaries and I'd like to be able to raise a custom exception for KeyError. Is there an elegant way to do this other than writing a method that raises an exception when checking for the value in the dictionary?

Here's an example:

class ConfigError(Exception): pass

class Config:
    def __init__(self):
        self.cars = {'BMW': 'M5', 'Honda': 'Civic'}

    def get_car(self, name):
        try:
            return self.cars[name]
        except KeyError, e:
            raise ConfigError("Car %s doesn't exist!!!" % name)

conf = Config()
print 'Car: %s' % conf.cars['BMW']
print 'Car: %s' % conf.cars['Mercedes']

Here's the output:

Car: M5 
Traceback (most recent call last):
  File "test.py", line 17, in ?
    print 'Car: %s ' % conf.cars['Mercedes']
KeyError: 'Mercedes'

I know I can write a method like Config.get_car() above and raise a custom exception, but I'd like to be able to raise the custom exception when directly trying to access the Config.cars dictionary. I'd like to do so because there's actually more dictionaries in the config, but I only need to raise a custom exception for one of the dictionaries and would like to keep how the data is access consistent (all as dictionaries).

Note: This is using Python 2.4.4

Était-ce utile?

La solution

Consider doing this.

class MyConfigDict( dict ):
    def __getitem__( self, key ):
        try:
            return super( MyConfigDict, self ).__getitem__( key )
        except KeyError as e:
            raise MyConfigError( e.message )

Something like that may allow you to wrap every access in your own extended exception.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top