pimoroni / automation-hat

Python library and examples for the Pimoroni Automation HAT, pHAT and HAT Mini
https://shop.pimoroni.com/products/automation-hat
MIT License
122 stars 41 forks source link

Defer setup to avoid module import-time side-effects #13

Closed Gadgetoid closed 6 years ago

Gadgetoid commented 7 years ago

This PR makes several "friendly neighbour" changes to the Automation HAT library:

An experimental Default class, which shadows all the methods used in Automation HATs ObjectCollection class is used to trap calls to the library and call ensure_setup before handing them off to the correct class.

The default class is triggered only once. After this default class has been triggered, it will be replaced by instances of the actual Relay, Input, Output, etc classes for subsequent calls.

The setup method will be called automatically by the first call to an Automation HAT method. It will raise a RuntimeError if run again. If you want to setup with custom settings - ie: quiet mode - then automationhat.setup() should be the first thing you call after import.

See here for details of the problems import-time side-effects can have: https://www.raspberrypi.org/forums/viewtopic.php?f=32&t=193502&p=1212488#p1212488

Gadgetoid commented 7 years ago

I've refactored this to 094d6c4015095b9c3a5c66f7105232d26958fb67 from attempt 1 which relied on far too much runtime morphing of the code and was too complicated for its own good.

This attempt is markedly better, but still suffers from issues with disambiguation of Automation HAT from Automation pHAT which must be done at runtime but cannot be done upon import.

Presently Relay one, two and three are all mapped onto Automation pHATs one relay, which is suboptimal. Perhaps a RuntimeError should be raised when accessing a relay which doesn't exist, and relay one should map correctly for Automation pHAT.

Similarly Analog four exists for both Automation HAT and pHAT presently, but should only be usable on HAT.