Code Formatting Best Practices » History » Version 1

Version 1/3 - Next » - Current version
Thomas Hein, 07/21/2017 10:26 AM

Code Formatting Best Practices

Fix Exceptions

Using "except [Exception Name] as [temp_var]" instead of "except [Exception Name], [temp_var]"

Has_Key Removal

Using "[dictionary key] in [dictionary]" instead of "[dictionary].has_key([dictionary key])". Some classes had a has_key method. Make sure that when using "key in my_var", my_var is actually a dictionary. If it's a class, make sure to add a contains method.

Fix Idioms

First, stop using the type module when possible. A few sections down is a table with types()'s and its aliases. Also, use isinstance() when comparing a variable and its type. For example, isinstance(my_list, list).

Fix Not Equal To

Straight forward, use "!=" over "<>"

Fix Number literals

With octal numbers, us an "o" after the first 0.

Fix Types

Again, moving away from the types module. Here is a table of common types and it's aliases,

Type Method Alias (Use This Instead)
types.TypeType type
types.BooleanType bool
types.IntType int
types.LongType long
types.FloatType float
types.TupleType tuple
types.ListType list
types.DictType dict
types.FileType file
types.XRangeType xrange
types.SliceType slice

h2. Fix Comma

Fix Next Call

Use "next(self)" over ""

Fix Raise

Pass a message as an argument instead of using a comma. For example, use "raise RuntimeError(':/')".

Also worth noting that you shouldn't raise a message directly. Define an exception or at least use ValueError and pass a message as the argument.