Search code examples
pythonintrospectionpraw

Seeking a better way to check an instance property and assign value depending on property type


I'm working with the praw module, and I find that my objects sometimes have a property subreddit that is sometimes a string and that is sometimes an object with its own properties. I've dealt with it using the following:

for c in comments:
    if isinstance(c.subreddit, str):
        subreddit_name = c.subreddit
    else:
        subreddit_name =  c.subreddit.display_name

I have two functions where I have to do this, and it's really ugly. Is there a better way to deal with this?


Solution

  • I would use EAFP rather than LBYL:

    for c in comments:
        try:
             subreddit_name =  c.subreddit.display_name
        except AttributeError:
            subreddit_name = c.subreddit
    

    You could also try getattr, which takes a default like dict.get:

    subreddit_name = getattr(c.subreddit, 'display_name', c.subreddit)
    

    This is effectively a neater version of:

    subreddit_name = (c.subreddit.display_name 
                      if hasattr(c.subreddit, 'display_name') 
                      else c.subreddit)