B Python at DHSC

The following are the DHSC sensible defaults for Python:

B.1 Version & IDE

Use Python 3 via Jupyter Notebooks or VSCode

B.2 Default Packages and Add Ins

B.3 General

  • Use pandas for data analysis and reshaping
    • Use loc and iloc to index into data frames
  • Use Altair for basic data visualisation
  • Use Scikit Learn for machine learning
  • Use SQLAlchemy and pandas for database interactions, rather than writing your own SQL

B.4 Packages

Recommended Packages:

Note: This list is under development - If you have a package you would like to suggest / remove please submit an issue.

B.5 Project Workflow

Python has many different options, all supported by different IDEs and tools:

B.6 Packaging Your Code

Python - Packaging Projects

B.7 Managing Dependencies

Virtual Environments venv

B.8 Error Handling

In Python, an error can be a syntax error or an exception. Exceptions will crash your program as they are encountered. Fortunately, Python has a method for dealing with exception errors: the try-except block.

The try-except block is used to catch and handle exceptions. Python executes code following the try statement as a “normal” part of the program. The code that follows the except statement is the program’s response to any exceptions in the preceding try clause. For example,

try: 
    print(0/0)
except:
    print ("Cannot divide by O!" ) 
Cannot divide by O! 

It is also possible to write programs that handle selected exceptions (and this is generally considered good practice):

try:
    print(0/0) 
except ZeroDivisionError: 
    print ("Cannot divide by O!" ) 
Cannot divide by O! 

And to handle different types of errors:

try:
    print(0/j) 
except ZeroDivisionError: 
    print("Cannot divide by O!") 
except NameError: 
    print("Something else went wrong") 
Something else went wrong 

For more information see python documentation on error handling.

B.9 Unit Testing