Google Groups no longer supports new Usenet posts or subscriptions. Historical content remains viewable.
Dismiss

New syntax for blocks

3 views
Skip to first unread message

r

unread,
Nov 10, 2009, 2:23:35 PM11/10/09
to
Forgive me if i don't properly explain the problem but i think the
following syntax would be quite beneficial to replace some redundant
"if's" in python code.

if something_that_returns_value() as value:
#do something with value

# Which can replace the following syntactical construct...

value = something_that_returns_value()
if value:
#do something with value

i dunno, just seems to make good sense. You save one line of code but
more importantly one indention level. However i have no idea how much
trouble the implementation would be? Now i know you could write a
function and do the following to forgo the indention...

value = something_that_returns_value()
if not value:
return
#do something with value

....but that's even uglier and i would like the construct to work in
both sinlge 'ifs' and also conditional's Now some might say...Whats
the big deal, you only save one line of code?...True, but if you can
save one line of code 100 or 1000 times how many lines of code is that
my inquisitive friend? ;-)

Robert Latest

unread,
Nov 10, 2009, 3:08:14 PM11/10/09
to
r wrote:
> Forgive me if i don't properly explain the problem but i think the
> following syntax would be quite beneficial to replace some redundant
> "if's" in python code.
>
> if something_that_returns_value() as value:
> #do something with value
>
> # Which can replace the following syntactical construct...
>
> value = something_that_returns_value()
> if value:
> #do something with value
>
> i dunno, just seems to make good sense. You save one line of code but
> more importantly one indention level.

Typical case in matching regexes. But where do we save an indentation
level?

Also it's not the "if" that is (if at all) redundant here but the assignment.

robert

Bearophile

unread,
Nov 10, 2009, 3:45:13 PM11/10/09
to
r:

> i think the following syntax would be quite beneficial
> to replace some redundant "if's" in python code.

http://python.org/dev/peps/pep-3003/

bearophile

steve

unread,
Nov 10, 2009, 3:45:37 PM11/10/09
to r, pytho...@python.org
On 11/11/2009 02:05 AM, steve wrote:
> Hi,
>
> On 11/11/2009 12:53 AM, r wrote:
>> [...snip...]

>> i dunno, just seems to make good sense. You save one line of code but
>> more importantly one indention level. However i have no idea how much
>> trouble the implementation would be?
> I guess the problem would be that this would go against the (design ?) principle
> of not evaluating functions in the 'if' conditional part, because it would lead

^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ gah !! sorry, what was I thinking ??
That is just not true !! Anyways, at least the assignments not being allowed bit
is true.


cheers,
- steve

--
random non tech spiel: http://lonetwin.blogspot.com/
tech randomness: http://lonehacks.blogspot.com/
what i'm stumbling into: http://lonetwin.stumbleupon.com/

steve

unread,
Nov 10, 2009, 3:49:03 PM11/10/09
to pytho...@python.org
Hi,

On 11/11/2009 12:53 AM, r wrote:

> Forgive me if i don't properly explain the problem but i think the
> following syntax would be quite beneficial to replace some redundant
> "if's" in python code.
>
> if something_that_returns_value() as value:
> #do something with value
>
> # Which can replace the following syntactical construct...
>
> value = something_that_returns_value()
> if value:
> #do something with value
>
> i dunno, just seems to make good sense. You save one line of code but
> more importantly one indention level. However i have no idea how much
> trouble the implementation would be?

I guess the problem would be that this would go against the (design ?) principle
of not evaluating functions in the 'if' conditional part, because it would lead

to statements such as:

if something(someother(sumsuch() + thisthing())) + ... == value:

also, assignment in the 'if' statement was consciously avoided, if I am not
mistaken.

However, the same 'effect' can be obtained with the 'with' statement:
------------------------------------------------
class something_that_returns_value:
def __init__(self, x):
# do something with x, self.value is what ought to be 'returned'
self.value = x

def __enter__(self):
if self.value:
return self.value
else:
return ValueError()

def __exit__(self, type, value, traceback):
return True


with something_that_returns_value(1) as value:
print value

with something_that_returns_value(0) as value:
print value

with something_that_returns_value(False) as value:
value + 10
# never reach here
value.dosomething()

with something_that_returns_value([1,2,3]) as value:
value.append(4)
print value

------------------------------------------------
nasty huh ? :)

r

unread,
Nov 10, 2009, 4:59:24 PM11/10/09
to
On Nov 10, 2:08 pm, Robert Latest <boblat...@yahoo.com> wrote:
(..snip..)

> Also it's not the "if" that is (if at all) redundant here but the assignment.

Not exactly. The assignment happens only once just as the boolean
check of "if <value>" happens once. The redundancy is in validating
the existence of a truthful value contained in a variable after
assignment of a value to that same variable. It's like putting on your
tennis shoes and then asking yourself 'am i wearing tennis shoes?'. Of
course we all know *why* we must verify the existence of value
afterward and the shoe analogy doesn't translate 1:1 to programming.
It's more like...

shoes = grab_a_pair_of_shoes_or_none_and_apply_to_feet()
if shoes:
shoes.this()
shoes.that()

Now did we find a pair of shoes or did we fail because the lights were
out and all we accomplished was to toil around in the closet for half
an hour bumping our head before finally giving up and returning empty
handed?

Just thinking out loud here...what if variable assignments could
return a value... hmmm? Not to them selfs of course but to a caller,
like an if statement...

if a=openfile:
# do something with a

(if(a.__eq__(openfile)))

Python would need to stuff the value of openfile into "a", then add
the variable "a" to the proper namespace, then evaluate if "a" is
True. This would read more naturally than even my first postulation. I
bet it would confuse the crap out of noobies though!

So basically with the new syntax what your saying is this:
if the value of this expression bools to False, toss it away because i
don't need it, else assign the value to a local variable and run the
block. Basically your encaspulating an if..else block in one line of
code.


Steven D'Aprano

unread,
Nov 10, 2009, 10:12:55 PM11/10/09
to

I knew it wouldn't take long for people to start responding to any
proposal with "don't bother, there's a moratorium".

Of course in this case, the correct response would have been "don't
bother, it's a stupid idea, moratorium or no moratorium".

