Sign up ×
Code Review Stack Exchange is a question and answer site for peer programmer code reviews. It's 100% free, no registration required.

I have this code:

    lengths = []
    lengths.append(len(self.download_links))
    lengths.append(len(self.case_names))
    lengths.append(len(self.case_dates))
    lengths.append(len(self.docket_numbers))
    lengths.append(len(self.neutral_citations))
    lengths.append(len(self.precedential_statuses))

Unfortunately, any of those object properties can be None, so I need to check each with either an if not None block or a try/except block. Checking each individually will blow up the size and conciseness of the code.

I assume there must be a better way for this kind of pattern, right?

share|improve this question

2 Answers 2

up vote 5 down vote accepted

Firstly, consider whether these shouldn't be None, but instead should be empty lists. Most of the time None is better replaced by something else like an empty list.

If that's not an option, you can use a list:

for item in [self.download_links, self.case_name...]:
    if item is not None:
         length.append( len(item) )

or a function

def add_length(obj):
   if obj is not None:
            lengths.append(len(obj))

add_length(self.download_links)
add_length(self.case_name)
...
share|improve this answer
    
I think None is better semantically in this case than [], but this will do it, and makes sense, thanks. –  mlissner Feb 24 '12 at 19:50
    
@mlissner: If something could be None or a list I'd say it's a bad design choice. –  Rik Poggi Mar 5 '12 at 12:31

Why not just try some list comprehensions:

chunks = [self.download_links, self.case_name...]
lengths = [len(i) for i in chunks if i is not None]
share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.