My Universe

Mens Insana in Corpore Ignavo

Elegant Python Exceptions

2023-10-31 Python

Particularly when creating library packages in Python, raising exceptions is a great way to let the downstream developer know about problems occuring while executing code from within the library. Python’s built-in exceptions cover a whole host of cases. However, some problems might be library-specific and deserve a custom exception.

Custom Exceptions

Creating a custom exception in Python isn’t particularly hard when observing a few rules:

  • Custom exceptions shall be derived from Python’s Exception class
  • By convention, exception names shall end with “Error”
1class MyLibError(Exception):
2    pass

In many library packages, you will find exceptions similar to the one shown in the code example above. There’s nothing wrong with that; if chosen wisely, the exception name by itself will already tell what went wrong. However, the more details an exception provides about the circumstances it was raised in, the easier to diagnose and debug the problem, and the more appropriate the reaction to an exception.

Continue reading

Colours in Django Models

2017-11-08

Colours are quite a common property to real world objects. So naturally when building web applications, sooner or later one encounters the need to assign a colour attribute to an object. For Django developers, this usually means adding a models.CharField to their model, ready to capture the colour’s hex code.

Technically this works pretty well, as those hex codes can directly be used in HTML style attributes, embedded SVG drawings, etc. However, setting colour values via text input widget is quite tedious. On the frontend side, various libraries offer quite elaborate solutions for integrating nice colour picking widgets. For the Django admin, there is however a quite simple solution: use HTML 5 color inputs!

Continue reading

Pythonic Distance Conversion

2017-05-28

When dealing with distances or lengths, it’s a common problem to convert values between all the different units available out there. Of course, converting itself is a less than complicated simple floating point division or multiplication, depending on how values and conversion factors are stored internally. However, maintaining conversion factors all across a project is a tedious task, and Python has some good means at hand to simplify our life.

Continue reading