Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

hasattr for nested attributes

Tags:

python

I need something like this (pseudocode):

if hasattr(object, 'detail.infotext')

I mean I want to check if object has attribute details and if it has, then if details has a attribute named infotext

I could do it like this:

if hasattr(object, 'detail'):
    if hasattr(object.detail, 'infotext'):
        do something

But one-liners are so much easier to read.

like image 341
Lord_JABA Avatar asked Jan 10 '23 05:01

Lord_JABA


1 Answers

I know this isn't really what you want to do, but it's more pythonic anyway (if you know the names of the attributes you're looking for explicitly):

try:
   do something with object.detail.infotext
except AttributeError:
   do something else
like image 72
Andrew Jaffe Avatar answered Jan 21 '23 21:01

Andrew Jaffe