Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
expression vs statement
#1
given a string with a snippet of Python code, is there an easy way to determine if it is an expression or a statement or group of statements like a script?
Tradition is peer pressure from dead people

What do you call someone who speaks three languages? Trilingual. Two languages? Bilingual. One language? American.
Reply
#2
Sure, you can try compiling it and see if you get a SyntaxError:
>>> # eval mode can only compile expressions
>>> compile('a = 1', '', 'eval')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "", line 1
    a = 1
      ^
SyntaxError: invalid syntax
>>>
>>> # single mode can only compile a single statement
>>> script = '''
... a = 1
... b = 3
... c = a + b'''
>>> compile(script, '', 'single')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "", line 2
    a = 1
         ^
SyntaxError: multiple statements found while compiling a single statement
>>>
>>> # exec can compile any valid python code
>>> compile(script, '', 'exec')
<code object <module> at 0x000001EAC0789240, file "", line 2>
Skaperen and Gribouillis like this post
Reply


Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020