Category Archives: python

python: ‘for’ or ‘while’ loop with ‘else’ statement (‘try’ statement too)

in python, ‘for’ and ‘while’ statements have an optional ‘else’ clause which gets executed when the testing condition becomes false. The ‘break’ statement will get you out of the loop without executing ‘else’ clause ‘Try’ statement can have an optional ‘else’ clause too which gets executed when no exception was raise. You cannot have an ‘else’ statement if your ‘try’ block has no ‘except’ statement. [source] http://docs.python.org/ref/while.html http://docs.python.org/ref/for.html http://docs.python.org/ref/try.html http://docs.python.org/ref/break.html explain ‘break’ rule regarding ‘else’ statement

python ‘return’ statement within try … finally

When exectuting ‘return’ in code defined within a try,catch,finally statement, it’s good to know that ‘finally’ code gets executed prior to returning the value => indeed, finally really gets executed whatever happens (i.e. an exception being generated or not) [source] http://docs.python.org/ref/return.html

python “exec” statement

“exec” statement is pretty interesting in python since you can pass dictonaries to be used as global and local namespaces respectively [source] http://docs.python.org/ref/exec.html

unexpected static class properties

Python does not have any “static” keyword to use as it is in php or java. Thing is you can create static class properties and might not even know it, leading to tricky bugs to spot!! If you have any doubt, call ‘id()’ builtin function which return the memory address of passed variable. If you define a class such as: class myclass: prop1 = [] prop2 = ” def __init__(self): self.prop3 = [] Well, in the above class, prop1 is static while prop2 and prop3 are not! Remember that lists, dictionaries and objects are always passed by reference in python […]

memory address in python

to print the memory address of a given var, call builtin ‘id()’ function: id(myvar) This is pretty useful for debugging since python pass list and dictionaries by reference