Hint to would-be language designers: if you start off by claiming that a
new feature will save an indent level, when in fact it *doesn't* save an
indent level, you can save yourself from embarrassment by pressing Close
on your post instead of Send.

--
Steven

Carl Banks

unread,
Nov 10, 2009, 11:02:03 PM11/10/09
to
On Nov 10, 11:23 am, r <rt8...@gmail.com> wrote:
> if something_that_returns_value() as value:
>     #do something with value

Been proposed before. No one has bothered to write a PEP for it, so I
can't say for sure how the Python gods would react, but I suspect a
"meh, don't think it's important enough". This, even though it's more
useful than you are giving it credit for. It's a minor improvement.


Carl Banks

Carl Banks

unread,
Nov 10, 2009, 11:13:21 PM11/10/09
to
On Nov 10, 7:12 pm, Steven D'Aprano

<ste...@REMOVE.THIS.cybersource.com.au> wrote:
> On Tue, 10 Nov 2009 12:45:13 -0800, Bearophile wrote:
> > r:
>
> >> i think the following syntax would be quite beneficial to replace some
> >> redundant "if's" in python code.
>
> >http://python.org/dev/peps/pep-3003/
>
> I knew it wouldn't take long for people to start responding to any
> proposal with "don't bother, there's a moratorium".
>
> Of course in this case, the correct response would have been "don't
> bother, it's a stupid idea, moratorium or no moratorium".

r didn't actually give a good example. Here is case where it's
actually useful. (Pretend the regexps are too complicated to be
parsed with string method.)

if re.match(r'go\s+(north|south|east|west)',cmd) as m:
hero.move(m.group(1))
elif re.match(r'take\s+(\w+)',cmd) as m:
hero.pick_up(m.group(1))
elif re.match(r'drop\s+(\w+)',cmd) as m:
here.put_Down(m.group(1))

I wouldn't mind seeing this in Python for this exact use case,
although I'd rather the syntax to be more like the following so that
you can bind something other than the condition if need be.

if m with m as re.match(regexp,command):

Moot point for the next two years, and probably forever as I doubt it
would ever happen.

Carl Banks

r

unread,
Nov 10, 2009, 11:23:03 PM11/10/09
to
On Nov 10, 9:12 pm, Steven D'Aprano
<ste...@REMOVE.THIS.cybersource.com.au> wrote:
(..snip..)

> Hint to would-be language designers: if you start off by claiming that a
> new feature will save an indent level, when in fact it *doesn't* save an
> indent level, you can save yourself from embarrassment by pressing Close
> on your post instead of Send.

Does anyone out there know the textual smiley for conveying an
overwhelming feeling of embarrassment? Also may want to send the one
for feeling of confusion too ;-)

Steven D'Aprano

unread,
Nov 11, 2009, 12:37:13 AM11/11/09
to
On Tue, 10 Nov 2009 20:13:21 -0800, Carl Banks wrote:

> On Nov 10, 7:12 pm, Steven D'Aprano
> <ste...@REMOVE.THIS.cybersource.com.au> wrote:
>> On Tue, 10 Nov 2009 12:45:13 -0800, Bearophile wrote:
>> > r:
>>
>> >> i think the following syntax would be quite beneficial to replace
>> >> some redundant "if's" in python code.
>>
>> >http://python.org/dev/peps/pep-3003/
>>
>> I knew it wouldn't take long for people to start responding to any
>> proposal with "don't bother, there's a moratorium".
>>
>> Of course in this case, the correct response would have been "don't
>> bother, it's a stupid idea, moratorium or no moratorium".
>
> r didn't actually give a good example. Here is case where it's actually
> useful. (Pretend the regexps are too complicated to be parsed with
> string method.)
>
> if re.match(r'go\s+(north|south|east|west)',cmd) as m:
> hero.move(m.group(1))
> elif re.match(r'take\s+(\w+)',cmd) as m:
> hero.pick_up(m.group(1))
> elif re.match(r'drop\s+(\w+)',cmd) as m:
> here.put_Down(m.group(1))

This is where a helper function is good. You want a dispatcher:


COMMANDS = {
r'go\s+(north|south|east|west)': hero.move,
r'take\s+(\w+)': hero.pick_up,
r'drop\s+(\w+)': here.put_Down,
}

def dispatch(cmd):
for regex in COMMANDS:
m = re.match(regex, cmd)
if m:
COMMANDS[regex](m.group(1))
break

dispatch(cmd)

If you need the regexes to be tested in a specific order, change the dict
to an OrderedDict, or use a list of tuples and the obvious change to the
for loop.

--
Steven

Terry Reedy

unread,
Nov 11, 2009, 12:44:55 AM11/11/09
to pytho...@python.org
Carl Banks wrote:
>
> r didn't actually give a good example. Here is case where it's
> actually useful. (Pretend the regexps are too complicated to be
> parsed with string method.)
>
> if re.match(r'go\s+(north|south|east|west)',cmd) as m:
> hero.move(m.group(1))
> elif re.match(r'take\s+(\w+)',cmd) as m:
> hero.pick_up(m.group(1))
> elif re.match(r'drop\s+(\w+)',cmd) as m:
> here.put_Down(m.group(1))

The effect of this proposal can already be accomplished with a 'pocket'
class as has been posted before and again in a slightly different form
in Steve's post.

tjr

r

unread,
Nov 11, 2009, 2:00:09 AM11/11/09
to
On Nov 10, 2:49 pm, steve <st...@lonetwin.net> wrote:
(..snip..)

> However, the same 'effect' can be obtained with the 'with' statement:
(..snip..)

Hardly!,Here is an interactive session with your test case
#----------------------------------------------------------#


>>> class something_that_returns_value:
def __init__(self, x):
# do something with x, self.value is what ought to be
'returned'
self.value = x
def __enter__(self):
if self.value:
return self.value
else:
return ValueError()
def __exit__(self, type, value, traceback):
return True

>>> with something_that_returns_value(1) as value:
print 'block'

block
>>> with something_that_returns_value(0) as value:
print 'block'

block
>>> with something_that_returns_value(False) as value:
print 'block'

block


>>> with something_that_returns_value([1,2,3]) as value:

