apache-ignite
65 строк · 1.8 Кб
1# Licensed to the Apache Software Foundation (ASF) under one or more
2# contributor license agreements. See the NOTICE file distributed with
3# this work for additional information regarding copyright ownership.
4# The ASF licenses this file to You under the Apache License, Version 2.0
5# (the "License"); you may not use this file except in compliance with
6# the License. You may obtain a copy of the License at
7#
8# http://www.apache.org/licenses/LICENSE-2.0
9#
10# Unless required by applicable law or agreed to in writing, software
11# distributed under the License is distributed on an "AS IS" BASIS,
12# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13# See the License for the specific language governing permissions and
14# limitations under the License.
15
16"""
17This module contains various syntaxic sugar for enums
18"""
19
20from enum import IntEnum21
22
23def constructible(cls):24"""25If decorate IntEnum subclass with this decorator, following is possible:
26
27@constructible
28class StopType(IntEnum):
29SIGTERM = 0
30SIGKILL = 1
31DISCONNECT = 2
32
33stop_type = 1
34
35with StopType.construct_from(stop_type) as sp:
36if sp is StopType.SIGKILL:
37print('got sigkill')
38
39stop_type = 'DISCONNECT'
40
41with StopType.construct_from(stop_type) as sp:
42if sp is StopType.DISCONNECT:
43print('got disconnect')
44
45"""
46assert issubclass(cls, IntEnum)47
48members = dict(cls.__members__.items())49
50def construct_from(val):51if isinstance(val, str):52return members[val]53return cls.__new__(cls, val)54
55def __enter__(self):56return self57
58def __exit__(self, *args, **kwargs):59pass60
61cls.construct_from = construct_from62cls.__enter__ = __enter__63cls.__exit__ = __exit__64
65return cls66