【发布时间】:2019-12-13 05:57:11
【问题描述】:
我正在尝试将类型添加到返回生成器的方法中。每当我使用指定的返回类型运行该程序时,都会引发 TypeError。
添加引号或删除输入可修复错误,但这似乎是 hack。这样做肯定有正确的方法。
def inbox_files(self) -> "Generator[RecordsFile]":
...
# OR
def inbox_files(self):
...
from typing import Generator, List
from .records_file import RecordsFile
Class Marshaller:
...
def inbox_files(self) -> Generator[RecordsFile]:
return self._search_directory(self._inbox)
def _search_directory(self, directory: str) -> RecordsFile:
for item_name in listdir(directory):
item_path = path.join(item_name, directory)
if path.isdir(item_path):
yield from self._search_directory(item_path)
elif path.isfile(item_path):
yield RecordsFile(item_path)
else:
print(f"[WARN] Unknown item found: {item_path}")
产生以下堆栈跟踪:
Traceback (most recent call last):
File "./bin/data_marshal", line 8, in <module>
from src.app import App
File "./src/app.py", line 9, in <module>
from .marshaller import Marshaller
File "./src/marshaller.py", line 9, in <module>
class Marshaller:
File "./src/marshaller.py", line 29, in Marshaller
def inbox_files(self) -> Generator[RecordsFile]:
File "/usr/local/Cellar/python/3.7.4/Frameworks/Python.framework/Versions/3.7/lib/python3.7/typing.py", line 254, in inner
return func(*args, **kwds)
File "/usr/local/Cellar/python/3.7.4/Frameworks/Python.framework/Versions/3.7/lib/python3.7/typing.py", line 630, in __getitem__
_check_generic(self, params)
File "/usr/local/Cellar/python/3.7.4/Frameworks/Python.framework/Versions/3.7/lib/python3.7/typing.py", line 208, in _check_generic
raise TypeError(f"Too {'many' if alen > elen else 'few'} parameters for {cls};"
TypeError: Too few parameters for typing.Generator; actual 1, expected 3
¯\_(ツ)_/¯
【问题讨论】:
标签: python python-3.x generator