Skip to content
Draft
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
15 changes: 12 additions & 3 deletions Lib/profile.py
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@


import importlib.machinery
import importlib.util
import io
import sys
import time
Expand Down Expand Up @@ -602,12 +603,20 @@ def main():
code = compile(fp.read(), progname, 'exec')
spec = importlib.machinery.ModuleSpec(name='__main__', loader=None,
origin=progname)
globs = {
'__spec__': spec,
module = importlib.util.module_from_spec(spec)
# Set __main__ so that importing __main__ in the profiled code will
# return the same namespace that the code is executing under.
sys.modules['__main__'] = module
# Ensure that we're using the same __dict__ instance as the module
# for the global variables so that updates to globals are reflected
# in the module's namespace.
globs = module.__dict__
globs.update({
'__spec__': None,
'__file__': spec.origin,
'__name__': spec.name,
'__package__': None,
}
})
try:
runctx(code, globs, None, options.outfile, options.sort)
except BrokenPipeError as exc:
Expand Down
22 changes: 22 additions & 0 deletions Lib/test/test_profile.py
Original file line number Diff line number Diff line change
Expand Up @@ -120,6 +120,28 @@ def test_run_profile_as_module(self):
assert_python_ok('-m', self.profilermodule.__name__,
'-m', 'timeit', '-n', '1')

def test_script_with_deferred_dataclass_annotations(self):
# gh-88580: the profiled script must be available as __main__ so
# dataclasses can resolve string annotations in its global namespace.
with temp_dir() as tmpdir:
script = os.path.join(tmpdir, 'profile_dataclass.py')
with open(script, 'w', encoding='utf-8') as f:
f.write("""\
from __future__ import annotations
from dataclasses import dataclass, InitVar

@dataclass
class C:
value: InitVar[int]

def __post_init__(self, value):
assert value == 42

C(42)
""")

assert_python_ok('-m', self.profilermodule.__name__, script)

def test_output_file_when_changing_directory(self):
with temp_dir() as tmpdir, change_cwd(tmpdir):
os.mkdir('dest')
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
Fix the :mod:`profile` command-line interface to execute scripts in the actual
``__main__`` module namespace. This fixes profiling dataclasses that use
deferred :class:`~dataclasses.InitVar` annotations.
Loading