People often say that Python is an easy language, but like other easy languages it is often harder to make sure you are working in a safe manner. I'm not talking about security, but bug-free.
A) Assert allot:
assert something == True #This must be true because...
assert isinstance(variable, int) #This algorithm only makes sense with intergerspython -O to remove the asserts.
B) Keep your scope clean:
This is why I started this post, if you have a loop your loop variable will be in the loop declaration scope and not inside the loop. It could come in handy if you want to see how far a loop got, but there are also problems. Each assignment in Python is also an implicit definition, which could make a typo problematic:
bestValues = "abcd"
for bestValue in bestValues:
print bestValue
bestValeu = "c"
for i in bestValue:
print i#sockets is a list of sockets
for s in sockets:
s.send("ok, thank you")
del sockets #That's it, close all the sockets
#Reconnect for a new transaction
sockets = [socket("192.168.1.%i" % i) for i in range(255)]del sockets line will not work as expected because the last socket in the list is still alive as the variable "s".
One way to keep this from happening is using del after every loop:
for a in values:
print a
del a
b = [i/2.0 for i in xrange(10)]
del idef formatit(a):
s = "see:"
for i in a:
s += " " + str(i)
del i
return sdel i will raise an error when you call "formatit([])". It is comprehensible result as the loop is not run, so why should i be defined in the first place? But this is where a habit of using del i will not be a good thing, because in this context del i is effectively assert len(a); del i (which can be nice if you actually want that).
This is where I'm not sure what best practice to choose. I think I'm going to have to go with the following solution to keep safe without thinking to much. A good habbit may be: use only a single loop in every scope, if you decide to use multiple then place each in a separate scope using if True:
if True:
for i in something:
print i