]> Repositories - Adafruit_Blinka-hackapet.git/blob - src/adafruit_blinka/__init__.py
32b2002ba2dab539ffd2468f870f8e9c88967ce3
[Adafruit_Blinka-hackapet.git] / src / adafruit_blinka / __init__.py
1 """Module providing runtime utility objects to support the Micro/CircuitPython api"""
2
3 class Enum(object):
4     """
5         Object supporting CircuitPython-style of static symbols
6         as seen with Direction.OUTPUT, Pull.UP
7     """
8
9     def __repr__(self):
10         """
11         Assumes instance will be found as attribute of own class.
12         Returns dot-subscripted path to instance
13         (assuming absolute import of containing package)
14         """
15         cls = type(self)
16         for key in dir(cls):
17             if getattr(cls, key) is self:
18                 return "{}.{}.{}".format(cls.__module__, cls.__qualname__, key)
19         return repr(self)
20
21     @classmethod
22     def iteritems(cls):
23         """
24             Inspects attributes of the class for instances of the class
25             and returns as key,value pairs mirroring dict#iteritems
26         """
27         for key in dir(cls):
28             val = getattr(cls, key)
29             if type(val) is cls:
30                 yield (key, val)
31
32
33 class ContextManaged:
34     def __enter__(self):
35         return self
36
37     def __exit__(self, exc_type, exc_value, traceback):
38         self.deinit()
39
40 class Lockable(ContextManaged):
41     _locked = False
42
43     def try_lock(self):
44         if self._locked:
45             return False
46         else:
47             self._locked=True
48             return True
49
50     def unlock(self):
51         if self._locked:
52             self._locked = False
53         else:
54             raise ValueError("Not locked")