Pylint - Too many boolean expressions in if statement

2

Good afternoon I have the following code snippet:

content_view = cleaned_data.get('content_view')
show_content = cleaned_data.get('show_content')
show_children = cleaned_data.get('show_children')

footer_title_1 = cleaned_data.get('footer_title_1')
footer_link_1 = cleaned_data.get('footer_link_1')
footer_image_1 = cleaned_data.get('footer_image_1')
footer_title_2 = cleaned_data.get('footer_title_2')
footer_link_2 = cleaned_data.get('footer_link_2')
footer_image_2 = cleaned_data.get('footer_image_2')
footer_title_3 = cleaned_data.get('footer_title_3')
footer_link_3 = cleaned_data.get('footer_link_3')
footer_image_3 = cleaned_data.get('footer_image_3')

if not self.object and not parent:
    msg = u'No se puede crear páginas del primer nivel.'
    self.add_error('parent', msg)

if not image and not parent:
    msg = u'La página del primer nivel debe tener una imagen.'
    self.add_error('image', msg)

if show_children and not content_view:
    msg = u'Tiene que elegir la forma de mostrar a los hijos.'
    self.add_error('content_view', msg)

if not show_children and not show_content:
    msg = u'Tiene que elegir qué mostrar en la página: ' \
          u'el contenigo, los hijos o ambos.'
    self.add_error('show_content', msg)

if (
    footer_title_1 or footer_link_1 or footer_image_1 or
    footer_title_2 or footer_link_2 or footer_image_2 or
    footer_title_3 or footer_link_3 or footer_image_3
) and not (
    footer_title_1 and footer_link_1 and footer_image_1 and
    footer_title_2 and footer_link_2 and footer_image_2 and
    footer_title_3 and footer_link_3 and footer_image_3
):
    msg = u'Tiene que completar todos los campos \
          de los bloques inferiores de la página.'
    self.add_error(None, msg)

I would like to know in what way I could refactor it? since pylint throws me alert for having more than 5 conditions.

    
asked by Felipe Zuluaga 03.05.2016 в 00:13
source

1 answer

2

As @toledano says, it is best to take advantage of django's facilities to control the form.

But to answer your question, it is possible to reduce the chain of checks using the functions all and any leaving much more readable :

footers = [footer_title_1, footer_link_1, footer_image_1,
           footer_title_2, footer_link_2, footer_image_2,
           footer_title_3, footer_link_3, footer_image_3 ]

if any(footers) and not all(footers):
   ...

You can still do better to avoid having to check each item twice:

if len(footers) > sum(1 for f in footers if f) >= 1:
   ...
    
answered by 09.05.2016 / 12:40
source