print 'block'

block
#----------------------------------------------------------#

The block obviously executes every time no matter what value is
returned from something_that_returns_value(*). The with statement is
meant to only cleanup an exception in a "nice-clean-way" not to
evaluate a variable assignment as evidenced by this simple testing of
your code. If anything executes in the block following the "if" (when
the assignment value is None) it undermines the whole reason for using
the new syntax in the first place!

I think what has escaped everyone (including myself until my second
post) is the fact that what really needs to happen is for variable
*assignments* to return a boolean to any "statements" that evaluate
the assignment -- like in an "if" or "elif" construct. The current
"with" statement cannot replace that action and was never meant for
such things.

if range(0) as var:
#python will never execute even one line
#in this block because bool(var) == None
#also since bool(var) equals None, the
#variable "var" will never be created!

elif range(10) as var:
#this block will execute and the variable "var"
#will be added to appropriate namespace containing
#a list of 10 ints

var = 100 #var is still available in this namespace!


Very clean, very elegant solution to a messy problem that pops up in
python code quite often. It not only saves one distracting line of
code per usage but makes the code more readable. If there is an
existing solution, Steve's is not it.

Steven D'Aprano

unread,
Nov 11, 2009, 2:25:35 AM11/11/09
to
On Tue, 10 Nov 2009 23:00:09 -0800, r wrote:

> I think what has escaped everyone (including myself until my second
> post) is the fact that what really needs to happen

Why?


> is for variable
> *assignments* to return a boolean to any "statements" that evaluate the
> assignment -- like in an "if" or "elif" construct.

I don't even understand what that means.


> The current "with"
> statement cannot replace that action and was never meant for such
> things.
>
> if range(0) as var:
> #python will never execute even one line
> #in this block because bool(var) == None


No, that's impossible. bool() always returns True or False, not None.


> #also since bool(var) equals None, the

Incorrect.

>>> True == None
False
>>> False == None
False

> #variable "var" will never be created!

That will cause no end of trouble.


if range(N) as var:
do_something_with_var()
if var:
print "Oops, this blows up if N <= 0"

Conditional assignments are a terrible idea.

> elif range(10) as var:
> #this block will execute and the variable "var"
> #will be added to appropriate namespace containing
> #a list of 10 ints
>
> var = 100 #var is still available in this namespace!
>
>
> Very clean, very elegant solution to a messy problem that pops up in
> python code quite often.


You haven't actually explained what the messy problem is.


var = range(N)
if var:
...

is not a messy problem. It's perfectly reasonable. If you need to do two
things with a value, you assign it to a name first:

var = range(N)
p = var.index(5)
var.append(42)


x = func(10)
y = x + 1
z = x*2


x = func(10)
if x:
y = x + 1


Why is the third example, with an if... test, so special that it needs
special syntax to make it a two-liner?


Would you suggest we can write this?


# instead of var = range(N)
p = range(N).index(5) as var # var might be range(N), or undefined.
var.append(42)

> It not only saves one distracting line of code
> per usage but makes the code more readable.

What distracting line of code?

--
Steven

r

unread,
Nov 11, 2009, 3:08:58 AM11/11/09
to
On Nov 11, 1:25 am, Steven D'Aprano
<ste...@REMOVE.THIS.cybersource.com.au> wrote:
(snip)

> Incorrect.
> >>> True == None
> False
> >>> False == None
> False

Of course i meant True/False but my fingers were thinking None at the
time. And besides if i don't make a mistake here or there what ever
would you do with your time? ;-)
Seven += 1

> >    #variable "var" will never be created!
> That will cause no end of trouble.
> if range(N) as var:
>     do_something_with_var()
> if var:
>     print "Oops, this blows up if N <= 0"
> Conditional assignments are a terrible idea.

Yea it's called a NameError. Would it not also blow up in the current
state of syntax usage?

if var:
print 'var'

Traceback (most recent call last):
File "<pyshell#45>", line 1, in <module>
if var:
NameError: name 'var' is not defined

Steven -= 1

> Why is the third example, with an if... test, so special that it needs
> special syntax to make it a two-liner?

...because Beautiful is better than ugly.

> Would you suggest we can write this?
> # instead of var = range(N)
> p = range(N).index(5) as var  # var might be range(N), or undefined.
> var.append(42)

No if you read my post my usage of this syntax only includes "if" and
"elif" constructs and nothing "else" because usage outside of such a
"truth-seeking" construct is pointless.

print Steven -> 0
Hmm, just as i suspected.

Steven D'Aprano

unread,
Nov 11, 2009, 3:37:35 AM11/11/09
to
On Wed, 11 Nov 2009 00:08:58 -0800, r wrote:


>> >    #variable "var" will never be created!
>> That will cause no end of trouble.
>> if range(N) as var:
>>     do_something_with_var()
>> if var:
>>     print "Oops, this blows up if N <= 0"
>> Conditional assignments are a terrible idea.
>
> Yea it's called a NameError. Would it not also blow up in the current
> state of syntax usage?

No.


> if var:
> print 'var'
>
> Traceback (most recent call last):
> File "<pyshell#45>", line 1, in <module>
> if var:
> NameError: name 'var' is not defined


You missed a line:

var = range(N)
if var:
...

The problem isn't the if statement, it is the conditional assignment.
Sometimes "x as y" creates y, sometimes it doesn't, according to some
mysterious rule something to do without whether the assignment is true or
false, whatever that means.

>> Why is the third example, with an if... test, so special that it needs
>> special syntax to make it a two-liner?
>
> ...because Beautiful is better than ugly.

I can quote the Zen too:

Special cases aren't special enough to break the rules.

You haven't demonstrated that your construct is "beautiful", or the
existing way of writing it is "ugly".

# apparently not ugly
x = func()


y = x + 1

z = 2*x

# also not ugly
var = range(N)
var.append(42)
find(23, var)

# still not ugly
var = range(N)
for x in var:
do_something_with(x, var)

# not ugly
var = MyClass()
with var.magic as x:
process(var)


# why is this ugly?


var = range(N)
if var:

process(var)

