小编sve*_*cax的帖子

实现协议的Python泛型类型

对象 A、B ... 具有属性namespace,并且我有一个函数可以通过一组特定的属性值过滤此类对象的列表namespace

T = TypeVar('T')


def filter(seq: list[T], namespace_values: set[str]) -> list[T]:
    # Returns a smaller list containing only the items from
    # `seq` whose `namespace` are in `namespace_values`
    ...
Run Code Online (Sandbox Code Playgroud)

X这很有效,但它允许传递不具有该属性的类型的对象,namespace而不会出现任何检查错误。

然后我创建了一个协议并更改了函数以便使用该协议:


class Namespaced(Protocol):
    namespace: str

def filter(seq: list[Namespaced], namespace_values: set[str]) -> list[Namespaced]:
    # Returns a smaller list containing only the items from
    # `seq` whose `namespace` are in `namespace_values`
    ...
Run Code Online (Sandbox Code Playgroud)

现在,如果我传递一个列表X(这就是我想要的),我会收到一个检查错误,但我丢失了泛型:


list_of_a: list[A] = [a1, a2, a3]

output …
Run Code Online (Sandbox Code Playgroud)

python generics protocols python-typing

9
推荐指数
1
解决办法
2350
查看次数

Python 3.10 asyncio.gather() 显示 DeprecationWarning: 没有当前事件循环

我有一个 Django 应用程序,在其视图之一中,我使用 asyncio 来向外部组件发出一些并发请求。

这个想法是这样的:

import asyncio


async def do_request(project):
    result = ...

    return result

def aggregate_results(projects: list):
    loop = asyncio.new_event_loop()

    asyncio.set_event_loop(loop)

    results = loop.run_until_complete(
        asyncio.gather(*(do_request(project) for project in projects))
    )

    loop.close()

    return zip(projects, results)
Run Code Online (Sandbox Code Playgroud)

好吧,当我运行测试时,我得到了DeprecationWarning: There is no current event loop这一行:

        asyncio.gather(*(do_request(project) for project in projects))
Run Code Online (Sandbox Code Playgroud)

我应该如何解释此警告以及我需要进行哪些更改才能消除它?谢谢!

python python-asyncio python-3.10

5
推荐指数
1
解决办法
2万
查看次数

如何从匿名ActionListener访问JFrame以在框架中添加面板?

如果要单击某个按钮,并且不知道如何从匿名ActionListener进行管理,我想在框架中添加JPanel。这是代码:

public class MyFrame extends JFrame {
   JPanel panel;
   JButton button;
   public MyFrame() {
      button = new JButton("Add panel");
      button.addActionListener(new ActionListener() {
         public void actionPerformed(ActionEvent event) {
            panel = new JPanel();
            //here I want to add the panel to frame: this.add(panel), but I don't know
            //how to write that. In these case "this" refers to ActionListener, not to
            //frame, so I want to know what to write instead of "this" in order to
            //refer to the frame
         }
      }
      this.add(button); …
Run Code Online (Sandbox Code Playgroud)

java swing actionlistener

4
推荐指数
2
解决办法
4365
查看次数