Tim Peters | fc35de4 | 2001-03-02 01:48:16 +0000 | [diff] [blame] | 1 | """Verify that warnings are issued for global statements following use.""" |
Jeremy Hylton | 8e43cd7 | 2001-02-28 01:51:01 +0000 | [diff] [blame] | 2 | |
| 3 | from test_support import check_syntax |
| 4 | |
| 5 | import warnings |
| 6 | |
Jeremy Hylton | 150a664 | 2001-02-28 22:50:15 +0000 | [diff] [blame] | 7 | warnings.filterwarnings("error", module="<test code>") |
Jeremy Hylton | 8e43cd7 | 2001-02-28 01:51:01 +0000 | [diff] [blame] | 8 | |
Tim Peters | fc35de4 | 2001-03-02 01:48:16 +0000 | [diff] [blame] | 9 | def compile_and_check(text, should_fail=1): |
Jeremy Hylton | 8e43cd7 | 2001-02-28 01:51:01 +0000 | [diff] [blame] | 10 | try: |
| 11 | compile(text, "<test code>", "exec") |
Jeremy Hylton | 150a664 | 2001-02-28 22:50:15 +0000 | [diff] [blame] | 12 | except SyntaxError, msg: |
Tim Peters | fc35de4 | 2001-03-02 01:48:16 +0000 | [diff] [blame] | 13 | if should_fail: |
| 14 | print "got SyntaxError as expected" |
| 15 | else: |
| 16 | print "raised unexpected SyntaxError:", text |
Jeremy Hylton | 8e43cd7 | 2001-02-28 01:51:01 +0000 | [diff] [blame] | 17 | else: |
Tim Peters | fc35de4 | 2001-03-02 01:48:16 +0000 | [diff] [blame] | 18 | if should_fail: |
| 19 | print "should have raised SyntaxError:", text |
| 20 | else: |
| 21 | print "as expected, no SyntaxError" |
Jeremy Hylton | 8e43cd7 | 2001-02-28 01:51:01 +0000 | [diff] [blame] | 22 | |
| 23 | prog_text_1 = """ |
| 24 | def wrong1(): |
| 25 | a = 1 |
| 26 | b = 2 |
| 27 | global a |
| 28 | global b |
| 29 | """ |
Tim Peters | fc35de4 | 2001-03-02 01:48:16 +0000 | [diff] [blame] | 30 | compile_and_check(prog_text_1) |
Jeremy Hylton | 8e43cd7 | 2001-02-28 01:51:01 +0000 | [diff] [blame] | 31 | |
| 32 | prog_text_2 = """ |
| 33 | def wrong2(): |
| 34 | print x |
| 35 | global x |
| 36 | """ |
Tim Peters | fc35de4 | 2001-03-02 01:48:16 +0000 | [diff] [blame] | 37 | compile_and_check(prog_text_2) |
Jeremy Hylton | 8e43cd7 | 2001-02-28 01:51:01 +0000 | [diff] [blame] | 38 | |
| 39 | prog_text_3 = """ |
| 40 | def wrong3(): |
| 41 | print x |
| 42 | x = 2 |
| 43 | global x |
| 44 | """ |
Tim Peters | fc35de4 | 2001-03-02 01:48:16 +0000 | [diff] [blame] | 45 | compile_and_check(prog_text_3) |
Jeremy Hylton | 2922ea8 | 2001-02-28 23:49:19 +0000 | [diff] [blame] | 46 | |
| 47 | prog_text_4 = """ |
| 48 | global x |
| 49 | x = 2 |
| 50 | """ |
Tim Peters | fc35de4 | 2001-03-02 01:48:16 +0000 | [diff] [blame] | 51 | compile_and_check(prog_text_4, 0) |