Menu

#29 Avoid check repetition an exception raise

New
nobody
None
High
Enhancement
2014-05-28
2014-05-28
No

Change the pattern from if key in the dictionary get value else raise an exception, we could inherit from a dictionary and add a new method: get_or_except

class Dict(dict):
    def __init__(self, *args, **kwargs):
        super(Dict, self).__init__(*args, **kwargs)

    def get_or_except(self, key, exception=None):
        """Try to get the dictionary element or raise an exception.

        ::

            >>> dictionary = Dict(a=1, b=2, c=3)
            >>> dictionary.get_or_except('a', KeyError("Not a valid key!"))
            1
            >>> dictionary.get_or_except('d', KeyError("Not a valid key!"))
            ... # doctest: +ELLIPSIS
            Traceback (most recent call last):
            ...
            KeyError: 'Not a valid key!'

        """
        if key in self:
            return self[key]
        if exception is not None:
            raise exception

For example in init of sosGFfilter if requestObject is an instance of Dict we could substitute the following code:

# ---FeatureOfInterest
if "featureofinterestid" not in requestObject:
    raise SOSException(
        "MissingParameterValue", "FeatureOfInterestId",
        'Parameter "FeatureOfInterestId" '
        'is required with multiplicity 1')
else:
    self.featureOfInterest = get_name_from_urn(
        requestObject["featureofinterestid"], "feature",
        sosConfig)  # one-many ID

with:

self.featureOfInterest = get_name_from_urn(
        requestObject.get_or_except("featureofinterestid",
                                    SOSException(
                                        "MissingParameterValue",
                                        "FeatureOfInterestId",
                                        'Parameter "FeatureOfInterestId" '
                                        'is required with multiplicity 1')), 
        "feature",
        sosConfig)

Discussion


Log in to post a comment.

MongoDB Logo MongoDB