New syntax for blocks

R

r

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? ;-)
 
R

Robert Latest

r said:
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
 
S

steve

Hi,

[...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
 
S

steve

Hi,

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
 
R

r

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.
 
S

Steven D'Aprano


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.
 
C

Carl Banks

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
 
C

Carl Banks

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

r

On Nov 10, 9:12 pm, Steven D'Aprano
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 ;-)
 
S

Steven D'Aprano

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.
 
T

Terry Reedy

Carl said:
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

r

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

Hardly!,Here is an interactive session with your test case
#----------------------------------------------------------# 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
print 'block'

block print 'block'

block 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.
 
S

Steven D'Aprano

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.
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?
 
R

r

Incorrect.
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
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.
 
S

Steven D'Aprano

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.


...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)




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".
 
R

r

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)
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?
 
C

Carl Banks

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
 
C

Carl Banks

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
 
S

steve

Hi,

[...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.

cheers,
- steve
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,755
Messages
2,569,537
Members
45,022
Latest member
MaybelleMa

Latest Threads

Top