Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

More pythonic way for exceptions? [closed]

I have a method that must return one of three objects depending on their existence.

My implementation

try:
    return Model.objects.get(param=param)
except Model.DoesNotExist as ex:
    # go to the next verification
    pass

try:
    return RelatedModel.objects.get(param=param).model
except RelatedMolel.DoesNotExist as ex:
    # get the default model
    pass

return Model.objects.get_default()

So question for the guru of python - is it a more pythonic implementation than inner try/catch blocks or ?

try:
    return Model.objects.get(param=param)
except Model.DoesNotExist as ex:

    try:
        return RelatedModel.objects.get(param=param).model
    except RelatedModel.DoesNotExist as ex:

        return Model.objects.get_default()
like image 969
erthalion Avatar asked Feb 14 '23 02:02

erthalion


2 Answers

From the Zen of Python (import this):

Flat is better than nested.

I would prefer the first version in this case.

like image 114
jonrsharpe Avatar answered Feb 17 '23 21:02

jonrsharpe


The docs tell us:

ObjectDoesNotExist is defined in django.core.exceptions. DoesNotExist is a subclass of the base ObjectDoesNotExist exception that is provided on every model class as a way of identifying the specific type of object that could not be found.

So what I'd do is:

queries = [lambda: Model.objects.get(param=param),
             lambda: RelatedModel.objects.get(param=param).model,
             lambda: Model.objects.get_default()]

for query in queries:
    try:
        return query()
    except ObjectDoesNotExist:
        pass

Arguably this way isn't "obvious", but it's both flat, reduces redundancy, and keeps related things together.

like image 24
millimoose Avatar answered Feb 17 '23 19:02

millimoose