Thursday, February 14, 2008

[Python]Eliminate assignment before conditional statement

Python doesn't allow to write a statement in a condition clause.
The limitation keeps beginners away from the well-known bug;
using an assignment while thay want to evaluate equality of two values.
However, it is a little pain to be forced an assignment before a conditional statement for me as below.


import re

data = "aaaabbbbaaaa"

m = re.search("b+", data)
if m:
print "'b+' is found at", m.start()


One possible solution is introducing a stack.
By using my 'bigstack' library you can write as below.


import re
import bigstack

data = "aaaabbbbaaaa"

if push(re.search("b+", data)):
print "'b+' is found at", pop().start()


The library introduces two function 'push' and 'pop' to the built-in namespace. You may easily imagine how it works. And the temporary variable 'm' is no longer needed.

The source code of the 'bigstack' library is as below. It is very simple.
I doesn't think it is the perfect solution, but it could make your code more pretty especially in a 'while' statement.


"""bigstack.py: singleton stack to eliminate temporary variables"""

import __builtin__

BIG_STACK = []

def push(x):
BIG_STACK.append(x)
return x

def pop():
return BIG_STACK.pop()

__builtin__.__dict__.update(
push=push,
pop=pop
)


-----
p.s.
I'm sorry. It requires extra "else" clause to pop the value. worthless...

No comments: