问题描述
@H_502_1@def get_source(import_name: str) -> Optional[str]: spec = get_spec(import_name) # Now,here. The spec.loader might be one of several values. # But I *kNow* that it is gonna be importlib.machinery.sourceFileloader # I need to typecast the attribute of the spec.loader into the above if spec and spec.loader.path.endswith('.py'): return spec.loader.get_data(spec.loader.path).decode("utf-8") return None def get_spec(import_name: str) -> importlib.machinery.ModuleSpec: try: return importlib.util.find_spec(import_name) except (ImportError,AttributeError,TypeError,ValueError): return None
显然,PEP526允许我尝试使用可想象的最基本语法
@H_502[email protected]: annotation
但是,据我从Rossum's comment得知,显然类型检查器不必支持此语法。并且mypy给出错误@H_502_1@Type cannot be declared in assignment to non-self attribute。
现在,根据我在github上的shedshed上发现的另一个问题,您可以执行断言以让mypy知道对象的类型。而不是打字。
@H_502_1@assert isinstance(obj.attr,annotation)
但是,对我来说,这感觉不对。我正在尝试使用打字功能(如果可能的话),并且我尝试提供的项目将mypy用作其类型检查器。
有效但使我讨厌自己的断言版本是:
@H_502_1@def get_source(import_name: str) -> Optional[str]: spec = get_spec(import_name) assert isinstance(spec.loader,importlib.machinery.sourceFileLoader) assert isinstance(spec.loader.path,str) if spec and spec.loader.path.endswith('.py'): return spec.loader.get_data(spec.loader.path).decode("utf-8") return None
我读过的无数排版和Mypy问题无济于事,所以我在这里。
解决方法
暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!
如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。
小编邮箱:dio#foxmail.com (将#修改为@)