Dictionary key initializations
dict.get method if you are not sure if the key is present. It allows you to return a default value if key is not found. The traditional method
dict[key] would raise a
Rather than doing
To switch the value of two variables you can use tuple unpacking.
Test for "__main__" to avoid unexpected code execution
It is good practice to test the calling program's
__name__ variable before executing your code.
Using this pattern ensures that your code is only executed when you expect it to be; for example, when you run your file explicitly:
The benefit, however, comes if you decide to
import your file in another program (for example if you are writing it as part of a library). You can then
import your file, and the
__main__ trap will ensure that no code is executed unexpectedly:
Use truth value testing
Python will implicitly convert any object to a Boolean value for testing, so use it wherever possible.
This generally produces more readable code, and is usually much safer when dealing with unexpected types.
Click here for a list of what will be evaluated to