Python TutorialGetting Started with PythonPython Basic SyntaxPython DatatypesPython IndentationPython Collection TypesPython Basic Input and OutputPython Built in Modules and FunctionsPython FunctionsChemPy - python packageCreating Python packagesFunctional Programming in PythonIncompatibilities moving from Python 2 to Python 3IoT Programming with Python and Raspberry PIKivy - Cross-platform Python Framework for NUI DevelopmentMutable vs Immutable (and Hashable) in PythonPyInstaller - Distributing Python CodePython *args and **kwargsPython 2to3 toolPython Abstract Base Classes (abc)Python Abstract syntax treePython Alternatives to switch statement from other languagesPython and ExcelPython Anti-PatternsPython ArcPyPython ArraysPython Asyncio ModulePython Attribute AccessPython AudioPython Binary DataPython Bitwise OperatorsPython Boolean OperatorsPython Checking Path Existence and PermissionsPython ClassesPython CLI subcommands with precise help outputPython Code blocks, execution frames, and namespacesPython Collections modulePython Comments and DocumentationPython Common PitfallsPython Commonwealth ExceptionsPython ComparisonsPython Complex mathPython concurrencyPython ConditionalsPython configparserPython Context Managers (with Statement)Python Copying dataPython CountingPython ctypesPython Data SerializationPython Data TypesPython Database AccessPython Date and TimePython Date FormattingPython DebuggingPython DecoratorsPython Defining functions with list argumentsPython DeploymentPython Deque ModulePython DescriptorPython Design PatternsPython DictionaryPython Difference between Module and PackagePython DistributionPython DjangoPython Dynamic code execution with `exec` and `eval`Python EnumPython ExceptionsPython ExponentiationPython Files & Folders I/OPython FilterPython FlaskPython Functools ModulePython Garbage CollectionPython GeneratorsPython getting start with GZipPython graph-toolPython groupby()Python hashlibPython HeapqPython Hidden FeaturesPython HTML ParsingPython HTTP ServerPython IdiomsPython ijsonPython Immutable datatypes(int, float, str, tuple and frozensets)Python Importing modulesPython Indexing and SlicingPython Input, Subset and Output External Data Files using PandasPython Introduction to RabbitMQ using AMQPStorm

Python Idioms

From WikiOD

Dictionary key initializations[edit | edit source]

Prefer 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 KeyError exception.

Rather than doing

def add_student():
        students['count'] += 1
    except KeyError:
        students['count'] = 1


def add_student():
        students['count'] = students.get('count', 0) + 1

Switching variables[edit | edit source]

To switch the value of two variables you can use tuple unpacking.

x = True 
y = False 
x, y = y, x 
# False 
# True

Use truth value testing[edit | edit source]

Python will implicitly convert any object to a Boolean value for testing, so use it wherever possible.

# Good examples, using implicit truth testing
if attr:
    # do something

if not attr:
    # do something

# Bad examples, using specific types
if attr == 1:
    # do something

if attr == True:
    # do something

if attr != '':
    # do something

# If you are looking to specifically check for None, use 'is' or 'is not'
if attr is None:
    # do something

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 False.

Test for "__main__" to avoid unexpected code execution[edit | edit source]

It is good practice to test the calling program's __name__ variable before executing your code.

import sys

def main():
    # Your code starts here

    # Don't forget to provide a return code
    return 0

if __name__ == "__main__":

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:

# A new program file
import my_program        # main() is not run

# But you can run main() explicitly if you really want it to run: