首页 > 解决方案 > 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]])

标签: pythonrangemultimethod

解决方案


推荐阅读