python - 相当于 dart 中的 python with 语句

标签 python dart telegram with-statement

例如,当使用 Pyrogram 库启动 Telegram 客户端时,可以这样做:

with Client as app:
  app.do_something()

dart 中已经有一个 tdlib 包,尽管不像 Pyrogram。 感谢有关此主题的任何帮助。


对于那些了解 Dart 但不懂 Python 的人来说,with 语句采用一个上下文管理器,并在执行主体之前和之后执行其一些代码。上面的代码非常大致相当于

app = Client.__enter__()
app.do_something()
app.__exit__()

除非 app.__exit__() 保证被调用,即使 app.do_something() 引发异常。 __enter____exit__ 是由 Client 类型定义的两个方法,使其成为上下文管理器。

最佳答案

Dart 中不存在与 Python with 语句等同的直接形式。但是,您可以使用以下模式来实现相同的行为:

void clientScope(void Function(Client) callback) {
  // Initialize your client
  final client = Client.initialize();

  // Acts as the body of a 'with' statement
  callback(client);

  // Perform any cleanup
  client.cleanup();
}

然后可以通过以下方式使用它:

clientScope((Client app) {
  app.doSomething();
});

为了保持鲁棒性,您还可以将回调包装在try-catch-finally中,并在finally block 中执行任何清理。

关于python - 相当于 dart 中的 python with 语句,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59427601/

相关文章:

flutter - 如何在 flutter 数据表中设置垂直和水平边框?

flutter - 错误:无法使用静态访问权限访问实例成员 'imageUrl'。 (位于[store] lib\main.dart:82处的static_access_to_instance_member)

telegram - 如何在 Telegram Bot API 中 setWebhook 后使用 getUpdates

python - heroku Telegram Bot ,BadRequest : Bad webhook: ip address 0. 0.0.0 被保留

python - 最大矩形算法

python - 在 Python 中交互运行外部可执行文件

listview - 当应用程序移至后台状态并再次移至前台状态时,无限列表会导致重复

python - 在 telegram.org API 中响应 new_session_created 消息

python - 尝试在我的测试中激活 Django 信号

python - 在 python 中生成结构化文本的想法或模块?