@@ -281,6 +281,15 @@ def f():
281281 f ()
282282 self .assertIn ("only allowed at module level" , str (cm .exception ))
283283
284+ def test_lazy_import_exec_in_class (self ):
285+ """lazy import via exec() inside a class should raise SyntaxError."""
286+ # exec() inside a class body also has non-module-level locals.
287+ with self .assertRaises (SyntaxError ) as cm :
288+ class C :
289+ exec ("lazy import json" )
290+
291+ self .assertIn ("only allowed at module level" , str (cm .exception ))
292+
284293 @support .requires_subprocess ()
285294 def test_lazy_import_exec_at_module_level (self ):
286295 """lazy import via exec() at module level should work."""
@@ -332,6 +341,50 @@ def test_eager_import_func(self):
332341 f = test .test_lazy_import .data .eager_import_func .f
333342 self .assertEqual (type (f ()), type (sys ))
334343
344+ def test_exec_import_func (self ):
345+ """Implicit lazy imports via exec() inside functions should be eager."""
346+ sys .set_lazy_imports ("all" )
347+
348+ def f ():
349+ exec ("import test.test_lazy_import.data.basic2" )
350+
351+ f ()
352+ self .assertIn ("test.test_lazy_import.data.basic2" , sys .modules )
353+
354+ def test_exec_import_func_with_lazy_modules (self ):
355+ """__lazy_modules__ should not make exec() imports lazy inside functions."""
356+ globals ()["__lazy_modules__" ] = ["test.test_lazy_import.data.basic2" ]
357+ try :
358+ def f ():
359+ exec ("import test.test_lazy_import.data.basic2" )
360+
361+ f ()
362+ self .assertIn ("test.test_lazy_import.data.basic2" , sys .modules )
363+ finally :
364+ del globals ()["__lazy_modules__" ]
365+
366+ def test_exec_import_class (self ):
367+ """Implicit lazy imports via exec() inside classes should be eager."""
368+ sys .set_lazy_imports ("all" )
369+
370+ class C :
371+ exec ("import test.test_lazy_import.data.basic2" )
372+
373+ self .assertIsNotNone (C )
374+ self .assertIn ("test.test_lazy_import.data.basic2" , sys .modules )
375+
376+ def test_exec_import_class_with_lazy_modules (self ):
377+ """__lazy_modules__ should not make exec() imports lazy inside classes."""
378+ globals ()["__lazy_modules__" ] = ["test.test_lazy_import.data.basic2" ]
379+ try :
380+ class C :
381+ exec ("import test.test_lazy_import.data.basic2" )
382+
383+ self .assertIsNotNone (C )
384+ self .assertIn ("test.test_lazy_import.data.basic2" , sys .modules )
385+ finally :
386+ del globals ()["__lazy_modules__" ]
387+
335388
336389class WithStatementTests (unittest .TestCase ):
337390 """Tests for lazy imports in with statement context."""
0 commit comments