>> Would you suggest we can write this?
>> # instead of var = range(N)
>> p = range(N).index(5) as var  # var might be range(N), or undefined.
>> var.append(42)
>
> No if you read my post my usage of this syntax only includes "if" and
> "elif" constructs and nothing "else" because usage outside of such a
> "truth-seeking" construct is pointless.

What's so special about "truth-seeking"?

for x in range(N) as var:
do_something_with(x, var)


That would save a line too, it would behave exactly as you specified, and
it uses virtually the identical syntax: "expr as name".

--
Steven

r

unread,
Nov 11, 2009, 5:50:37 AM11/11/09
to
On Nov 11, 2:37 am, Steven D'Aprano

<ste...@REMOVE.THIS.cybersource.com.au> wrote:
> On Wed, 11 Nov 2009 00:08:58 -0800, r wrote:

> > Yea it's called a NameError. Would it not also blow up in the current
> > state of syntax usage?
>
> No.
>
> > if var:
> >     print 'var'
>
> > Traceback (most recent call last):
> >   File "<pyshell#45>", line 1, in <module>
> >     if var:
> > NameError: name 'var' is not defined
>
> You missed a line:
>
> var = range(N)
> if var:

Oh i get it now! If i assign a valid value to a variable the variable
is also valid...thats...thats... GENUIS! *sarcasm*

> The problem isn't the if statement, it is the conditional assignment.
> Sometimes "x as y" creates y, sometimes it doesn't, according to some
> mysterious rule something to do without whether the assignment is true or
> false, whatever that means.

i don't find True or False, Black or White, 1 or 0, Alpha or Omega to
be mysterious...? If you still cannot grasp this simple concept then i
fear i may not be able to help you understand Steven.

(snip: excessive inane blubbering)

> > No if you read my post my usage of this syntax only includes "if" and
> > "elif" constructs and nothing "else" because usage outside of such a
> > "truth-seeking" construct is pointless.
>
> What's so special about "truth-seeking"?
>
> for x in range(N) as var:
>     do_something_with(x, var)

You could do that but why would you want to. A "for x in range(N)" is
just so you can loop N times. And since changing the values in a list
whilst looping over it is the sport of fools then what usefulness
would a variable be for such a construct? You have failed to prove the
usefulness of this syntax Steven.

I suggest you go back and read over my posts again and then marinate
on the contents for a while. THEN come back with an argument based in
reality and we will try again...You know at one time i actually
considered you a formidable foe, well these times they are a chang'in
right Dylan?

Carl Banks

unread,
Nov 11, 2009, 6:52:45 AM11/11/09
to
On Nov 10, 9:37 pm, Steven D'Aprano

<ste...@REMOVE.THIS.cybersource.com.au> wrote:
> On Tue, 10 Nov 2009 20:13:21 -0800, Carl Banks wrote:
> > On Nov 10, 7:12 pm, Steven D'Aprano
> > <ste...@REMOVE.THIS.cybersource.com.au> wrote:
> >> On Tue, 10 Nov 2009 12:45:13 -0800, Bearophile wrote:
> >> > r:
>
> >> >> i think the following syntax would be quite beneficial to replace
> >> >> some redundant "if's" in python code.
>
> >> >http://python.org/dev/peps/pep-3003/
>
> >> I knew it wouldn't take long for people to start responding to any
> >> proposal with "don't bother, there's a moratorium".
>
> >> Of course in this case, the correct response would have been "don't
> >> bother, it's a stupid idea, moratorium or no moratorium".
>
> > r didn't actually give a good example.  Here is case where it's actually
> > useful.  (Pretend the regexps are too complicated to be parsed with
> > string method.)
>
> > if re.match(r'go\s+(north|south|east|west)',cmd) as m:
> >     hero.move(m.group(1))
> > elif re.match(r'take\s+(\w+)',cmd) as m:
> >     hero.pick_up(m.group(1))
> > elif re.match(r'drop\s+(\w+)',cmd) as m:
> >     here.put_Down(m.group(1))
>
> This is where a helper function is good. You want a dispatcher:

No I really don't. I want to be able to see the action performed
adjacent to the test, and not have to scroll up to down ten pages to
find whatever function it dispatched to.


Carl Banks

Carl Banks

unread,
Nov 11, 2009, 7:00:09 AM11/11/09
to
On Nov 10, 9:44 pm, Terry Reedy <tjre...@udel.edu> wrote:
> Carl Banks wrote:
>
> > r didn't actually give a good example.  Here is case where it's
> > actually useful.  (Pretend the regexps are too complicated to be
> > parsed with string method.)
>
> > if re.match(r'go\s+(north|south|east|west)',cmd) as m:
> >     hero.move(m.group(1))
> > elif re.match(r'take\s+(\w+)',cmd) as m:
> >     hero.pick_up(m.group(1))
> > elif re.match(r'drop\s+(\w+)',cmd) as m:
> >     here.put_Down(m.group(1))
>
> The effect of this proposal can already be accomplished with a 'pocket'
> class

Nice metaphorical name.


> as has been posted before and again in a slightly different form
> in Steve's post.

I'm well aware of it, but I didn't think the proposal deserved to be
called stupid when it was a reasonable solution to a real need, even
though a workable and less intrusive option exists.


Carl Banks

steve

unread,
Nov 11, 2009, 8:10:03 AM11/11/09
to r, pytho...@python.org
Hi,

On 11/11/2009 12:30 PM, r wrote:
> [...snip...]


> I think what has escaped everyone (including myself until my second
> post) is the fact that what really needs to happen is for variable
> *assignments* to return a boolean to any "statements" that evaluate
> the assignment -- like in an "if" or "elif" construct. The current
> "with" statement cannot replace that action and was never meant for
> such things.
>

True. It escaped me too that the assignment was happening and I was only relying
on the side-effect to break out of the with statement. So, I'm sorry.

>
> Very clean, very elegant solution to a messy problem that pops up in
> python code quite often. It not only saves one distracting line of
> code per usage but makes the code more readable. If there is an
> existing solution, Steve's is not it.

However, if it is /only/ about saving that one 'distracting' line of the final
code that you are concerned about (which I think is the case), how about:

-----------------------------------------------------
def deco(f):
def assign(x):
if x:
globals()['value'] = f(x)
return True
else:
globals()['value'] = False
return assign

