记录一些方便使用的python代码片段
从字典构造Enum枚举类型
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
| DATA = {'alice': {}, 'bob': {}}
class MyEnumBase():
def __init__(self, *args):
self._data = {}
def get_data(self) -> dict:
return self._data.copy()
@property
def foo(self) -> int:
return int(self._data["foo"])
class MyEnum(MyEnumBase, Enum):
"""MyEnum type
"""
def __init__(self, *args):
super().__init__(*args)
self._data = DATA[self._value_]
self.__doc__ = MyEnum.__doc__
MyEnumClass = MyEnum('MyEnumClass', {k: k for k in DATA})
|
构造namedtuple类型
1
2
3
4
5
6
7
8
9
10
11
| class Gems(namedtuple('Gems', list('rgbwd'), defaults=[0, 0, 0, 0, 0])):
def __add__(self, other):
return self.__class__(*(x+y for x, y in zip(self, other)))
def __sub__(self, other):
return self.__class__(*(x-y for x, y in zip(self, other)))
@property
def gtz(self) -> 'Gems':
"""greater than zero"""
return self.__class__(*(max(0, x) for x in self))
|
命令行接口模块
使用click
库。读取当前目录的所有文件作为子命令。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
| @click.group()
def cli_group():
pass
if '__path__' in locals():
_path_ = __path__
else:
_path_ = [os.path.dirname(__file__)]
for _, module_name, _ in pkgutil.walk_packages(_path_):
module = importlib.import_module('.' + module_name, __package__)
if hasattr(module, 'cli'):
command_name = module_name.replace("_", "-")
cli_group.add_command(module.cli, name=command_name)
cli_group()
|