Python Forum
wanted: regex or code to find valide def statements in a line
Thread Rating:
  • 1 Vote(s) - 1 Average
  • 1
  • 2
  • 3
  • 4
  • 5
wanted: regex or code to find valide def statements in a line
#10
Using compile() is more robust that exec()
>>> source = "def spam(ham=[n for n in range(1, dividend+1) if dividend % n == 0]):\n"
>>> source = source.rstrip('\n') + 'pass\n'
>>> result = compile(source, '<string>', mode='single')
<code object <module> at 0x7f33bbb89420, file "<string>", line 1>
Now with an invalid line
>>> source = "def spam(**ham, *eggs):\n"
>>> source = source.rstrip('\n') + 'pass\n'
>>> result = compile(source, '<string>', mode='single')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<string>", line 1
    def spam(**ham, *eggs):pass
                  ^
SyntaxError: invalid syntax
Reply


Messages In This Thread
RE: wanted: regex or code to find valide def statements in a line - by Gribouillis - Mar-16-2020, 12:32 PM

Possibly Related Threads…
Thread Author Replies Views Last Post
  python code wanted: grep IP address Skaperen 7 6,265 Jul-09-2018, 05:25 AM
Last Post: Skaperen
  code wanted, but don't expect me to do it Skaperen 0 2,135 Jul-07-2018, 10:50 PM
Last Post: Skaperen
  command line progam wanted: clock Skaperen 2 2,772 Apr-18-2018, 06:54 AM
Last Post: Gribouillis
  code wanted: file splicing Skaperen 10 6,605 Mar-28-2018, 12:13 AM
Last Post: Skaperen
  looking 4 py code: line up columns Skaperen 8 7,989 Jan-09-2017, 05:15 AM
Last Post: Skaperen

Forum Jump:

User Panel Messages

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