Skip to content

Commit f53ceed

Browse files
authored
Merge branch 'main' into monitoring-capi
2 parents 0438389 + a2ae847 commit f53ceed

34 files changed

+2529
-864
lines changed

Include/internal/pycore_crossinterp.h

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -217,6 +217,11 @@ typedef struct _excinfo {
217217
const char *errdisplay;
218218
} _PyXI_excinfo;
219219

220+
PyAPI_FUNC(int) _PyXI_InitExcInfo(_PyXI_excinfo *info, PyObject *exc);
221+
PyAPI_FUNC(PyObject *) _PyXI_FormatExcInfo(_PyXI_excinfo *info);
222+
PyAPI_FUNC(PyObject *) _PyXI_ExcInfoAsObject(_PyXI_excinfo *info);
223+
PyAPI_FUNC(void) _PyXI_ClearExcInfo(_PyXI_excinfo *info);
224+
220225

221226
typedef enum error_code {
222227
_PyXI_ERR_NO_ERROR = 0,
@@ -313,6 +318,21 @@ PyAPI_FUNC(PyObject *) _PyXI_ApplyCapturedException(_PyXI_session *session);
313318
PyAPI_FUNC(int) _PyXI_HasCapturedException(_PyXI_session *session);
314319

315320

321+
/*************/
322+
/* other API */
323+
/*************/
324+
325+
// Export for _testinternalcapi shared extension
326+
PyAPI_FUNC(PyInterpreterState *) _PyXI_NewInterpreter(
327+
PyInterpreterConfig *config,
328+
PyThreadState **p_tstate,
329+
PyThreadState **p_save_tstate);
330+
PyAPI_FUNC(void) _PyXI_EndInterpreter(
331+
PyInterpreterState *interp,
332+
PyThreadState *tstate,
333+
PyThreadState **p_save_tstate);
334+
335+
316336
#ifdef __cplusplus
317337
}
318338
#endif

Include/internal/pycore_interp.h

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -103,11 +103,22 @@ struct _is {
103103
int requires_idref;
104104
PyThread_type_lock id_mutex;
105105

106+
#define _PyInterpreterState_WHENCE_NOTSET -1
107+
#define _PyInterpreterState_WHENCE_UNKNOWN 0
108+
#define _PyInterpreterState_WHENCE_RUNTIME 1
109+
#define _PyInterpreterState_WHENCE_LEGACY_CAPI 2
110+
#define _PyInterpreterState_WHENCE_CAPI 3
111+
#define _PyInterpreterState_WHENCE_XI 4
112+
#define _PyInterpreterState_WHENCE_MAX 4
113+
long _whence;
114+
106115
/* Has been initialized to a safe state.
107116
108117
In order to be effective, this must be set to 0 during or right
109118
after allocation. */
110119
int _initialized;
120+
/* Has been fully initialized via pylifecycle.c. */
121+
int _ready;
111122
int finalizing;
112123

113124
uintptr_t last_restart_version;
@@ -305,6 +316,11 @@ PyAPI_FUNC(int) _PyInterpreterState_IDInitref(PyInterpreterState *);
305316
PyAPI_FUNC(int) _PyInterpreterState_IDIncref(PyInterpreterState *);
306317
PyAPI_FUNC(void) _PyInterpreterState_IDDecref(PyInterpreterState *);
307318

319+
PyAPI_FUNC(long) _PyInterpreterState_GetWhence(PyInterpreterState *interp);
320+
extern void _PyInterpreterState_SetWhence(
321+
PyInterpreterState *interp,
322+
long whence);
323+
308324
extern const PyConfig* _PyInterpreterState_GetConfig(PyInterpreterState *interp);
309325

310326
// Get a copy of the current interpreter configuration.

Include/internal/pycore_pystate.h

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -77,6 +77,9 @@ _Py_IsMainInterpreterFinalizing(PyInterpreterState *interp)
7777
interp == &_PyRuntime._main_interpreter);
7878
}
7979

80+
// Export for _xxsubinterpreters module.
81+
PyAPI_FUNC(PyObject *) _PyInterpreterState_GetIDObject(PyInterpreterState *);
82+
8083
// Export for _xxsubinterpreters module.
8184
PyAPI_FUNC(int) _PyInterpreterState_SetRunningMain(PyInterpreterState *);
8285
PyAPI_FUNC(void) _PyInterpreterState_SetNotRunningMain(PyInterpreterState *);

