本篇为阅读源码时看到的一些有趣的代码,有所改变后记录
使用二进制作为选项判断
这是在Rich
中看到的一段, 用sum
总和,得到那些参数为真
self._set_attributes = sum(
(
bold is not None,
dim is not None and 2,
italic is not None and 4,
underline is not None and 8,
blink is not None and 16,
blink2 is not None and 32,
reverse is not None and 64,
conceal is not None and 128,
strike is not None and 256,
underline2 is not None and 512,
frame is not None and 1024,
encircle is not None and 2048,
overline is not None and 4096,
)
)
self._attributes = (
sum(
(
bold and 1 or 0,
dim and 2 or 0,
italic and 4 or 0,
underline and 8 or 0,
blink and 16 or 0,
blink2 and 32 or 0,
reverse and 64 or 0,
conceal and 128 or 0,
strike and 256 or 0,
underline2 and 512 or 0,
frame and 1024 or 0,
encircle and 2048 or 0,
overline and 4096 or 0,
)
)
灵活运用or
灵活运用or可以做到参数里面
render_options = render_options.update_dimensions(
render_options.max_width, render_options.height or self.height
)
使用自定义类来判断是否写了参数
class NoChange:
pass
NO_CHANGE = NoChange()
self,
*,
width: Union[int, NoChange] = NO_CHANGE,
min_width: Union[int, NoChange] = NO_CHANGE
):
if not isinstance(width, NoChange):
options.min_width = options.max_width = max(0, width)
if not isinstance(min_width, NoChange):
options.min_width = min_width
单行 if…else
print('a') if True else print('b')
or
print('a'
if True
else 'b')
配合 for 循环
_layouts = [
layout if isinstance(layout, Layout) else Layout(layout)
for layout in layouts
]
lambda 作为参数
from typing import Callable
def test_lambda(code: Callable):
print(type(code))
if isinstance(code, Callable):
print("code is callable")
print(code())
code = 1
test_lambda(code=lambda: str(code or ''))
## output:
#<class 'function'>
#str is callable
#1
print 中的!r
pwd='123456'
print(f"password={pwd!r}")
## output:
#password='123456'
会将内容用引号包括住
多个 contentmanager 一起写
with Popen("command", stdout=PIPE, stderr=STDOUT, bufsize=1) as p, \
open('logfile', 'ab') as file:
for line in p.stdout: # b'\n'-separated lines
sys.stdout.buffer.write(line) # pass bytes as is
file.write(line)
使用__file__
定位程序的路径
import os
from . import __file__ as module_file
self.root_path = os.path.dirname(module_file)
正则表达式的扩展
希望逐字匹配的时候。
当遇到show version
的时候,需要匹配sh[[ow]] ver[[sion]]
这样写
def _PreParse(self, key, value):
"""Executed against each field of each row read from index table."""
if key == 'Command':
return re.sub(r'(\[\[.+?\]\])', self._Completion, value)
else:
return value
def _Completion(self, match):
r"""Replaces double square brackets with variable length completion.
Completion cannot be mixed with regexp matching or '\' characters
i.e. '[[(\n)]] would become (\(n)?)?.'
Args:
match: A regex Match() object.
Returns:
String of the format '(a(b(c(d)?)?)?)?'.
"""
# Strip the outer '[[' & ']]' and replace with ()? regexp pattern.
word = str(match.group())[2:-2]
return '(' + ('(').join(word) + ')?' * len(word)
多系统路径分割方法
import os
path = os.path.normpath(path)
path.split(os.sep)
遍历文件,返回列表
之前我用的都是os.walk
,其实还有一种方式,使用glob
import glob
for file in glob.iglob("{0}/*.yml".format(dirpath)):
print(file)
# or
glob.glob("{0}/*.yml".format(dirpath))
contextmanager 跳过代码块
单例类
用类继承会好些
class Singleton(object):
_instance = None
def __new__(class_, *args, **kwargs):
if not isinstance(class_._instance, class_):
class_._instance = object.__new__(class_, *args, **kwargs)
return class_._instance
class OtherClass(Singleton):
...
多类型参数
使用functools模块里面的singledispatch装饰器实现函数重载
from functools import singledispatch
@singledispatch
def connect(address):
print('类型不支持')
@connect.register
def _(address: str):
ip, port = address.split(':')
print('参数类型为string 连接到{}:{}'.format(ip, port))
@connect.register
def _(address: tuple):
ip, port = address
print('参数类型为tuple 连接到{}:{}'.format(ip, port))
connect(123)
connect('192.168.1.1:123')
connect(('192.168.1.1', 123))
## output
# 类型不支持
# 参数类型为string 连接到192.168.1.1:123
# 参数类型为tuple 连接到192.168.1.1:123
dataclass 使用dict
正常情况下,dataclass中是能有dict这种iter类的,但是可以加入field
来解决
from dataclasses import dataclass, field
@dataclass
class A:
headers: dict = field(default_factory=lambda: {})
转载请注明来源,欢迎对文章中的引用来源进行考证,欢迎指出任何有错误或不够清晰的表达。可以在下面评论区评论,也可以邮件至 365433079@qq.com