@deco
def something_that_returns_value(x):
# do something with x and return a value
return x

if something_that_returns_value(1) and value:
print value

if something_that_returns_value(0) and value:
print value

# or if you cannot decorate something_that_returns_value in it's definition
# for instance, a method from another module, then ...

if deco(something_that_returns_value)(0) and value:
print value

# Note that we've just siphoned off the assignment elsewhere. One problem
# tho' is, irrespective of the conditional code being entered 'value' would
# be initialized, which is what your ...
#
# if something_that_returns_value(x) as value:
#
# ... would also have done (if such a thing existed).
# To avoid this side effect we could also do:

if (something_that_returns_value(0) and value) or globals().pop('value'):
print value

# ...but that is beginning to look too much like the perl.

Well, that's all i could think of to overcome one line of extra code.

samwyse

unread,
Nov 11, 2009, 8:11:21 AM11/11/09
to
On Nov 10, 1:23 pm, r <rt8...@gmail.com> wrote:
> Forgive me if i don't properly explain the problem but i think the
> following syntax would be quite beneficial to replace some redundant
> "if's" in python code.
>
> if something_that_returns_value() as value:
>     #do something with value
>
> # Which can replace the following syntactical construct...
>
> value = something_that_returns_value()
> if value:
>     #do something with value

I don't like the proposed syntax. I know, it's copied from the "with"
statement, but it makes the assignment look like an afterthought.
Plus, it's not good English when read aloud.

If you want something useful, wait two years for the moratorium to
expire and then figure out how to augment the "for" statement with an
"if" clause, as is currently done in comprehensions. In other words,
instead of this:
"for" target_list "in" expression_list ":" suite
let's have this:
"for" target_list "in" expression_list [ "if" expression_nocond ]
":" suite

You don't save much typing, but you really do save one indention
level. OTOH, I can see the use of an else-clause following the 'for'
as being even more confusing to anyone new to the language.

And there's also the fact that an expression_list consists of
conditional_expressions, which potentially use "if". You could
probably get the parser to figure it out based on the presence of the
"else" clause, but it wouldn't be easy.

Robert Latest

unread,
Nov 11, 2009, 2:01:33 PM11/11/09
to
r wrote:
> Just thinking out loud here...what if variable assignments could
> return a value... hmmm? Not to them selfs of course but to a caller,
> like an if statement...
>
> if a=openfile:
> # do something with a

That's like in C. I sometimes miss it in Python.

robert

Terry Reedy

unread,
Nov 11, 2009, 2:33:09 PM11/11/09
to pytho...@python.org
Steven D'Aprano wrote:

This is the first time I have seen this explanation and justification of
the status quo. Thanks for posting it so clearly.

...


> What's so special about "truth-seeking"?

as a second use


>
> for x in range(N) as var:
> do_something_with(x, var)
>
>
> That would save a line too, it would behave exactly as you specified, and
> it uses virtually the identical syntax: "expr as name".

I know that Guido does not want to generalize 'as' as a substitute for
'=' except where really necessary. The three current uses in import,
with, and except statements are necessary because the object being bound
is produced in the statement itself and so the assignment cannot be
separated into a prior proper assignment statement.

Terry Jan Reedy

Steven D'Aprano

unread,
Nov 11, 2009, 7:12:08 PM11/11/09
to
On Wed, 11 Nov 2009 03:52:45 -0800, Carl Banks wrote:

>> This is where a helper function is good. You want a dispatcher:
>
> No I really don't. I want to be able to see the action performed
> adjacent to the test, and not have to scroll up to down ten pages to
> find whatever function it dispatched to.


Then re-write the dispatcher to return a tuple (match_object,
method_to_call) and then call them there at the spot.


--
Steven

Steven D'Aprano

unread,
Nov 11, 2009, 7:17:34 PM11/11/09
to
On Wed, 11 Nov 2009 04:00:09 -0800, Carl Banks wrote:

>> as has been posted before and again in a slightly different form in
>> Steve's post.
>
> I'm well aware of it, but I didn't think the proposal deserved to be
> called stupid when it was a reasonable solution to a real need, even
> though a workable and less intrusive option exists.

Fair enough, I was feeling grumpy at the time. Perhaps "stupid" was
unfair. Perhaps.


--
Steven

Carl Banks

unread,
Nov 11, 2009, 10:04:36 PM11/11/09
to
On Nov 11, 4:12 pm, Steven D'Aprano

Well I don't just want to call a method, so I can't take that advice.
Some actions will do more than just to call a method. And I don't
want to scroll up or down ten screens to see what the actions
associated with the regexp are. A dispatcher is out.

Carl Banks

r

unread,
Nov 12, 2009, 12:07:12 AM11/12/09
to
On Nov 11, 9:04 pm, Carl Banks <pavlovevide...@gmail.com> wrote:
(Carl's reply to Steven's comments...)

> Well I don't just want to call a method, so I can't take that advice.
> Some actions will do more than just to call a method. And I don't
> want to scroll up or down ten screens to see what the actions
> associated with the regexp are. A dispatcher is out.

+1

The if... elif... construct that Carl provided coupled with the
proposed new syntax is much cleaner. And i'm not just saying that
because Steven called my idea stupid, well, *maybe* not? ;-)

PS: Does anyone know the textual smiley for apathy?

Bruno Desthuilliers

unread,
Nov 12, 2009, 3:27:31 PM11/12/09
to
r a �crit :
-snip)

> Just thinking out loud here...what if variable assignments could
> return a value... hmmm? Not to them selfs of course but to a caller,
> like an if statement...
>
> if a=openfile:
> # do something with a

Congratulations, you just reinvented one of the most infamous source of
bugs in C, C++, Java, PHP, javascript and quite a few other languages.
Believe it or not, but not allowing this in Python was a very deliberate
design choice.

Now whether it was a good choice is another troll^Mtopic !-)

Bruno Desthuilliers

unread,
Nov 12, 2009, 3:29:02 PM11/12/09
to
Steven D'Aprano a écrit :
(snip)

> Hint to would-be language designers: if you start off by claiming that a
> new feature will save an indent level, when in fact it *doesn't* save an
> indent level, you can save yourself from embarrassment by pressing Close
> on your post instead of Send.

