我的电报频道@pythonetc的提示和技巧,2018年12月



这是我的Telegram频道@pythonetc中关于Python和编程的新技巧和窍门。

多个上下文管理器


有时您想使用多个上下文管理器运行代码块:

with open('f') as f: with open('g') as g: with open('h') as h: pass 

从Python 2.7和3.1开始,您可以使用单个with表达式来实现:

 o = open with o('f') as f, o('g') as g, o('h') as h: pass 

在此之前,您可以使用contextlib.nested函数:

 with nested(o('f'), o('g'), o('h')) as (f, g, h): pass 

如果使用的上下文管理器数量未知,那么更高级的工具非常适合您。 contextlib.ExitStack允许您在任意时间输入任意数量的上下文,但保证在最后退出:

 with ExitStack() as stack: f = stack.enter_context(o('f')) g = stack.enter_context(o('g')) other = [ stack.enter_context(o(filename)) for filename in filenames ] 

解释器内存中的对象


可以通过gc.get_objects()访问解释器内存中当前存在的所有对象:

 In : class A: ...: def __init__(self, x): ...: self._x = x ...: ...: def __repr__(self): ...: class_name = type(self).__name__ ...: x = self._x ...: return f'{class_name}({x!r})' ...: In : A(1) Out: A(1) In : A(2) Out: A(2) In : A(3) Out: A(3) In : [x for x in gc.get_objects() if isinstance(x, A)] Out: [A(1), A(2), A(3)] 

数字符号


 In : int('୧৬༣') Out: 163 

0 1 2 3 4 5 6 7 8 9不是唯一被视为数字的字符。 Python遵循Unicode规则,将数百个符号视为数字,这是完整列表(http://www.fileformat.info/info/unicode/category/Nd/list.htm)。

这会影响intunicode.isdecimal甚至re.match

 In : int('෯') Out: 9 In : '٢'.isdecimal() Out: True In : bool(re.match('\d', '౫')) Out: True 

UTC午夜


 >>> bool(datetime(2018, 1, 1).time()) False >>> bool(datetime(2018, 1, 1, 13, 12, 11).time()) True 

在Python 3.5之前,如果datetime.time()对象表示UTC午夜,则将其视为false。 这可能会导致模糊的错误。 在以下示例中, if not运行,可能不是因为create_timeNone ,而是因为它是午夜。

 def create(created_time=None) -> None: if not created_time: created_time = datetime.now().time() 

您可以通过显式测试None来解决此问题: if created_time is None

异步文件操作


Python不支持异步文件操作。 为了使它们无阻塞,您必须使用单独的线程。

要在线程中异步运行代码,应使用loop.run_in_executor方法。

第三方aiofiles模块为您完成所有这些操作,从而提供了漂亮而简单的界面:

 async with aiofiles.open('filename', mode='r') as f: contents = await f.read() 

资料来源: habr.com/ru/company/mailru/blog/436322

Source: https://habr.com/ru/post/zh-CN436324/


All Articles