Not too long ago I discovered that Python implements the slots pattern. They allow you limit the attributes that a class can have after instantiating it.
The code below works, but it may give raise to un-intended behavior:
class Camera: exposure = '1ms' cam = Camera() cam.exposure_time = '10ms'
Since Python allows creating attributes of classes at runtime, the user of our
Camera class may, inadvertely, use a wrong name and never realize of the mistake. There are many ways of avoiding this problem, but today I'll discuss about
slots. We can change our class:
class Camera: __slots__ = ['exposure', ] exposure = '1ms'
If we repeat what we did earlier, we will now get an error:
>>> cam = Camera() >>> cam.exposure_time = '10ms' ... AttributeError: 'Camera' object has no attribute 'exposure_time'
Which, I believe is a very descriptive error.
slots has also the advantage of reducing the memory footprint of our objects. If we are going to create millions of camera objects at the same time (thinking about a server handling requests, for example), it may be smart to optimize the attribute declaration.
Did you know about slots? Have you ever had to use them in your code?