comparison doc/v2_planning/coding_style.txt @ 1150:d7192e52653e

coding_style: Moved some elements to official API
author Olivier Delalleau <delallea@iro>
date Thu, 16 Sep 2010 17:00:58 -0400
parents f6011a2aff0b
children 0904dd74894d
comparison
equal deleted inserted replaced
1148:2da593b0f29d 1150:d7192e52653e
290 Have a sample code that showcases everything one should comply to. 290 Have a sample code that showcases everything one should comply to.
291 291
292 Some coding guidelines (work-in-progress from OD) 292 Some coding guidelines (work-in-progress from OD)
293 ------------------------------------------------- 293 -------------------------------------------------
294 294
295 * Avoid using lists if all you care about is iterating on something. Using
296 lists:
297 - uses more memory (and possibly more CPU if the code may break out of
298 the iteration)
299 - can lead to ugly code when converted to Python 3 with 2to3
300 - can have a different behavior if evaluating elements in the list has
301 side effects (if you want these side effects, make it explicit by
302 assigning the list to some variable before iterating on it)
303
304 Iterative version List version
305 my_dict.iterkeys() my_dict.keys()
306 my_dict.itervalues() my_dict.values()
307 my_dict.iteritems() my_dict.items()
308 itertools.imap map
309 itertools.ifilter filter
310 itertools.izip zip
311 xrange range
312
313 * Use `in` on container objects instead of using class-specific methods.
314 It is easier to read and may allow you to use your code with different
315 container types.
316
317 Yes No
318 --- --
319 key in my_dict my_dict.has_key(key)
320 sub_string in my_string my_string.find(sub_string) >= 0
321
322
323 * Generally prefer list comprehensions to map / filter, as the former are
324 easier to read.
325 Yes:
326 non_comments = [line.strip() for line in my_file.readlines()
327 if not line.startswith('#')]
328 No:
329 non_comments = map(str.strip,
330 filter(lambda line: not line.startswith('#'),
331 my_file.readlines()))
332 295
333 * Use the `key` argument instead of `cmp` when sorting (for Python 3 296 * Use the `key` argument instead of `cmp` when sorting (for Python 3
334 compatibility). 297 compatibility).
335 Yes: 298 Yes:
336 my_list.sort(key=abs) 299 my_list.sort(key=abs)