From cb15ec2e5d8e788c3b392ce6affb308ab4a7c34a Mon Sep 17 00:00:00 2001 From: Sebastian Noack Date: Mon, 23 Nov 2015 12:28:26 +0000 Subject: [PATCH 1/3] Make one_line_regex usable as module --- one_line_regex.py | 9 +++++---- 1 file changed, 5 insertions(+), 4 deletions(-) diff --git a/one_line_regex.py b/one_line_regex.py index 19b679e..1a542cc 100644 --- a/one_line_regex.py +++ b/one_line_regex.py @@ -18,7 +18,8 @@ def magic_match(pattern, target): return result -if magic_match(r'[abcde]+', sys.argv[1]): - print 'Your match was %r' % match.group(0) -else: - print 'There was no match' +if __name__ == '__main__': + if magic_match(r'[abcde]+', sys.argv[1]): + print 'Your match was %r' % match.group(0) + else: + print 'There was no match' From 2a374eed33a8956885bd8ce533fe1e9383a45e5d Mon Sep 17 00:00:00 2001 From: Sebastian Noack Date: Mon, 23 Nov 2015 15:35:32 +0000 Subject: [PATCH 2/3] Make match_magic() assign to the global scope --- one_line_regex.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/one_line_regex.py b/one_line_regex.py index 1a542cc..993b612 100644 --- a/one_line_regex.py +++ b/one_line_regex.py @@ -9,12 +9,12 @@ def magic_match(pattern, target): """ Match a regex against a target string. - Assign the result to a 'match' variable in the *caller's scope*. + Assign the result to a 'match' variable in the *caller's global scope*. """ frame = sys._getframe(1) result = re.match(pattern, target) # This is properly, properly evil. Don't do this: - frame.f_locals['match'] = result + frame.f_globals['match'] = result return result From 0adaada87068a2c63d211f3fad24357a691d34e2 Mon Sep 17 00:00:00 2001 From: Sebastian Noack Date: Mon, 23 Nov 2015 15:36:30 +0000 Subject: [PATCH 3/3] Pass all arguments from magic_match() to re.match --- one_line_regex.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/one_line_regex.py b/one_line_regex.py index 993b612..ecf6ddc 100644 --- a/one_line_regex.py +++ b/one_line_regex.py @@ -5,14 +5,14 @@ import sys -def magic_match(pattern, target): +def magic_match(*args, **kwargs): """ Match a regex against a target string. Assign the result to a 'match' variable in the *caller's global scope*. """ frame = sys._getframe(1) - result = re.match(pattern, target) + result = re.match(*args, **kwargs) # This is properly, properly evil. Don't do this: frame.f_globals['match'] = result return result