Mouaaaaaaaa !-)

Thanks Steven, you made my day

(me ---> go back mouaaaaaa)

Bruno Desthuilliers

unread,
Nov 12, 2009, 3:37:48 PM11/12/09
to
r a �crit :

> On Nov 11, 2:37 am, Steven D'Aprano
> <ste...@REMOVE.THIS.cybersource.com.au> wrote:
>> On Wed, 11 Nov 2009 00:08:58 -0800, r wrote:
>
>>> Yea it's called a NameError. Would it not also blow up in the current
>>> state of syntax usage?
>> No.
>>
>>> if var:
>>> print 'var'
>>> Traceback (most recent call last):
>>> File "<pyshell#45>", line 1, in <module>
>>> if var:
>>> NameError: name 'var' is not defined
>> You missed a line:
>>
>> var = range(N)
>> if var:
>
> Oh i get it now! If i assign a valid value to a variable the variable
> is also valid...thats...thats... GENUIS! *sarcasm*

It's not about "assigning a valid value to a variable", it's about the
name being created (or not) in the current namespace, whatever it's
bound to.

r

unread,
Nov 12, 2009, 5:55:12 PM11/12/09
to
On Nov 12, 2:37 pm, Bruno Desthuilliers
<bdesth.quelquech...@free.quelquepart.fr> wrote:

> > Oh i get it now! If i assign a valid value to a variable the variable
> > is also valid...thats...thats... GENUIS! *sarcasm*
>
> It's not about "assigning a valid value to a variable", it's about the
> name being created (or not) in the current namespace, whatever it's
> bound to.

And thats what my sarcasm was alluding to. Steven's argument is moot
because it will blow up either way due to the fact that "value" is non-
existent! Every argument that has been brought forth about how this
will break is just False and basically a bunch of FUD! It just garbage
so you can discredit the idea.

It's actually quite funny when someone as small as me can bring down
the iron curtain of c.l.py.
'''Mr. Gorbachev, Tear down this wall!'''

How about one of you "esteemed" Pythonista's show me a real example
where it will break. Show me (and the world) this H.G Wells
nightmarish scenario you speak of but show no solid proofs. Sorry
chaps, I don't buy snake oil!

Going, Going, Gonnnne, out the park!

PS: And if it were so dangerous why would someone as knowledgeable as
Carl have stepped in and supported it. I think because (like me) Carl
put's the language before sewing circles. I think it's just personal
like all the times before, that's OK, i have very thick skin! If it's
wrong for a good reason i will graciously accept that, but no one has
proven it's non-worth, not yet!

Steven D'Aprano

unread,
Nov 12, 2009, 8:44:22 PM11/12/09
to
On Thu, 12 Nov 2009 21:27:31 +0100, Bruno Desthuilliers wrote:

> Congratulations, you just reinvented one of the most infamous source of
> bugs in C, C++, Java, PHP, javascript and quite a few other languages.
> Believe it or not, but not allowing this in Python was a very deliberate
> design choice.

Oh, but those hundreds of thousands of man-hours lost to bugs caused by
assignment-as-an-expression is nothing compared to the dozens of man-
minutes saved by having one fewer line of code!


*wink*

--
Steven

r

unread,
Nov 12, 2009, 11:10:29 PM11/12/09
to
On Nov 12, 7:44 pm, Steven D'Aprano <st...@REMOVE-THIS-
cybersource.com.au> wrote

> Oh, but those hundreds of thousands of man-hours lost to bugs caused by
> assignment-as-an-expression is nothing compared to the dozens of man-
> minutes saved by having one fewer line of code!

OK, what *if* the variable would only be valid in *that* block and
*that* block only! My first idea was to have the variable avaiable in
the local scope (if that is correct terminology?) so if the
conditional was in global space the value would be available in global
space, alright? You follow me? Now forget all that and observe the
following. ;-)

if value=range(10):
#this block *would* execute and "value" would be a valid name
#but only IN this block!!!
value.append(1)
elif value=fetch(0):
#this block would *never* execute
value.append(1)

value.append(1) -> this throws a NameError


Is that different than how other languages handle "assignment-by-
expression"? Will that avoid the cataclysmic downward spiral you speak
of? I can't see any problems with it AND it can still be applied to
myself and Carl's use cases.

Anybody is welcome to comment...?

Bruno Desthuilliers

unread,
Nov 13, 2009, 3:53:27 PM11/13/09
to
r a �crit :

> On Nov 12, 7:44 pm, Steven D'Aprano <st...@REMOVE-THIS-
> cybersource.com.au> wrote
>> Oh, but those hundreds of thousands of man-hours lost to bugs caused by
>> assignment-as-an-expression is nothing compared to the dozens of man-
>> minutes saved by having one fewer line of code!
>
> OK, what *if* the variable would only be valid in *that* block and
> *that* block only!

Python doesn't have the notion of a "block scope" (or "block namespace").

> My first idea was to have the variable avaiable in
> the local scope (if that is correct terminology?) so if the
> conditional was in global space the value would be available in global
> space, alright? You follow me? Now forget all that and observe the
> following. ;-)
>
> if value=range(10):
> #this block *would* execute and "value" would be a valid name
> #but only IN this block!!!
> value.append(1)
> elif value=fetch(0):
> #this block would *never* execute
> value.append(1)
>
> value.append(1) -> this throws a NameError

Yuck.

>
> Is that different than how other languages handle "assignment-by-
> expression"? Will that avoid the cataclysmic downward spiral you speak
> of?

It's different, but only worse. It doesn't solve the problem of
mystyping "=" instead of "==" - which is the reason why Python's
assignement is not an expression, and it's not even consistent with
mainstream languages that support "assignement as an expression".

> I can't see any problems with it

I do see at least two big ones !-)

Now I don't mean there's not a use case for some "assign and test"
syntax - Carl provided a good one, and indeed there are some cases where
a dispatcher is *not* the simplest and obvious solution. But by all
means, not *this* syntax.

Bruno Desthuilliers

unread,
Nov 13, 2009, 4:20:16 PM11/13/09
to
r a �crit :

