S
Steve Howell
I have been reading the thread "while expression feature proposal,"
and one of the interesting outcomes of the thread is the idea that
Python could allow you to attach names to subexpressions, much like C
allows. In C you can say something like this:
tax_next_year = (new_salary = salary * (1 + raise)) * tax_rate
To avoid the "=" pitfall, folks have proposed something like this for
Python:
tax_next_year = ((salary * (1 + raise)) as new_salary) * tax_rate
print new_salary, tax_next_year
The basic rule in Python is that you can only do one assignment per
line of code, which generally forces you to write more readable code
IMHO:
new_salary = salary * (1 + raise)
tax_next_year = new_salary * tax_rate
print new_salary, tax_next_year
The above code is slightly more verbose than the "as" proposal would
permit, but the latter code is arguably easier for a human to parse,
and it's also very amenable to print debugging and/or defensive
coding:
new_salary = salary * (1 + raise)
print new_salary
assert new_salary > salary
tax_next_year = new_salary * tax_rate
print new_salary, tax_next_year
If the problem statement is "How do I name subexpression?", then
Python already has a clear path--break your code up into multiple
lines. I'm wondering where this simple solution really breaks down
from a readability perspective. Perhaps with short-circuited boolean
expressions?
and one of the interesting outcomes of the thread is the idea that
Python could allow you to attach names to subexpressions, much like C
allows. In C you can say something like this:
tax_next_year = (new_salary = salary * (1 + raise)) * tax_rate
To avoid the "=" pitfall, folks have proposed something like this for
Python:
tax_next_year = ((salary * (1 + raise)) as new_salary) * tax_rate
print new_salary, tax_next_year
The basic rule in Python is that you can only do one assignment per
line of code, which generally forces you to write more readable code
IMHO:
new_salary = salary * (1 + raise)
tax_next_year = new_salary * tax_rate
print new_salary, tax_next_year
The above code is slightly more verbose than the "as" proposal would
permit, but the latter code is arguably easier for a human to parse,
and it's also very amenable to print debugging and/or defensive
coding:
new_salary = salary * (1 + raise)
print new_salary
assert new_salary > salary
tax_next_year = new_salary * tax_rate
print new_salary, tax_next_year
If the problem statement is "How do I name subexpression?", then
Python already has a clear path--break your code up into multiple
lines. I'm wondering where this simple solution really breaks down
from a readability perspective. Perhaps with short-circuited boolean
expressions?