I am currently updating my code to comply with PEP8 maximum line length.
I have two questions on what people think is a better style. The first is the init of a class (or any function definition for that matter). Do people just split up all the arguments of a function definition if together the line is to long like this:
def __init__(self,
title,
url,
teaser,
parseDate,
updateDate,
redis,
id=None):
Or would it be considered better to only split thát part to a second line that would otherwise be too long like this:
def __init__(self, title, url, teaser, parseDate, updateDate, redis,
id=None):
And secondly: in long if statements, I don't really find the splitting up of the conditions add mucht to the clarity of the code like this:
if self.redis.exists('article:%s' % self.url)\
and self.redis.hexists('article:%s' % self.url, 'id'):
self.id = self.redis.hget('article:%s' % self.url, 'id')
else:
self.id = self.redis.incr('articleid')
If written like below, the line is definatily too long, but I think here it is clearer that you let the value of self.id depend on a condition. In the previous example, it is less clear to me where the condition ends and the contents of the if block starts.
if self.redis.exists('article:%s' % self.url) and self.redis.hexists('article:%s' % self.url, 'id'):
self.id = self.redis.hget('article:%s' % self.url, 'id')
else:
self.id = self.redis.incr('articleid')
What is from the python PEP8 guidelines point of view considered better code, especially since the guidelines says you should not follow the guideline:
"When applying the guideline would make the code less readable, even for someone who is used to reading code that follows this PEP."
Any advice would be highly appreciated.
For your __init__
function, I would go somewhere in the middle and try to put some parameters on each line, finding a logical place to split the line if possible:
def __init__(self, title, url, teaser,
parseDate, updateDate, redis,
id=None):
You might also consider if there is a way to refactor your code to avoid so many arguments to a single method, or just use **kwargs
, accept the intended parameters and explicitly reject any extras.
For your conditional, take advantage of the implicit line breaking allowed inside parentheses (which is exactly how you can split the parameters to a function across multiple lines). This technique is shown in PEP 8 itself.
if (self.redis.exists('article:%s' % self.url) and
self.redis.hexists('article:%s' % self.url, 'id'):
self.id = self.redis.hget('article:%s' % self.url, 'id')
else:
self.id = self.redis.incr('articled')
In this case, since you construct the key three separate times, you might factor that out into a temporary variable first.
key = 'article:%s' % (self.url,)
if (self.redis.exists(key) and
self.redis.hexists(key, 'id')):
self.id = self.redis.hget(key, 'id')
else:
self.id = self.redis.incr('articled')