> On Nov 12, 2:37 pm, Bruno Desthuilliers
> <bdesth.quelquech...@free.quelquepart.fr> wrote:
>
>>> Oh i get it now! If i assign a valid value to a variable the variable
>>> is also valid...thats...thats... GENUIS! *sarcasm*
>> It's not about "assigning a valid value to a variable", it's about the
>> name being created (or not) in the current namespace, whatever it's
>> bound to.
>
> And thats what my sarcasm was alluding to. Steven's argument is moot
> because it will blow up either way due to the fact that "value" is non-
> existent!

Sorry, but Steve's code, ie:

var = range(100)
if var:
...

will not break - after the first line, the name "var" exists, whether
it's bound to true or false value.

While with your proposal *as it is* (or at least as I and Steve
understood it), the existence of name "var" depends on some
unpredictable condition.

> Every argument that has been brought forth about how this
> will break is just False

Actually, identity testing on True or False is considered a very bad
practice. You really want equality testing <g>

> and basically a bunch of FUD! It just garbage
> so you can discredit the idea.

Please take a deep breath and calm down. There's no conspiracy, no
secret plan, no hidden agenda, and pointing out the shortcomings of a
proposals is definitly not "discredit"ing "the idea".

> It's actually quite funny when someone as small as me can bring down
> the iron curtain of c.l.py.
> '''Mr. Gorbachev, Tear down this wall!'''
>
> How about one of you "esteemed" Pythonista's show me a real example
> where it will break.

Steve did. But I'm afraid you missed his point.

>
> PS: And if it were so dangerous why would someone as knowledgeable as
> Carl have stepped in and supported it.

Carl supported the idea of a syntax for "assignment and test", but
that's not what Steve's comments were about - well, it may be that Steve
also refuses to consider the whole idea, but he still has a good point
wrt/ some shortcoming of your idea in it's current state.

> I think because (like me) Carl
> put's the language before sewing circles. I think it's just personal
> like all the times before,

Well, to be true, you did manage to make a clown of yourself more than
once, so don't be surprised if some people here tend to treat you as one
- even when you come up with something that _may_ have some value.

> that's OK, i have very thick skin! If it's
> wrong for a good reason i will graciously accept that, but no one has
> proven it's non-worth, not yet!

wrong != non-worth. I mean: having some possibly valid use case doesn't
imply the proposed solution is the good one in it's current state. And
pointing out the shortcomings of the proposed solution doesn't imply the
problem is not real neither (now whether it's a critical enough problem
to _require_ a solution is another problem I won't even debate here).

Anyway, just going to personal considerations won't help. If you ever
hope to be taken seriously, first behave as a reasonably sensible and
mature person.

My (hopefully friendly) 2 cents.

r

unread,
Nov 13, 2009, 8:00:53 PM11/13/09
to
On Nov 13, 3:20 pm, Bruno Desthuilliers
<bdesth.quelquech...@free.quelquepart.fr> wrote:
(...snip...)

> > I think because (like me) Carl
> > put's the language before sewing circles. I think it's just personal
> > like all the times before,
>
> Well, to be true, you did manage to make a clown of yourself more than
> once, so don't be surprised if some people here tend to treat you as one
> - even when you come up with something that _may_ have some value.

Well, i must agree with that assessment. There have been some
*interesting* post from me here. I am human and prone to make mistakes
like anyone 0:-)

> My (hopefully friendly) 2 cents.

Thanks, the tone of this message was very good!

But anyway this is all moot now. I received a message last night from
a very intelligent person who i will not name since the message was
only addressed to me (no it's not Guido! I don't want to start any
crazy rumors people!) This "persons" response was *so* intelligent and
informative i was awe struck whilst reading it and concluded i have no
further basis to argue for this syntax change (not at this time
anyway). I would like to post this person's message for all to see but
i will not without their permission. I can now see how the pros *may*
not outweigh the cons and so with that i concede to my opponents.

Anyway, good discussion chaps!

Jonathan Saxton

unread,
Nov 17, 2009, 10:28:36 AM11/17/09
to pytho...@python.org

And if I ever find the genius who had the brilliant idea of using = to mean assignment then I have a particularly nasty dungeon reserved just for him. Also a foul-smelling leech-infested swamp for those language designers and compiler writers who followed his example. (Come to think of it, plagiarizing a bad idea is probably the worse evil.)


--
Steven
--
http://mail.python.org/mailman/listinfo/python-list

MRAB

unread,
Nov 17, 2009, 12:31:18 PM11/17/09
to pytho...@python.org
> And if I ever find the genius who had the brilliant idea of using =
> to mean assignment then I have a particularly nasty dungeon reserved
> just for him. Also a foul-smelling leech-infested swamp for those
> language designers and compiler writers who followed his example.
> (Come to think of it, plagiarizing a bad idea is probably the worse
> evil.)
>
C was derived from BCPL, which used ":=" and "=".

Fortran uses "=" and ".EQ.", probably because (some) earlier autocodes
did.

It's a pity that Guido chose to follow C.

r

unread,
Nov 17, 2009, 1:15:41 PM11/17/09
to
On Nov 17, 9:28 am, Jonathan Saxton <jsax...@appsecinc.com> wrote:

> And if I ever find the genius who had the brilliant idea of using = to mean assignment then I have a particularly nasty dungeon reserved just for him.  Also a foul-smelling leech-infested swamp for those language designers and compiler writers who followed his example.  (Come to think of it, plagiarizing a bad idea is probably the worse evil.)

I think every new programmer wrestles with this dilemma in their first
days but very soon after accepts it as reality. As for me it made
perfect sense from day one to have '=' mean "assignment" and '==' to
mean "equality". Programming is not mathematics (on the contrary) they
are two sides of a mountain forever unknowing of each other but
sharing the same space. I think the syntax was chosen because the
alternatives are even worse AND since assignment is SO common in
programming, would you *really* rather type two chars instead of one?

Nobody

unread,
Nov 17, 2009, 2:09:22 PM11/17/09
to
On Tue, 17 Nov 2009 17:31:18 +0000, MRAB wrote:

