How to make pep8 for long attribute / method chain in Python


When we use 80 lines rules, sometimes we facing some difficult cases like long attributes. Usually this also happen in Django which need nested method chain for calling models. For instance :

1
user_list = User.objects.filter(created__year=2012).order_by(‘user’).values(‘user’).distinct()

We should shorten this long attributes. We should know that blackslash is “evil” in python. But, at this cases we can solve this problem using 3 way :

1. Yes, we using backslash “evil”

1
2
user_list = User.objects.filter(created__year=2012)
           .order_by(‘user’).values(‘user’).distinct()

2. Wrap using ()
We know that “()” works as wrapper in Python. We also make it on chained method like :

1
2
user_list = (User.objects.filter(created__year=2012)
           .order_by(‘user’).values(‘user’).distinct())

3. Store partial and invoke to the next method

1
2
user_list = User.objects.filter(created__year=2012)
user_list = user_list.order_by(‘user’).values(‘user’).distinct()

This is about programmer taste because all of them is valid by Pep8. Then, all depend on your eyes and habit.
For me, I prefer with number 1.

Sometimes evil works nicely! 🙂


Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.