Defining Custom Units in Julia and Python

Erik Engheim
11 min readOct 29, 2017

I’ve been writing code to deal with temperature in different units Celsius, Kelvin and Fahrenheit, because I do calculations involving the gass laws. I do this to determine out how large aerostat habitats have to be on Venus to float. For those who follow me on medium you might know of my interest in space exploration and colonization of Venus.

I will show you how we can represent different units of temperature in Julia and Python. This is an interesting case for Julia because it shows quite clearly the advantages of using a language supporting multiple-dispatch, in comparison to a more traditional object oriented language such as Python, which relies on single dispatch.

Python Solution

I had a number of false starts to get down a good Python solution, and not being as good with Python as with Julia, this might not be the most optimal way of solving the problem. I am happy to hear alternative solutions to this problem.

Below is a Python class defining the Celsius temperature unit. Notice we need to define conversion functions for all the other temperatures and define the add and subtract operators to operate on a common unit.

class Celsius(object):
def __init__(self, temp):
super(Celsius, self).__init__()
if type(temp) == float or type(temp)

--

--

Erik Engheim
Erik Engheim

Written by Erik Engheim

Geek dad, living in Oslo, Norway with passion for UX, Julia programming, science, teaching, reading and writing.

Responses (7)