Behavior of the for-else construct

2022-03-03 Thread computermaster360
I want to make a little survey here.

Do you find the for-else construct useful? Have you used it in
practice? Do you even know how it works, or that there is such a thing
in Python?

I have used it maybe once. My issue with this construct is that
calling the second block `else` doesn't make sense; a much more
sensible name would be `then`.

Now, imagine a parallel universe, where the for-else construct would
have a different behavior:

for elem in iterable:
process(elem)
else:
# executed only when the iterable was initially empty
print('Nothing to process')

Wouldn't this be more natural? I think so. Also, I face this case much
more often than having detect whether I broke out of a loop early
(which is what the current for-else construct is for).

Now someone may argue that it's easy to check whether the iterable is
empty beforehand. But is it really? What if it's an iterator?
Then one would have to resort to using a flag variable and set it in
each iteration of the loop. An ugly alternative would be trying to
retrieve
the first element of the iterable separately, in a try block before
the for-loop, to find out whether the iterable is empty. This would of
course
require making an iterator of the iterable first (since we can't be
sure it is already an iterator), and then -- if there are any elements
-- processing
the first element separately before the for-loop, which means
duplicating the loop body. You can see the whole thing gets really
ugly really quickly...

What are your thoughts? Do you agree? Or am I just not Dutch enough...?
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Behavior of the for-else construct

2022-03-03 Thread computermaster360
On Thu, 3 Mar 2022 at 18:25, Schachner, Joseph
 wrote:
>  I don't know what that would be. "finally" is available 😊  Write up a 
> feature request.

Not sure if you mean `finally` seriously but I think that would about
as confusing as the current `else`, if not even more 😅

Meanwhile, I found another solution which is somewhat neater than
using a boolean flag:

item = sentinel = object()
for item in iterable:
do_stuff(item)

if item is sentinel:
print('No items in iterable!')
-- 
https://mail.python.org/mailman/listinfo/python-list


Get the source of a class reliably?!?

2019-04-29 Thread computermaster360 .
Does anyone have an idea why classes don't contain their definition
line number as functions or methods do?

>>> some_fun.__code__.co_firstlineno
123
>>> SomeClass.???

This leads to some funny stuff when using `inspect`, such as this:

-- weird.py -
"""
class C:
  HAHAHA! YOU FOOL!
"""

class C:
  "this is a perfectly ok class"

  class C:
"this class is nice"
-

>>> inspect.getsource(weird.C)
class C:
  HAHAHA! YOU FOOL!


Why ???
-- 
https://mail.python.org/mailman/listinfo/python-list