| Conditions | 2 |
| Total Lines | 67 |
| Lines | 0 |
| Ratio | 0 % |
Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.
For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.
Commonly applied refactorings include:
If many parameters/temporary variables are present:
| 1 | # |
||
| 48 | def enum(option, *options): |
||
| 49 | """ |
||
| 50 | Construct a new enum object. |
||
| 51 | |||
| 52 | Parameters |
||
| 53 | ---------- |
||
| 54 | *options : iterable of str |
||
| 55 | The names of the fields for the enum. |
||
| 56 | |||
| 57 | Returns |
||
| 58 | ------- |
||
| 59 | enum |
||
| 60 | A new enum collection. |
||
| 61 | |||
| 62 | Examples |
||
| 63 | -------- |
||
| 64 | >>> e = enum('a', 'b', 'c') |
||
| 65 | >>> e |
||
| 66 | <enum: ('a', 'b', 'c')> |
||
| 67 | >>> e.a |
||
| 68 | 0 |
||
| 69 | >>> e.b |
||
| 70 | 1 |
||
| 71 | >>> e.a in e |
||
| 72 | True |
||
| 73 | >>> tuple(e) |
||
| 74 | (0, 1, 2) |
||
| 75 | |||
| 76 | Notes |
||
| 77 | ----- |
||
| 78 | Identity checking is not guaranteed to work with enum members, instead |
||
| 79 | equality checks should be used. From CPython's documentation: |
||
| 80 | |||
| 81 | "The current implementation keeps an array of integer objects for all |
||
| 82 | integers between -5 and 256, when you create an int in that range you |
||
| 83 | actually just get back a reference to the existing object. So it should be |
||
| 84 | possible to change the value of 1. I suspect the behaviour of Python in |
||
| 85 | this case is undefined. :-)" |
||
| 86 | """ |
||
| 87 | options = (option,) + options |
||
| 88 | rangeob = range(len(options)) |
||
| 89 | |||
| 90 | try: |
||
| 91 | inttype = _inttypes[int(np.log2(len(options) - 1)) // 8] |
||
| 92 | except IndexError: |
||
| 93 | raise OverflowError( |
||
| 94 | 'Cannot store enums with more than sys.maxsize elements, got %d' % |
||
| 95 | len(options), |
||
| 96 | ) |
||
| 97 | |||
| 98 | class _enum(Structure): |
||
| 99 | _fields_ = [(o, inttype) for o in options] |
||
| 100 | |||
| 101 | def __iter__(self): |
||
| 102 | return iter(rangeob) |
||
| 103 | |||
| 104 | def __contains__(self, value): |
||
| 105 | return 0 <= value < len(options) |
||
| 106 | |||
| 107 | def __repr__(self): |
||
| 108 | return '<enum: %s>' % ( |
||
| 109 | ('%d fields' % len(options)) |
||
| 110 | if len(options) > 10 else |
||
| 111 | repr(options) |
||
| 112 | ) |
||
| 113 | |||
| 114 | return _enum(*rangeob) |
||
| 115 |