>> And if I ever find the genius who had the brilliant idea of using =
>> to mean assignment then I have a particularly nasty dungeon reserved
>> just for him. Also a foul-smelling leech-infested swamp for those
>> language designers and compiler writers who followed his example.
>> (Come to think of it, plagiarizing a bad idea is probably the worse
>> evil.)
>>
> C was derived from BCPL, which used ":=" and "=".

ISTR that Ritchie said that he chose "=" because assignment is more common
than testing for equality, so C's approach meant less typing.

> Fortran uses "=" and ".EQ.", probably because (some) earlier autocodes
> did.
>
> It's a pity that Guido chose to follow C.

OTOH, functional languages use "=" for binding (let x = ... in ...), which
is more like C initialisation (which also uses "=").

Python's "=" is somewhere between assignment and binding. It's arguable
that Python should also have ":=" for in-place modification (as opposed to
re-binding a name). E.g. for an array, "foo := bar" would be equivalent to
"foo[:] = bar".

Russ P.

unread,
Nov 17, 2009, 2:36:23 PM11/17/09
to

There is absolutely nothing wrong with using = for assignment. The
problem in C was allowing an assignment within a conditional
expression. Now *that* was a bonehead idea! (Hingsight is 20/20, of
course.) Python does not allow that, so there is no problem. Nor do
most other languages allow it.

greg

unread,
Nov 18, 2009, 12:22:44 AM11/18/09
to
MRAB wrote:

> Fortran uses "=" and ".EQ.", probably because (some) earlier autocodes
> did.

I think Fortran used .LT. and .GT. because some early character
sets didn't have < and > symbols. Having done that, it
probably seemed more consistent to use .EQ. for comparison
than to break the pattern and use =.

--
Greg

greg

unread,
Nov 18, 2009, 12:28:11 AM11/18/09
to
r wrote:
> I think the syntax was chosen because the
> alternatives are even worse AND since assignment is SO common in
> programming, would you *really* rather type two chars instead of one?

Smalltalk solved the problem by using a left-arrow character
for assignment. But they had an unfair advantage in being
able to use a non-standard character set on their custom-built
machines.

We should be able to do a lot better now using Unicode.
We could even heal the <> vs != rift by using a real
not-equal symbol!

--
Greg

Steven D'Aprano

unread,
Nov 18, 2009, 6:27:15 PM11/18/09
to

The problem isn't with the available characters, but with *typing* them.

It is hard to enter arbitrary Unicode characters by the keyboard, which
frankly boggles my mind. I don't know what the state of the art on Mac is
these days, but in 1984s Macs had a standard keyboard layout that let you
enter most available characters via the keyboard, using sensible
mnemonics. E.g. on a US keyboard layout, you could get ≠ by holding down
the Option key and typing =.

For me, I had to:

Click Start menu > Utilities > More Applications > KCharSelect.
Click through thirty-four(!) tables scanning by eye for the symbol I
wanted.
Click the ≠ character.
Click To Clipboard.
Go back to my editor window and paste.

--
Steven

r

unread,
Nov 18, 2009, 9:06:16 PM11/18/09
to
On Nov 18, 5:27 pm, Steven D'Aprano

♂ <-- Heres a free lesson... Stephen, hold down <CNTRL> and press
<KEYPAD-1> twice, then release <CNTRL>. ;-)

PS: But please lets not start using Unicode chars in programming, you
guy's already know how much i *hate* Unicode.

Gregory Ewing

unread,
Nov 19, 2009, 3:20:34 AM11/19/09
to
Steven D'Aprano wrote:
> I don't know what the state of the art on Mac is
> these days, but in 1984s Macs had a standard keyboard layout that let you
> enter most available characters via the keyboard, using sensible
> mnemonics. E.g. on a US keyboard layout, you could get ≠ by holding down
> the Option key and typing =.

They all still seem to work -- presumably generating the
appropriate unicode characters now instead of MacRoman.

I don't think there's any left-arrow character available
on the keyboard though, unfortunately.

--
Greg

Ben Finney

unread,
Nov 19, 2009, 6:38:18 AM11/19/09
to
Gregory Ewing <greg....@canterbury.ac.nz> writes:

> Steven D'Aprano wrote:
> > I don't know what the state of the art on Mac is these days, but in
> > 1984s Macs had a standard keyboard layout that let you enter most
> > available characters via the keyboard, using sensible mnemonics.
> > E.g. on a US keyboard layout, you could get ≠ by holding down the
> > Option key and typing =.

[…]

> I don't think there's any left-arrow character available on the
> keyboard though, unfortunately.

I'm glad to live in an age when free-software “Input Methods” for many
different character entry purposes are available in good operating
systems. I switch between them using SCIM <URL:http://www.scim-im.org/>.
At a pinch, when I'm without my GUI, I can turn some of them on with
Emacs. Common input methods → joy.

I usually default to the “rfc1345” input method which has many
non-keyboard characters available via two-character mnemonics from the
eponymous RFC document — which appears to be about the only purpose that
document has any more.

--
\ “The most dangerous man to any government is the man who is |
`\ able to think things out for himself, without regard to the |
_o__) prevailing superstitions and taboos.” —Henry L. Mencken |
Ben Finney

Carl Banks

unread,
Nov 19, 2009, 7:32:44 AM11/19/09
to
On Nov 19, 12:20 am, Gregory Ewing <greg.ew...@canterbury.ac.nz>
wrote:

> Steven D'Aprano wrote:
> > I don't know what the state of the art on Mac is
> > these days, but in 1984s Macs had a standard keyboard layout that let you
> > enter most available characters via the keyboard, using sensible
> > mnemonics. E.g. on a US keyboard layout, you could get ≠ by holding down
> > the Option key and typing =.
>
> They all still seem to work -- presumably generating the
> appropriate unicode characters now instead of MacRoman.

³It¹s about time.²


Carl Banks

Ben Finney

unread,
Nov 19, 2009, 7:44:22 AM11/19/09
to
Carl Banks <pavlove...@gmail.com> writes:

I � Unicode.


(lrf, gung *vf* qryvorengr, sbe gur uhzbhe-vzcnverq nzbat lbh)

--
\ “Courteous and efficient self-service.” —café, southern France |
`\ |
_o__) |
Ben Finney

0 new messages