Include/internal/pycore_runtime_init.h

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -162,6 +162,7 @@ extern PyTypeObject _PyExc_MemoryError;
162162
#define _PyInterpreterState_INIT(INTERP) \
163163
{ \
164164
.id_refcount = -1, \
165+
._whence = _PyInterpreterState_WHENCE_NOTSET, \
165166
.imports = IMPORTS_INIT, \
166167
.ceval = { \
167168
.recursion_limit = Py_DEFAULT_RECURSION_LIMIT, \

Lib/glob.py

Lines changed: 223 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,9 @@
44
import os
55
import re
66
import fnmatch
7+
import functools
78
import itertools
9+
import operator
810
import stat
911
import sys
1012

@@ -256,7 +258,9 @@ def escape(pathname):
256258
return drive + pathname
257259

258260

261+
_special_parts = ('', '.', '..')
259262
_dir_open_flags = os.O_RDONLY | getattr(os, 'O_DIRECTORY', 0)
263+
_no_recurse_symlinks = object()
260264

261265

262266
def translate(pat, *, recursive=False, include_hidden=False, seps=None):
@@ -312,3 +316,222 @@ def translate(pat, *, recursive=False, include_hidden=False, seps=None):
312316
results.append(any_sep)
313317
res = ''.join(results)
314318
return fr'(?s:{res})\Z'
319+
320+
321+
@functools.lru_cache(maxsize=512)
322+
def _compile_pattern(pat, sep, case_sensitive, recursive=True):
323+
"""Compile given glob pattern to a re.Pattern object (observing case
324+
sensitivity)."""
325+
flags = re.NOFLAG if case_sensitive else re.IGNORECASE
326+
regex = translate(pat, recursive=recursive, include_hidden=True, seps=sep)
327+
return re.compile(regex, flags=flags).match
328+
329+
330+
class _Globber:
331+
"""Class providing shell-style pattern matching and globbing.
332+
"""
333+
334+
def __init__(self, sep, case_sensitive, recursive=False):
335+
self.sep = sep
336+
self.case_sensitive = case_sensitive
337+
self.recursive = recursive
338+
339+
# Low-level methods
340+
341+
lstat = staticmethod(os.lstat)
342+
scandir = staticmethod(os.scandir)
343+
parse_entry = operator.attrgetter('path')
344+
concat_path = operator.add
345+
346+
if os.name == 'nt':
347+
@staticmethod
348+
def add_slash(pathname):
349+
tail = os.path.splitroot(pathname)[2]
350+
if not tail or tail[-1] in '\\/':
351+
return pathname
352+
return f'{pathname}\\'
353+
else:
354+
@staticmethod
355+
def add_slash(pathname):
356+
if not pathname or pathname[-1] == '/':
357+
return pathname
358+
return f'{pathname}/'
359+
360+
# High-level methods
361+
362+
def compile(self, pat):
363+
return _compile_pattern(pat, self.sep, self.case_sensitive, self.recursive)
364+
365+
def selector(self, parts):
366+
"""Returns a function that selects from a given path, walking and
367+
filtering according to the glob-style pattern parts in *parts*.
368+
"""
369+
if not parts:
370+
return self.select_exists
371+
part = parts.pop()
372+
if self.recursive and part == '**':
373+
selector = self.recursive_selector
374+
elif part in _special_parts:
375+
selector = self.special_selector
376+
else:
377+
selector = self.wildcard_selector
378+
return selector(part, parts)
379+
380+
def special_selector(self, part, parts):
381+
"""Returns a function that selects special children of the given path.
382+
"""
383+
select_next = self.selector(parts)
384+
385+
def select_special(path, exists=False):
386+
path = self.concat_path(self.add_slash(path), part)
387+
return select_next(path, exists)
388+
return select_special
389+
390+
def wildcard_selector(self, part, parts):
391+
"""Returns a function that selects direct children of a given path,
392+
filtering by pattern.
393+
"""
394+
395+
match = None if part == '*' else self.compile(part)
396+
dir_only = bool(parts)
397+
if dir_only:
398+
select_next = self.selector(parts)
399+
400+
def select_wildcard(path, exists=False):
401+
try:
402+
# We must close the scandir() object before proceeding to
403+
# avoid exhausting file descriptors when globbing deep trees.
404+
with self.scandir(path) as scandir_it:
405+
entries = list(scandir_it)
406+
except OSError:
407+
pass
408+
else:
409+
for entry in entries:
410+
if match is None or match(entry.name):
411+
if dir_only:
412+
try:
413+
if not entry.is_dir():
414+
continue
415+
except OSError:
416+
continue
417+
entry_path = self.parse_entry(entry)
418+
if dir_only:
419+
yield from select_next(entry_path, exists=True)
420+
else:
421+
yield entry_path
422+
return select_wildcard
423+
424+
def recursive_selector(self, part, parts):
425+
"""Returns a function that selects a given path and all its children,
426+
recursively, filtering by pattern.
427+
"""
428+
# Optimization: consume following '**' parts, which have no effect.
429+
while parts and parts[-1] == '**':
430+
parts.pop()
431+
432+
# Optimization: consume and join any following non-special parts here,
433+
# rather than leaving them for the next selector. They're used to
434+
# build a regular expression, which we use to filter the results of
435+
# the recursive walk. As a result, non-special pattern segments
436+
# following a '**' wildcard don't require additional filesystem access
437+
# to expand.
438+
follow_symlinks = self.recursive is not _no_recurse_symlinks
439+
if follow_symlinks:
440+
while parts and parts[-1] not in _special_parts:
441+
part += self.sep + parts.pop()
442+
443+
match = None if part == '**' else self.compile(part)
444+
dir_only = bool(parts)
445+
select_next = self.selector(parts)
446+
447+
def select_recursive(path, exists=False):
448+
path = self.add_slash(path)
449+
match_pos = len(str(path))
450+
if match is None or match(str(path), match_pos):
451+
yield from select_next(path, exists)
452+
stack = [path]
453+
while stack:
454+
yield from select_recursive_step(stack, match_pos)
455+
456+
def select_recursive_step(stack, match_pos):
457+
path = stack.pop()
458+
try:
459+
# We must close the scandir() object before proceeding to
460+
# avoid exhausting file descriptors when globbing deep trees.
461+
with self.scandir(path) as scandir_it:
462+
entries = list(scandir_it)
463+
except OSError:
464+
pass
465+
else:
466+
for entry in entries:
467+
is_dir = False
468+
try:
469+
if entry.is_dir(follow_symlinks=follow_symlinks):
470+
is_dir = True
471+
except OSError:
472+
pass
473+
474+
if is_dir or not dir_only:
475+
entry_path = self.parse_entry(entry)
476+
if match is None or match(str(entry_path), match_pos):
477+
if dir_only:
478+
yield from select_next(entry_path, exists=True)
479+
else:
480+
# Optimization: directly yield the path if this is
481+
# last pattern part.
482+
yield entry_path
483+
if is_dir:
484+
stack.append(entry_path)
485+
486+
return select_recursive
487+
488+
def select_exists(self, path, exists=False):
489+
"""Yields the given path, if it exists.
490+
"""
491+
if exists:
492+
# Optimization: this path is already known to exist, e.g. because
493+
# it was returned from os.scandir(), so we skip calling lstat().
494+
yield path
495+
else:
496+
try:
497+
self.lstat(path)
498+
yield path
499+
except OSError:
500+
pass
501+
502+
@classmethod
503+
def walk(cls, root, top_down, on_error, follow_symlinks):
504+
"""Walk the directory tree from the given root, similar to os.walk().
505+
"""
506+
paths = [root]
507+
while paths:
508+
path = paths.pop()
509+
if isinstance(path, tuple):
510+
yield path
511+
continue
512+
try:
513+
with cls.scandir(path) as scandir_it:
514+
dirnames = []
515+
filenames = []
516+
if not top_down:
517+
paths.append((path, dirnames, filenames))
518+
for entry in scandir_it:
519+
name = entry.name
520+
try:
521+
if entry.is_dir(follow_symlinks=follow_symlinks):
522+
if not top_down:
523+
paths.append(cls.parse_entry(entry))
524+
dirnames.append(name)
525+
else:
526+
filenames.append(name)
527+
except OSError:
528+
filenames.append(name)
529+
except OSError as error:
530+
if on_error is not None:
531+
on_error(error)
532+
else:
533+
if top_down:
534+
yield path, dirnames, filenames
535+
if dirnames:
536+
prefix = cls.add_slash(path)
537+
paths += [cls.concat_path(prefix, d) for d in reversed(dirnames)]

Lib/linecache.py

Lines changed: 11 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -5,9 +5,6 @@
55
that name.
66
"""
77

8-
import sys
9-
import os
10-
118
__all__ = ["getline", "clearcache", "checkcache", "lazycache"]
129

1310

@@ -66,6 +63,11 @@ def checkcache(filename=None):
6663
size, mtime, lines, fullname = entry
6764
if mtime is None:
6865
continue # no-op for files loaded via a __loader__
66+
try:
67+
# This import can fail if the interpreter is shutting down
68+
import os
69+
except ImportError:
70+
return
6971
try:
7072
stat = os.stat(fullname)
7173
except OSError:
@@ -76,6 +78,12 @@ def checkcache(filename=None):
7678

7779

7880
def updatecache(filename, module_globals=None):
81+
# These imports are not at top level because linecache is in the critical
82+
# path of the interpreter startup and importing os and sys take a lot of time
83+
# and slow down the startup sequence.
84+
import os
85+
import sys
86+
7987
"""Update a cache entry and return its list of lines.
8088
If something's wrong, print a message, discard the cache entry,
8189
and return an empty list."""

0 commit comments

Comments
 (0)