python - TypeError:类型“范围”不是可接受的基本类型
问题描述
你能告诉我这段代码有什么问题吗?
from multimethod import multimethod
from typing import Iterable
@multimethod
def foo(x: Iterable[Iterable]):
print(x)
@multimethod
def foo(x):
print(x)
foo([range(1), range(2)])
我得到的错误是:
TypeError: type 'range' is not an acceptable base type
有趣的是,这些片段确实有效:
from multimethod import multimethod
@multimethod
def foo(x):
print(x)
foo([range(1), range(2)])
或者
from multimethod import multimethod
from typing import Iterable
@multimethod
def foo(x: Iterable):
print(x)
@multimethod
def foo(x):
print(x)
foo([range(1), range(2)])
作为一点上下文,我想做的是建立一个层次结构并根据Iterable
持有的类型调度不同的函数:
from multimethod import multimethod
from typing import Generator, Iterable
import string
def gen(stop):
i = 0
for c in string.ascii_lowercase:
if i < stop:
i += 1
yield c
@multimethod
def bar(x: Iterable[range]):
print('bar(x: Iterable[range]')
@multimethod
def bar(x: Iterable[Generator]):
print('bar(x: Generator)')
@multimethod
def bar(x: Iterable[Iterable]):
print('bar(x: Iterable)')
#bar([range(1), range(2)])
bar([gen(2), gen(3)])
bar([[0, 1, 2], [0, 1, 2, 3]])
解决方案
推荐阅读
- python - 如何在 Tkinter 中滚动浏览一组标签小部件?
- python - 如何在 Windows 版 Git Bash 中启用 Python 上次命令历史记录?
- autohotkey - 我需要一个热键,例如“c”来启用脚本
- javascript - Camera js Web App无法获取相机供稿
- powershell - 将日历添加到组合框
- git - 如何获取 tfs 中两个变更集或 git 中两个分支的多个文件的所有更改?
- video - 视频点播如何在 Youtube 中工作?
- gcc - 为什么独立的 C hello 程序在用作动态链接器时会崩溃
- javascript - 使用变量推送json
- javascript - 在 React 状态下使用嵌套对象