0

My Django codebase has foreign key references that are a few objects deep and it feels like a code smell to have to check for truthiness at each level.

Is there a way to check for this kind of thing in a more pythonic way with less boilerplate?

Take this simplified example:

if page.banner.image:
    # ...

If page.banner is optional and it doesn't exist it will return None and throw an exception saying, rightly, that NoneType doesn't have an image attribute.

The obvious fix is

if page.banner and page.banner.image:
    # ...

But this will get repetitive and verbose. I suppose you could use getattr() to do something like I'm after but it's even uglier:

if getattr(getattr(page, 'banner', None), 'image', None):
    # ...

Is there a concise way to do this without all these conditional clauses?

jonathanpglick
  • 306
  • 2
  • 11

1 Answers1

3

Python recommends the easier to ask for forgiveness than permission approach.

try:
    new_var = page.banner.image
except AttributeError:
    ....

There is some good discussion about asking permission vs forgiveness here.

Stuart Dines
  • 748
  • 6
  • 12