Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions Doc/library/argparse.rst
Original file line number Diff line number Diff line change
Expand Up @@ -638,6 +638,11 @@ by setting ``color`` to ``False``::
... help='an integer for the accumulator')
>>> parser.parse_args(['--help'])

Note that when ``color=True``, colored output depends on both environment
variables and terminal capabilities. However, if ``color=False``, colored
output is always disabled, even if environment variables like ``FORCE_COLOR``
are set.

.. versionadded:: 3.14


Expand Down
17 changes: 11 additions & 6 deletions Lib/annotationlib.py
Original file line number Diff line number Diff line change
Expand Up @@ -159,19 +159,21 @@ def evaluate(
type_params = getattr(owner, "__type_params__", None)

# Type parameters exist in their own scope, which is logically
# between the locals and the globals. We simulate this by adding
# them to the globals.
# between the locals and the globals.
type_param_scope = {}
if type_params is not None:
globals = dict(globals)
for param in type_params:
globals[param.__name__] = param
type_param_scope[param.__name__] = param

if self.__extra_names__:
locals = {**locals, **self.__extra_names__}

arg = self.__forward_arg__
if arg.isidentifier() and not keyword.iskeyword(arg):
if arg in locals:
return locals[arg]
elif arg in type_param_scope:
return type_param_scope[arg]
elif arg in globals:
return globals[arg]
elif hasattr(builtins, arg):
Expand All @@ -183,12 +185,15 @@ def evaluate(
else:
code = self.__forward_code__
try:
return eval(code, globals=globals, locals=locals)
return eval(code, globals=globals, locals={**type_param_scope, **locals})
except Exception:
if not is_forwardref_format:
raise

# All variables, in scoping order, should be checked before
# triggering __missing__ to create a _Stringifier.
new_locals = _StringifierDict(
{**builtins.__dict__, **locals},
{**builtins.__dict__, **globals, **type_param_scope, **locals},
globals=globals,
owner=owner,
is_class=self.__forward_is_class__,
Expand Down
2 changes: 0 additions & 2 deletions Lib/mailbox.py
Original file line number Diff line number Diff line change
Expand Up @@ -2090,8 +2090,6 @@ def closed(self):
return False
return self._file.closed

__class_getitem__ = classmethod(GenericAlias)


class _PartialFile(_ProxyFile):
"""A read-only wrapper of part of a file."""
Expand Down
1 change: 0 additions & 1 deletion Lib/pdb.py
Original file line number Diff line number Diff line change
Expand Up @@ -3603,7 +3603,6 @@ def main():
invalid_args = list(itertools.takewhile(lambda a: a.startswith('-'), args))
if invalid_args:
parser.error(f"unrecognized arguments: {' '.join(invalid_args)}")
sys.exit(2)

if opts.module:
file = opts.module
Expand Down
35 changes: 35 additions & 0 deletions Lib/test/test_annotationlib.py
Original file line number Diff line number Diff line change
Expand Up @@ -1877,6 +1877,32 @@ def test_name_lookup_without_eval(self):

self.assertEqual(exc.exception.name, "doesntexist")

def test_evaluate_undefined_generic(self):
# Test the codepath where have to eval() with undefined variables.
class C:
x: alias[int, undef]

generic = get_annotations(C, format=Format.FORWARDREF)["x"].evaluate(
format=Format.FORWARDREF,
globals={"alias": dict}
)
self.assertNotIsInstance(generic, ForwardRef)
self.assertIs(generic.__origin__, dict)
self.assertEqual(len(generic.__args__), 2)
self.assertIs(generic.__args__[0], int)
self.assertIsInstance(generic.__args__[1], ForwardRef)

generic = get_annotations(C, format=Format.FORWARDREF)["x"].evaluate(
format=Format.FORWARDREF,
globals={"alias": Union},
locals={"alias": dict}
)
self.assertNotIsInstance(generic, ForwardRef)
self.assertIs(generic.__origin__, dict)
self.assertEqual(len(generic.__args__), 2)
self.assertIs(generic.__args__[0], int)
self.assertIsInstance(generic.__args__[1], ForwardRef)

def test_fwdref_invalid_syntax(self):
fr = ForwardRef("if")
with self.assertRaises(SyntaxError):
Expand All @@ -1885,6 +1911,15 @@ def test_fwdref_invalid_syntax(self):
with self.assertRaises(SyntaxError):
fr.evaluate()

def test_re_evaluate_generics(self):
global alias
class C:
x: alias[int]

evaluated = get_annotations(C, format=Format.FORWARDREF)["x"].evaluate(format=Format.FORWARDREF)
alias = list
self.assertEqual(evaluated.evaluate(), list[int])


class TestAnnotationLib(unittest.TestCase):
def test__all__(self):
Expand Down
4 changes: 2 additions & 2 deletions Lib/test/test_genericalias.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@
from functools import partial, partialmethod, cached_property
from graphlib import TopologicalSorter
from logging import LoggerAdapter, StreamHandler
from mailbox import Mailbox, _PartialFile
from mailbox import Mailbox
try:
import ctypes
except ImportError:
Expand Down Expand Up @@ -117,7 +117,7 @@ class BaseTest(unittest.TestCase):
Iterable, Iterator,
Reversible,
Container, Collection,
Mailbox, _PartialFile,
Mailbox,
ContextVar, Token,
Field,
Set, MutableSet,
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
Fix :meth:`annotationlib.ForwardRef.evaluate` returning :class:`annotationlib.ForwardRef`
objects which do not update in new contexts.
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
Fix partial evaluation of :class:`annotationlib.ForwardRef` objects which rely
on names defined as globals.
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
The internal class ``mailbox._ProxyFile`` is no longer a parameterized generic.
Loading