我是靠谱客的博主 认真橘子,最近开发中收集的这篇文章主要介绍python 中evaluationcontext是什么,我可以在带有延迟注释评估的Python类型提示中使用__qualname__吗?...,觉得挺不错的,现在分享给大家,希望可以做个参考。

概述

I like using __qualname__ for the return-type annotation of factory-style class methods, because it doesn't hardcode the classname and therefore keeps working subclasses (cf. this answer).

class Foo:

@classmethod

def make(cls) -> __qualname__:

return cls()

Currently this seems to work fine, but I am not sure whether this will still be possible with the postponed evaluation of annotations (PEP 563): the PEP says that

Annotations can only use names present in the module scope as postponed evaluation using local names is not reliable (with the sole exception of class-level names resolved by typing.get_type_hints()).

The PEP also says:

The get_type_hints() function automatically resolves the correct value of globalns for functions and classes. It also automatically provides the correct localns for classes.

However, the following code

from __future__ import annotations

import typing

class Foo():

@classmethod

def make(cls) -> __qualname__:

return cls()

print(typing.get_type_hints(Foo.make))

fails with

File "qualname_test.py", line 11, in

print(typing.get_type_hints(Foo.make))

File "/var/local/conda/envs/py37/lib/python3.7/typing.py", line 1004, in get_type_hints

value = _eval_type(value, globalns, localns)

File "/var/local/conda/envs/py37/lib/python3.7/typing.py", line 263, in _eval_type

return t._evaluate(globalns, localns)

File "/var/local/conda/envs/py37/lib/python3.7/typing.py", line 467, in _evaluate

eval(self.__forward_code__, globalns, localns),

File "", line 1, in

NameError: name '__qualname__' is not defined

Commenting the __future__ import makes the code work again, in that case it outputs

{'return': }

as expected.

Is my use case __qualname__ supported (which would mean that get_type_hints is buggy), or is this approach not possible with PEP 563?

解决方案

Foo.make doesn't always return an instance of Foo (which is what __qualname__ expands to). It returns an instance of the class it receives as an argument, which isn't necessarily Foo. Consider:

>>> class Foo:

... @classmethod

... def make(cls):

... return cls()

...

>>> class Bar(Foo):

... pass

...

>>> type(Bar.make())

The correct type hint would be a type variable:

T = TypeVar("T", bound="Foo")

class Foo:

@classmethod

def make(cls: Type[T]) -> T:

return cls()

最后

以上就是认真橘子为你收集整理的python 中evaluationcontext是什么,我可以在带有延迟注释评估的Python类型提示中使用__qualname__吗?...的全部内容,希望文章能够帮你解决python 中evaluationcontext是什么,我可以在带有延迟注释评估的Python类型提示中使用__qualname__吗?...所遇到的程序开发问题。

如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(42)

评论列表共有 0 条评论

立即
投稿
返回
顶部