gh-85668: Create public API for typing._eval_type#21753
Conversation
| """Evaluate all forward references in the given type t. | ||
| For use of globalns and localns see the docstring for get_type_hints(). | ||
| """ | ||
| return _eval_type(t, globalns, localns) |
There was a problem hiding this comment.
Hm, you have to fill in globalns and localns if they are None, the same as get_type_hints does. And add tests for this.
There was a problem hiding this comment.
What should I fill them with? Unlike get_type_hints, eval_type is not aware of the context it's being used in, so it's the user's responsibility to provide one (in form of globalns and localns). get_type_hints retrieves the namespace from the passed object, but eval_type only receives a type (declaration).
There was a problem hiding this comment.
Good point, but then you shouldn't give then a default value of None. :-)
My proposal: require globalns, and let localns default to globalns.
There was a problem hiding this comment.
The intention behind giving a default of None to both parameters was to not prioritize one over the other. If one should take priority, globalns is certainly the better choice already from considering the order of parameters (to be consistent with get_type_hints).
But do we even need a distinction between global and local namespace at this point? What about exposing a single parameter namespace without default? The user can always do something like eval_type(t, namespace=globals() | locals()).
By the way, I realized that ForwardRef._evaluate sets globalns = localns if the former is None and the latter isn't. These are then passed to eval. Since eval accepts any mapping for locals but requires a dict for globals this can lead to the following error:
>>> from types import MappingProxyType
>>> _eval_type(ForwardRef('int'), globalns=None, localns=MappingProxyType({}))
[...]
File ".../lib/python3.8/typing.py", line 518, in _evaluate
eval(self.__forward_code__, globalns, localns),
TypeError: globals must be a real dict; try eval(expr, {}, mapping)Does that mean that either ForwardRef._evaluate or the new eval_type should include another safety check?
|
It would have a use case for me. When is this going to be finished? |
Never, unless someone revives it. |
|
This PR is stale because it has been open for 30 days with no activity. |
https://bugs.python.org/issue41496