[Python-ideas] Re: Protocols Subclassing Normal Classes

2023-04-24 Thread Mathew Elman
Rather than changing Protocols and affecting lots of users, it seems like was 
you really want is a generic class that is the "and" to Union's "or"? e.g.

def foo(thing: All[Thread, SupportsStop]):
...

which seems reasonable. If that appeals to you, then you probably want to raise 
that on the typing thread?
___
Python-ideas mailing list -- python-ideas@python.org
To unsubscribe send an email to python-ideas-le...@python.org
https://mail.python.org/mailman3/lists/python-ideas.python.org/
Message archived at 
https://mail.python.org/archives/list/python-ideas@python.org/message/JV3OYN5LXNMHBOT5RGEFHXSQYFKNB2EB/
Code of Conduct: http://python.org/psf/codeofconduct/


[Python-ideas] Extending LiteralString or Literal with structural validation

2022-12-20 Thread Mathew Elman
This is somewhat inspired by the "Tagged strings in python" thread, but from a 
different approach.
Specifically, rather than messing with runtime python, using static type 
analysis to help the usability of specific kinds of string literals.

It would be useful to take advantage of the `LiteralString` or `Literal` type 
hints to add structural validation to literals.

For *example*, if these could be subclassed to add a validation method:
class MyLiteral(LiteralString):
def __validate__(self):
...

or extended to allow something like regex in there generic type parameter:
Literal[r"\w+"]
LiteralString[r"\w+"]

then specific kinds of literal string can be "enforced" by static type 
checkers. 
Then IDEs could at the very least highlight that a string literal is not valid.

I stress these are just examples, the goal is to have a way to tell a static 
type checker what the structure of a string literal has to be.
___
Python-ideas mailing list -- python-ideas@python.org
To unsubscribe send an email to python-ideas-le...@python.org
https://mail.python.org/mailman3/lists/python-ideas.python.org/
Message archived at 
https://mail.python.org/archives/list/python-ideas@python.org/message/37OZHV2KNILDMO4WVOHOZZADVYPLQWE3/
Code of Conduct: http://python.org/psf/codeofconduct/


[Python-ideas] Re: Void type

2022-07-27 Thread Mathew Elman
Chris Angelico wrote:
> On Wed, 27 Jul 2022 at 21:54, Mathew Elman mathew.el...@ocado.com wrote:
> > I don't see why you couldn't. I guess what they do depends if any of these 
> > have defaults? Which I think they do not in this case, right?
> > If they were non vanilla dictionaries that had a default e.g.
> > class SomeDict(dict):
> > def __getitem__(self, item=None):
> > return super().__getitem__(item)
> > def __contains__(self, item=None):
> > return super().__contains__(item)
> > 
> > So Undefined would trigger a default, but only if there is one?
> > print(b[1]) would still print Undefined because print's first argument 
> > doesn't have a default.
> > But print doesn't have a first argument - it accepts *args. So
> Undefined still counts as an argument, except when there's a default,
> at which point it counts as a non-argument?

Yes, I guess you could do it so that for var args it was treated as a non 
argument? so print(Undefined) == print() ? But that seems even more 
surprising...

> > a in c would be False.
> > That is VERY surprising behaviour. For literally any other object,
> that would be True. But then, it would be surprising in other ways if
> Undefined behaved like a normal object.
> > c[a] would return c[None], which would raise an error here because None 
> > isn't in the mapping
> > Again, very surprising, if putting a value into a mapping doesn't
> result in that value being in the mapping.

Yes, compared with other objects, there would need to be some surprising 
behaviour because it isn't a concept in python already. 
You could fix this specific problem with mappings by changing Undefined to not 
be hashable, but that is definitely a bandaid.

> > Again, I am not pro this idea, just answering the questions you're asking 
> > as I see them :)
> > Yeah. I think you're doing a great job of showing why this is a bad idea :)

I do think the desire to fix the "wrapper not needing to know the defaults of 
wrapped" problem is admirable.
Is this the right approach? No, I think not.
___
Python-ideas mailing list -- python-ideas@python.org
To unsubscribe send an email to python-ideas-le...@python.org
https://mail.python.org/mailman3/lists/python-ideas.python.org/
Message archived at 
https://mail.python.org/archives/list/python-ideas@python.org/message/4VIQAKFNSKE7BV54NF3DGC4VNTO7BWEJ/
Code of Conduct: http://python.org/psf/codeofconduct/


[Python-ideas] Re: Void type

2022-07-27 Thread Mathew Elman
I don't see why you couldn't. I guess what they do depends if any of these have 
defaults? Which I think they do not in this case, right?
If they were non vanilla dictionaries that had a default e.g. 

class SomeDict(dict):
def __getitem__(self, item=None):
return super().__getitem__(item)

def __contains__(self, item=None):
return super().__contains__(item)

print(b[1]) would still print Undefined because print's first argument doesn't 
have a default.
a in c would be False.
c[a] would return c[None], which would raise an error here because None isn't 
in the mapping

Again, I am not pro this idea, just answering the questions you're asking as I 
see them :)
___
Python-ideas mailing list -- python-ideas@python.org
To unsubscribe send an email to python-ideas-le...@python.org
https://mail.python.org/mailman3/lists/python-ideas.python.org/
Message archived at 
https://mail.python.org/archives/list/python-ideas@python.org/message/ZR36EZY6DVV6TG4ECWLTVR2GDLKAQPT2/
Code of Conduct: http://python.org/psf/codeofconduct/


[Python-ideas] Re: Void type

2022-07-27 Thread Mathew Elman
To answer how this _could_ work, Undefined would be a new NoneType that is 
falsey (just like None) can't be reassigned (just like None) and does 
everything else just like None _except_ that when it is passed as a function 
argument, the argument name is bound to the default if it has one instead. 

I am not sure I understand your example
> notdefined = None
> def foo(x=undefined):# here
> notdefined = x
> return wrapped_function(x)   # there
> foo()
> print(notdefined)

This would call wrapped_function with "undefined" so it would use the default 
if present, and print None because notdefined in foo is only in that scope?
Did you mean to use a global notdefined in foo? In which case it would print 
undefined ?
In your example there is no default to use... it would be this case:

def foo(x=undefined):
return bar(x)

def bar(x=1):
return x

print(foo())   # 1
print(foo(2)) # 2


To be clear, I am _not_ +anything for this, I was just saying that I think this 
is what is really be asked for here. I am -0, I can see there being value, but 
that value is largely superficial and the possible can of worms is definitely a 
writhing one. The only problem it solves is allowing wrappers to fallback to 
their wrapped functions defaults, but at a fairly high cost.
___
Python-ideas mailing list -- python-ideas@python.org
To unsubscribe send an email to python-ideas-le...@python.org
https://mail.python.org/mailman3/lists/python-ideas.python.org/
Message archived at 
https://mail.python.org/archives/list/python-ideas@python.org/message/UGWCLL7U6UH6ALMXGNFYGQA7AQH4BWAS/
Code of Conduct: http://python.org/psf/codeofconduct/


[Python-ideas] Re: Void type

2022-07-26 Thread Mathew Elman
I believe this is a rebirth of a request that has come up many times before, 
which is to have something like javascript's `undefined` where it means "use 
the default value" if passed to a function that has a default value or "value 
not provided" (slightly different to "None").

>> def foo(x, y=1):
...  return x, y

>> foo(undefined, undefined)
undefined, 1

The idea being that wrapper functions don't need to then know what the default 
is for the function they wrap:

def outermost_wrapper(b, c=undefined):
return inner_wrapper(5, b, c)

def inner_wrapper(a, b=undefined, c=undefined):
return func(a, b, c)

def func(a=1, b=2, c=3):
return a*b*c

"undefined" would either have to be an alias for "None" everywhere _except_ 
function signatures, or be only allowed in function signatures and have special 
handling. It opens up a can of worms in javascript but has its uses.
___
Python-ideas mailing list -- python-ideas@python.org
To unsubscribe send an email to python-ideas-le...@python.org
https://mail.python.org/mailman3/lists/python-ideas.python.org/
Message archived at 
https://mail.python.org/archives/list/python-ideas@python.org/message/KO4FUF45RA6CJXEWQXOKOOOYC3RMFPIZ/
Code of Conduct: http://python.org/psf/codeofconduct/


[Python-ideas] Re: Null wildcard in de-structuring to ignore remainder and stop iterating

2022-06-20 Thread Mathew Elman
Chris Angelico wrote:
> On Mon, 20 Jun 2022 at 21:11, Mathew Elman mathew.el...@ocado.com wrote:
> > This I like - it seems very intuitive, almost like an irreversible io 
> > stream.
> > I don't know if there would be cases where this would lead to unexpected 
> > bugs, but without looking into it it seems nice.
> > Question: What would be the natural behaviour for negative indices? Raising 
> > an error?
> > Please quote the person and text that you're responding to (and then
> add your response underneath). Otherwise we have to guess which
> (sub)proposal it is that you like.
> ChrisA

Oops, I thought I had, it was this:

> To me, the natural implementation of slicing on a non-reusable iterator (such 
> as a generator) would be that you are not allowed to go backwards or even 
> stand still:
> mygen[42]
> mygen[42]
> ValueError: Element 42 of iterator has already been used (Apologies if I 
> don't know the difference between an iterator and an iterable; y'all know 
> what I mean.)
> You still get a useful feature that you didn't have before. Expecting a 
> generator (or whatever) to cache some its values in case you wanted a slice 
> of them opens up a huge can of worms and is surely best forgotten.  (100Gb 
> generator anyone?)  Well, maybe caching ONE value (the last one accessed) is 
> reasonable, so you could stand still but not go backwards.  But it's still 
> adding overhead.
> Best wishes
> Rob Cliffe
___
Python-ideas mailing list -- python-ideas@python.org
To unsubscribe send an email to python-ideas-le...@python.org
https://mail.python.org/mailman3/lists/python-ideas.python.org/
Message archived at 
https://mail.python.org/archives/list/python-ideas@python.org/message/LL5FBAT53QJRKGLQEY3H3GD6JGXTB4QE/
Code of Conduct: http://python.org/psf/codeofconduct/


[Python-ideas] Re: Null wildcard in de-structuring to ignore remainder and stop iterating

2022-06-20 Thread Mathew Elman
This I like - it seems very intuitive, almost like an irreversible io stream.

I don't know if there would be cases where this would lead to unexpected bugs, 
but without looking into it it seems nice. 

Question: What would be the natural behaviour for negative indices? Raising an 
error?
___
Python-ideas mailing list -- python-ideas@python.org
To unsubscribe send an email to python-ideas-le...@python.org
https://mail.python.org/mailman3/lists/python-ideas.python.org/
Message archived at 
https://mail.python.org/archives/list/python-ideas@python.org/message/BNVFN7B5TYH6RTYD3GZI7AFIJRJVX4I5/
Code of Conduct: http://python.org/psf/codeofconduct/


[Python-ideas] Re: PEP 671 (late-bound arg defaults), next round of discussion!

2022-06-15 Thread Mathew Elman
Could this be the behaviour of passing in an Ellipsis? e.g.

def foo(defaults_to_one=1):
return defaults_to_one

assert foo(...) == foo()

def bar(something=...):
return foo(something)

assert bar() == foo()

def baz(arg):  # no defaults
return arg

assert baz(...) == ...

The only place that I am aware of the Ellipsis being used is in index notation 
(numpy).
So this would have likely an impact on __getitem__ or the slice object.

*Alternatively* a subtype of Ellipses specifically for when used in argument 
defaults DefaultEllipsis (or equivalent):
def foo(x=...):
return x

assert isinstance(foo(), EllipsisType)
assert foo() != Ellipsis

assert isinstance(foo(...), EllipsisType)
assert foo(...) == Ellipsis
___
Python-ideas mailing list -- python-ideas@python.org
To unsubscribe send an email to python-ideas-le...@python.org
https://mail.python.org/mailman3/lists/python-ideas.python.org/
Message archived at 
https://mail.python.org/archives/list/python-ideas@python.org/message/C2L3COISYSSVFAYXRFVVNPFBBOQYXVQU/
Code of Conduct: http://python.org/psf/codeofconduct/


[Python-ideas] Re: Null wildcard in de-structuring to ignore remainder and stop iterating

2022-06-09 Thread Mathew Elman
would it not be possible to have slicing fallback to islice if __iter__ is 
implemented and __geitem__ is not?
___
Python-ideas mailing list -- python-ideas@python.org
To unsubscribe send an email to python-ideas-le...@python.org
https://mail.python.org/mailman3/lists/python-ideas.python.org/
Message archived at 
https://mail.python.org/archives/list/python-ideas@python.org/message/VNTIKNRIR3E4PRAKEI664KWYP7Y3ZC3R/
Code of Conduct: http://python.org/psf/codeofconduct/


[Python-ideas] Re: Addition to fnmatch.py

2022-06-06 Thread Mathew Elman
oops, you're right, I have ended up with an unnecessary "not" in there, should 
be:

from collections import deque


def partition(pred, iterable):
results = deque([]), deque([])

def gen_split(only):
for thing in iterable:
if results[only]:
yield results[only].popleft()
results[pred(thing)].append(thing)
for thing in results[only]:
yield thing

return gen_split(True), gen_split(False)
___
Python-ideas mailing list -- python-ideas@python.org
To unsubscribe send an email to python-ideas-le...@python.org
https://mail.python.org/mailman3/lists/python-ideas.python.org/
Message archived at 
https://mail.python.org/archives/list/python-ideas@python.org/message/QURICBHMB3D2WG2VWEBJ56Q6ZZHKBUJX/
Code of Conduct: http://python.org/psf/codeofconduct/


[Python-ideas] Re: Addition to fnmatch.py

2022-06-06 Thread Mathew Elman
from collections import deque

def partition(pred, iterable):
results = deque([]), deque([])

def gen_split(only):
for thing in iterable:
if results[only]:
yield results[only].popleft()
results[not pred(thing)].append(thing)
for thing in results[only]:
yield thing

return gen_split(True), gen_split(False)
___
Python-ideas mailing list -- python-ideas@python.org
To unsubscribe send an email to python-ideas-le...@python.org
https://mail.python.org/mailman3/lists/python-ideas.python.org/
Message archived at 
https://mail.python.org/archives/list/python-ideas@python.org/message/EUAYPXMZM4DOGTAAUURNOMWTDU65K6UY/
Code of Conduct: http://python.org/psf/codeofconduct/


[Python-ideas] Re: Real Positional Arguments or OO Currying

2021-10-19 Thread Mathew Elman
> Seems like the docs should cover that (or even `help()`) -- and if not, then 
> the parameter names could be better.

It should, and normally does as do the parameters, but the best documentation 
should be the code itself, right? So the idea here would be to make it harder 
to not know the order than to forget, i.e. so you would check the docs for the 
more nuanced behaviour around kwargs or something of that nature.
___
Python-ideas mailing list -- python-ideas@python.org
To unsubscribe send an email to python-ideas-le...@python.org
https://mail.python.org/mailman3/lists/python-ideas.python.org/
Message archived at 
https://mail.python.org/archives/list/python-ideas@python.org/message/KYBVRLWBCWP3WCZLRFH7RM44X7G2KXMU/
Code of Conduct: http://python.org/psf/codeofconduct/


[Python-ideas] Re: Real Positional Arguments or OO Currying

2021-10-18 Thread Mathew Elman
> Reminds me of some testing/assertion frameworks. I'm not a fan, but
> some people like it.
> 
> expect(thing).to.be.numeric()

That rings a bell with test a javascript test framework, something like enzyme?
___
Python-ideas mailing list -- python-ideas@python.org
To unsubscribe send an email to python-ideas-le...@python.org
https://mail.python.org/mailman3/lists/python-ideas.python.org/
Message archived at 
https://mail.python.org/archives/list/python-ideas@python.org/message/F7M54KRJODO2UMIFSWNMTPYTFU5ZW6N3/
Code of Conduct: http://python.org/psf/codeofconduct/


[Python-ideas] Re: Real Positional Arguments or OO Currying

2021-10-18 Thread Mathew Elman
> I think that a programming language needs to be different enough from a 
> natural language to remind you that it's a programming language and that 
> the computer isn't that smart. The computer will do as you say, not as 
> you mean.

I agree entirely, that's why I am not suggesting putting spaces and using magic 
keywords or 's, the proposed change is very limited in that regard and is 
focused on making positional arguments be positional. The proposed change in 
behaviour is to ​allow `.` in a function signature declaration/definition:

def foo(arg1).bar(arg2):
...
 
foo(0).bar(1) == foo.bar(0,1)

this doesn't look like english at all, but facilitates more language like / 
naturally readable function signatures.

A broader option, that I have seen before but can't find the thread, is to 
allow `.` in a signature as sugar for defining a function as an attribute / in 
the scope of something else i.e.

def foo.function(...):
...

is equivalent to

def function(...):
... 
foo.function = function

If that were allowed, then it would be possible to sort of get the syntax I am 
talking about.
___
Python-ideas mailing list -- python-ideas@python.org
To unsubscribe send an email to python-ideas-le...@python.org
https://mail.python.org/mailman3/lists/python-ideas.python.org/
Message archived at 
https://mail.python.org/archives/list/python-ideas@python.org/message/ZIJAORKONOOFRN7ZJMUOWY5IER5ZUFHK/
Code of Conduct: http://python.org/psf/codeofconduct/


[Python-ideas] Re: Real Positional Arguments or OO Currying

2021-10-18 Thread Mathew Elman
This is interesting, it's not as nice as native syntax support could have been 
but a decorator like this is also pretty nice. 
I think I would bikeshed this so the decorator was the full dot separated 
signature, e.g.

@curry_helper('insert.into')
def insert(x: Any, y: list):
def y.append(x)

but other than that, I think this is probably the closest thing I'll get out of 
this, so thanks.
___
Python-ideas mailing list -- python-ideas@python.org
To unsubscribe send an email to python-ideas-le...@python.org
https://mail.python.org/mailman3/lists/python-ideas.python.org/
Message archived at 
https://mail.python.org/archives/list/python-ideas@python.org/message/NBMWJ54XSI6JQESR7ZXUR4WFYW7GNHU4/
Code of Conduct: http://python.org/psf/codeofconduct/


[Python-ideas] Re: Real Positional Arguments or OO Currying

2021-10-18 Thread Mathew Elman
Not really, I'm not trying to suggest a fully English like language be incepted 
into python, my main point here was that there are cases where the order of 
arguments is important and being able to have actually positional arguments 
would go a long way to improving knowing intuitively that order. 
e.g. I would have to check if `my_list.insert(1, 0)` meant insert 1 at 0 or 0 
at 1.
but `my_list.insert(0).at_index(1)` would make it really easy to remember, even 
if you rarely called it that way.
___
Python-ideas mailing list -- python-ideas@python.org
To unsubscribe send an email to python-ideas-le...@python.org
https://mail.python.org/mailman3/lists/python-ideas.python.org/
Message archived at 
https://mail.python.org/archives/list/python-ideas@python.org/message/2DNW3V6YGP5QY7ZTOYRWFKZLIPIQQQWI/
Code of Conduct: http://python.org/psf/codeofconduct/


[Python-ideas] Re: Real Positional Arguments or OO Currying

2021-10-18 Thread Mathew Elman
> What you are describing is very, very dissimilar to currying. It's simply 
> multi-argument functions with a different call syntax.

It is almost identical to currying, the only differences are:
1. the intermediate return being an object with an attribute (rather than a new 
function) that you call.
2. the names of the attributes from 1 (which aren't a thing otherwise) are 
declared when defining the initial function

> It's not even close to worthwhile to have special syntax for rare cases.

It would make sense for a huge number of functions, its just not a natural way 
to consider writing them because the syntax doesn't exist e.g. almost any 
boolean function makes sense this way.
___
Python-ideas mailing list -- python-ideas@python.org
To unsubscribe send an email to python-ideas-le...@python.org
https://mail.python.org/mailman3/lists/python-ideas.python.org/
Message archived at 
https://mail.python.org/archives/list/python-ideas@python.org/message/FJWSTADJE76BVS5XSSNIS2OKRDYDSANX/
Code of Conduct: http://python.org/psf/codeofconduct/


[Python-ideas] Re: Real Positional Arguments or OO Currying

2021-10-18 Thread Mathew Elman
Paul Moore wrote:
> On Mon, 18 Oct 2021 at 12:49, Mathew Elman mathew.el...@ocado.com wrote:
> > The point is that at the moment to set this sort of api up requires a lot 
> > of work, defeating 50% of the value i.e. to define a new function with the 
> > attribute access behaviour requires defining each individual function to 
> > return a middle step object that has the attribute of the next function, so 
> > you can't define a function in plain english.
> > Adding a new feature to a language is *even more* work, though. The
> reason (one of the reasons) we'd add a feature to the language is
> because it would get used so often that the repeated saving outweighs
> the initial (and ongoing) cost of the language feature.

It's more work for the internals of python yes, because it becomes part of 
python stdlib that you can define a function with `.` in the signature and that 
has a specific meaning as syntax sugar for what's below. But that doesn't mean 
it's more work across the board, given that the below would be necessary for 
every single function that wanted to have this sort of syntax. In every single 
code base that wanted to use it. Granted no one would use it right now, because 
right now the effort of doing the below it prohibitive and misses out on the 
easy to ready signature definition.

> > def insert_into(x, y):
> > ...
> > def insert(x):
> > class Return:
> > def into(self, y):
> > return insert_into(x, y)
> > return Return()
> > insert.into = insert_into
> > is a very long way to say:
> > def insert(x)._into(y):
> > ...
> > and that is without the actual logic and for only 2 positional args.
> > But why would you? It's ugly if spelled like that, and your whole argument 
> > is that the "interspersed arguments" form is better. If you just want to 
> > pass the function to something that expects "normal" argument conventions, 
> > lambda x,y: insert(x).into(y) does what you want.
> > > The point is so that in code that expects dynamically called functions or 
> > > to be able to reference the function by name it needs to have a single 
> > > name that follows backward compatible naming conventions. I would be 
> > > happy with it being on the onus of the developer in question to add a 
> > > wrapping function, less happy than if it was added by default but it 
> > > would still be a saving (and could maybe be in a decorator or something).
> > So the automatic definition of the extra name is purely because
> there's no other way to pass these types of function around as
> first-class objects? What about other aspects of first class functions
> - would you be able to introspect these new types of function?

It wouldn't need to be a new type of function, so yes of course you would be 
able to introspect these objects. The change does not require any real magic 
beyond the way you would do it now, except that it doubles the value of how you 
do it now by it being in a single neat function definition.

> Extract the places in the name where the arguments can be interposed? If not,
> why not? 

Assuming that it would just make each segment of the function name be a 
function with the next part as an attribute and have a return object yes you 
would be able to get where the arguments go in the signature.

> How would a call like foo_(x)_bar(y) be parsed into the AST?

Again, assuming the `.` syntax and a new "Return" class, it would be parse the 
same way `foo_(x)._bar(y)` would be. no magic needed

> Would the original form be recoverable (black, for example, would want this).

yes

> Also, are the underscores part of the syntax? Is foo(x)bar(y) a single
> function call using your new syntax? If not, why not? You would be
> making underscores into special syntax otherwise.

so, the underscores were a personal choice, because I separate words with 
underscores, but would not be necessary. 
Assuming (again) that it used a Return class for the intermediate returns with 
attributes for the next part, `foo(x)bar(y)` would not be an example, instead 
`foo(x).bar(y)` would be, which is using existing syntax and concepts. the main 
difference would be how this is initially defined, requiring only the presence 
of the `.` and interspersed args in the function signature.

> > I've never heard anyone else suggest anything like this, so you might want 
> > to consider that the annoyance you feel is not a common reaction...
> > I know lots of people that have had this reaction but just shrugged it off 
> > as "the way things are", which would seem like a good way to stagnate a 
> > language, so I thought I would ask.
> > There seem to be a lot of open design q

[Python-ideas] Re: Real Positional Arguments or OO Currying

2021-10-18 Thread Mathew Elman
> Still, I don't want Python to try to be Cobol.

I agree, I don't want Python to try and be Cobol, but that doesn't mean there 
aren't things to learn from Cobol regarding this, if this indeed something 
found there - I can't comment on that. 

> I think the intellectual argument for "English syntax" failed, 
> notwithstanding installed base.

I see this argument used for python in this list (and in the wild) a lot i.e. 
that it should be readable in English. I am not saying that this is the 
be-all-end-all of python but it does matter.  Also, this being syntax for 
defining OO curried functions, achieves the goal of more English like syntax 
while introducing a standard for curried functions in Python - which are of a 
lot of value in many situations, but usually require nasty syntax.
___
Python-ideas mailing list -- python-ideas@python.org
To unsubscribe send an email to python-ideas-le...@python.org
https://mail.python.org/mailman3/lists/python-ideas.python.org/
Message archived at 
https://mail.python.org/archives/list/python-ideas@python.org/message/FCPD3K7OPGZTLHJ56ZUDXISJKY6L46GC/
Code of Conduct: http://python.org/psf/codeofconduct/


[Python-ideas] Re: Real Positional Arguments or OO Currying

2021-10-18 Thread Mathew Elman
The point is that at the moment to set this sort of api up requires a lot of 
work, defeating 50% of the value i.e. to define a new function with the 
attribute access behaviour requires defining each individual function to return 
a middle step object that has the attribute of the next function, so you can't 
define a function in plain english.
e.g.

def insert_into(x, y):
...

def insert(x):
class Return:
def into(self, y):
return insert_into(x, y)
return Return()

insert.into = insert_into

is a very long way to say:

def insert(x)._into(y):
...

and that is without the actual logic and for only 2 positional args.


> But why would you? It's ugly if spelled like that, and your whole argument is 
> that the "interspersed arguments" form is better. If you just want to pass 
> the function to something that expects "normal" argument conventions, lambda 
> x,y: insert(x).into(y) does what you want.

The point is so that in code that expects dynamically called functions or to be 
able to reference the function by name it needs to have a single name that 
follows backward compatible naming conventions. I would be happy with it being 
on the onus of the developer in question to add a wrapping function, less happy 
than if it was added by default but it would still be a saving (and could maybe 
be in a decorator or something).


> I've never heard anyone else suggest anything like this, so you might want to 
> consider that the annoyance you feel is not a common reaction...

I know lots of people that have had this reaction but just shrugged it off as 
"the way things are", which would seem like a good way to stagnate a language, 
so I thought I would ask.
___
Python-ideas mailing list -- python-ideas@python.org
To unsubscribe send an email to python-ideas-le...@python.org
https://mail.python.org/mailman3/lists/python-ideas.python.org/
Message archived at 
https://mail.python.org/archives/list/python-ideas@python.org/message/JY3JEMACQQ33F6NTZJZ7T6U4YPEZFQTJ/
Code of Conduct: http://python.org/psf/codeofconduct/


[Python-ideas] Re: Real Positional Arguments or OO Currying

2021-10-18 Thread Mathew Elman
That is interesting but is missing the point of what I am really getting at, in 
order to build a function of multiple args this way would require a lot of 
these "operators" that would need to be interchangeable, so I don't think what 
I am looking for is an operator. 

The key point being having a nice way to build up the signature with arguments 
dispersed as they are in an actual sentence in english, and being able to use 
it.
___
Python-ideas mailing list -- python-ideas@python.org
To unsubscribe send an email to python-ideas-le...@python.org
https://mail.python.org/mailman3/lists/python-ideas.python.org/
Message archived at 
https://mail.python.org/archives/list/python-ideas@python.org/message/6CVFLNILDKQ5NHPIGSGJZNIQIFO2NSFT/
Code of Conduct: http://python.org/psf/codeofconduct/


[Python-ideas] Real Positional Arguments or OO Currying

2021-10-18 Thread Mathew Elman
I don't know if this has been suggested before, or if this is outlandishly 
impossible (though I would be surprised if it was), so apologies in advance if 
so.

I have on occasion come across a situation where I use/write a signature like 
this:

def insert_x_into_y(x, y):
...

or worse

def insert_into(item, container):
...

where, despite a driving idea of python syntax being readability in english, 
the function signature is distinctly not english.
"I'll just go and insert into this item that container", is not only never said 
but is actually ambiguous in english.

What would be really cool, is if python let you write function signatures like 
this:

def insert_(item)_into_(container):
...

where the arguments dispersed between the function name are positional only 
argument, and any key word arguments would have to go at the end.
It would create a function that could be called as:

insert_(1)_into_(my_list)

or

insert__into_(1, my_list)

The purpose of allowing both should be obvious - so that the function can be 
referenced and called in other places.
(Rather than just skipping the brackets the function call with only the end 
parentheses could have a special stand in character e.g. ., ?, !, _ or other if 
that was more preferred.)

This sort of signature is particularly annoying for boolean checks like 
`isinstance` (N.B. I am _not_ suggesting changing any builtins), which one 
could wrap with:

def is_(obj)_an_instance_of_(type):
return isinstance(obj, type)

For precedence in other languages, this is similar to curried functions in 
functional languages e.g Haskell, especially if each part of a function were to 
be callable, which would be up for debate.

Allowing each part to be called would make sense if each "next" partial 
function were an attribute on the previous and what it returned, making it a 
sort of object oriented currying. 
Then the syntax could be with a `.`:

def is_(obj)._an_instance_of_(type):
...

is_(1)._an_instance_of_(int)
is_._an_instance_of_(1,int)
___
Python-ideas mailing list -- python-ideas@python.org
To unsubscribe send an email to python-ideas-le...@python.org
https://mail.python.org/mailman3/lists/python-ideas.python.org/
Message archived at 
https://mail.python.org/archives/list/python-ideas@python.org/message/YMFRX6K22TZNNAP2PPVV7RGNI5HLC764/
Code of Conduct: http://python.org/psf/codeofconduct/


[Python-ideas] Re: Deprecate sum of lists

2021-06-18 Thread Mathew Elman
I don't see how allowing 

[x, y for x in a] 

follows from allowing 

[*chunk for chunk in list_of_lists].
___
Python-ideas mailing list -- python-ideas@python.org
To unsubscribe send an email to python-ideas-le...@python.org
https://mail.python.org/mailman3/lists/python-ideas.python.org/
Message archived at 
https://mail.python.org/archives/list/python-ideas@python.org/message/CTYGB5FE3EMJCH4JJJKGG3OIPTREBW6C/
Code of Conduct: http://python.org/psf/codeofconduct/


[Python-ideas] Re: Should PEP 637 legalize "obj[]"?

2020-12-24 Thread Mathew Elman
I am +0.5 on allowing this, unless I misunderstand the implications, this would 
still raise errors in the cases where an empty tuple was not an intended 
key/index/argument.

I can see that `obj[]` is less explicit than `obj[()]` but is no less clear (if 
it is allowed). However, I am only +0.5 because I am not sure how common a 
useful use case for `obj[]` would occur, so it is not all that much of an sugar 
coating.

That being said, I agree that allowing this would undoubtedly open the doors to 
"abuse" of this syntax in ways that `obj[()]` would not - that is, if it was 
allowed, people would find ways use it and be aware that an empty tuple is an 
allowed argument (which I believe will be possible regardless, yes?), whereas 
not allowing it may lead to less prevalent use of empty tuples as arguments 
(make of that what you will).
Whether that "abuse" is really abuse or the exciting growth/usage of new syntax 
is debatable but I edge toward the latter as a mad pythonist myself.
___
Python-ideas mailing list -- python-ideas@python.org
To unsubscribe send an email to python-ideas-le...@python.org
https://mail.python.org/mailman3/lists/python-ideas.python.org/
Message archived at 
https://mail.python.org/archives/list/python-ideas@python.org/message/4V6CCPQX3BI5Q3JYS4FTG3UEESIKPQDC/
Code of Conduct: http://python.org/psf/codeofconduct/


[Python-ideas] Re: Standalone bool?

2020-12-21 Thread Mathew Elman
Christopher Barker wrote:
> > Surely what you're looking for is some kind of typed
> > hash table?
> > Maybe, maybe not. My impression is that the Typed hash  table is a kluge to
> get around this one issue.
> As others have pointed out, 1 and 1.0 are considered equal, and thus hash
> the same — a typed  hash table would not consider them the same. And while
> maybe useful, it would violate the spirit of duck typing. If you really
> want that kind of static typing, maybe Python is not the language for the
> job.

The OP states that in their case True and 1 should _not_ hash the same, whether 
that gels with Python was not my point, I was saying that this use case, to me, 
is asking for some kind of typed hash table not a change to the typing of 
Booleans themselves.

> (And since booleans are subclasses of Ints, they might still class in a
> typed has table, depending on the implementation)

Hence my suggestion that the OP's solution of a bespoke key mapping to tuples 
is not so bad (i.e. not making it part of the stdlib), but that it may be nicer 
to deal with if it is abstracted away into the getitem, setitem ... dunder 
methods.

> What I think the OP wants, and I happen to agree, is for Booleans to not
> only not BE integers in the subclassing sense, but also to not behave as
> numbers in the. Duck Typing sense. 

Apologies, but that is not what the user is saying, they are saying arguably 
the opposite. I am not saying I agree with the OP on this, but I don't think 
the behaviour of Bools in mathematical operations is their point.

> To the OP: perhaps you could create your own non-integer Bool type, and
> then put a wrapper around set and/or dict, that substitutes it on
> insertion.
> Whether that is more or less kludgy than your solution depends on your use
> case.

I think this is a similar idea to what I was suggesting but limited to only 
handle Booleans.
___
Python-ideas mailing list -- python-ideas@python.org
To unsubscribe send an email to python-ideas-le...@python.org
https://mail.python.org/mailman3/lists/python-ideas.python.org/
Message archived at 
https://mail.python.org/archives/list/python-ideas@python.org/message/BU3S65VWYZ6WQ3DRXZZ3EQA3DUL4KNH6/
Code of Conduct: http://python.org/psf/codeofconduct/


[Python-ideas] Re: Standalone bool?

2020-12-21 Thread Mathew Elman
Surely what you're looking for is some kind of typed hash table? Maybe you 
should be suggesting adding a TypedMapping to collections or something like 
that? But it seems to be your solution is fine, but maybe could abstract away 
the types in the keys in the class dunders?

```
class TypedMapping(dict):
def __getitem__(self, item):
return super().__getitem__((item, type(item)))
...
```
And so on
___
Python-ideas mailing list -- python-ideas@python.org
To unsubscribe send an email to python-ideas-le...@python.org
https://mail.python.org/mailman3/lists/python-ideas.python.org/
Message archived at 
https://mail.python.org/archives/list/python-ideas@python.org/message/VAPFARSZB6TRIQQAWANXMNAKQAM3GVDS/
Code of Conduct: http://python.org/psf/codeofconduct/


[Python-ideas] Re: Lazy Type Casting

2020-12-10 Thread Mathew Elman
Steven D'Aprano wrote:
> On Wed, Dec 09, 2020 at 12:05:17PM -0000, Mathew Elman wrote:
> > Steven D'Aprano wrote:
> > On Tue, Dec 08, 2020 at 11:46:59AM -0000, Mathew
> > Elman wrote:
> > I would like to propose adding lazy types for
> > casting
> > builtins in a 
> > lazy fashion. e.g. lazy_tuple which creates a reference to the 
> > source iterable and a morally immutable sequence but only populates 
> > the tupular container when it or the source is used.
> > What are your use-cases for this?
> > Does this include things like lazy_list, lazy_float,
> > lazy_bool, 
> > lazy_str, lazy_bytearray etc?
> > I would say yes, it should include these types as well.
> > The use case is for when you are casting between types a high number 
> > of times to pass them around, especially into another type and back.
> > I would say, don't do that. If you have a list, and you pass it to 
> another function after converting to a tuple, why would you take that 
> tuple and convert back to a list when you already have a list?
> For types like casting back and forth between float and int, there will 
> be data loss.
> Even if there is not, the overhead of creating a "lazy proxy" to the 
> float is probably greater than just converting.
I see what you mean here, I think my initial thought was more towards container 
types rather than ints and floats, I said these should be included because I 
saw no reason why not. Thinking about it, for int and float types it makes less 
sense, because you have no great saving, whereas for a container type, you can 
increase the reference count by 1 instead of N. 

> > How do these
> > hooks freeze the list?
> > they don't freeze the list, they freeze the values in the lazy_tuple 
> > when the list is mutated, so when mutating the list, the values in the 
> > tuple are set (if they have not been already), so that they aren't 
> > also mutated in the lazy_tuple.
You seem to be referring to the lazy_tuple as the hook, I am saying that _I_ 
could implement a lazy class if hooks existed. i.e. I could make a class 
`LazyTuple` that when instanced with a list, creates and stores the hooks on 
itself. 

> > How is this supposed to work in practice?
A method e.g. `create_hook(method, callback)` would return a concrete reference 
to the hook, and uses a weak reference to know if it needs to execute the 
callback (meaning that it would only add the overhead of a check for callbacks 
if the concrete reference still existed).

> > Where does the hook live? When 
> is it called? What does it do?
> How does the lazy tuple know that the list's setitem has been called?

It knows because of a hook? This is my whole point about including hooks in 
this thread, i.e. if it was possible to add a callback on a method, it would 
execute when it is called. I am not sure I understand your question.
___
Python-ideas mailing list -- python-ideas@python.org
To unsubscribe send an email to python-ideas-le...@python.org
https://mail.python.org/mailman3/lists/python-ideas.python.org/
Message archived at 
https://mail.python.org/archives/list/python-ideas@python.org/message/GD3TTQPULXGVQIKQUTERF6MAOD5WUS4B/
Code of Conduct: http://python.org/psf/codeofconduct/


[Python-ideas] Re: Lazy Type Casting

2020-12-09 Thread Mathew Elman
Stestagg wrote:
> That makes sense, so these are kind of 'views' over a sequence, but ones
> that implement a copy-on-write when the underlying object is modified in
> any way?

yes, a lazy sequence type would be exactly that, that is a nice way of putting 
it

> I can see this being super hard/impossible to implement reliably, but would
> be a pretty nice addition if it can be done.
___
Python-ideas mailing list -- python-ideas@python.org
To unsubscribe send an email to python-ideas-le...@python.org
https://mail.python.org/mailman3/lists/python-ideas.python.org/
Message archived at 
https://mail.python.org/archives/list/python-ideas@python.org/message/TI7KE4SLB3C2GHU3W2B6BOCL3ER3JLZO/
Code of Conduct: http://python.org/psf/codeofconduct/


[Python-ideas] Re: Lazy Type Casting

2020-12-09 Thread Mathew Elman
I agree that if you are using them as iterables, then the type is usually not 
important because you are treating their type as just iter-able. The lazy 
iterable would more or less just be the same as passing in `iter(sequence)`.

This is for other use cases where the use of the object is specific to the 
type, e.g. a case where in the outer scope you construct a list and mutate it 
but when it is passed to an inner scope, you want to enforce that it can be 
accessed but not mutated. Likewise if lazy built in types were implemented in 
python then getting a slice of a sequence could also be done lazily, whereas my 
understanding at the moment is that it has to create a whole new sequence.
___
Python-ideas mailing list -- python-ideas@python.org
To unsubscribe send an email to python-ideas-le...@python.org
https://mail.python.org/mailman3/lists/python-ideas.python.org/
Message archived at 
https://mail.python.org/archives/list/python-ideas@python.org/message/ZQIXX5632QT7QH5YCZGTTLPJ5ZQF7XOH/
Code of Conduct: http://python.org/psf/codeofconduct/


[Python-ideas] Re: Lazy Type Casting

2020-12-09 Thread Mathew Elman
Steven D'Aprano wrote:
> On Tue, Dec 08, 2020 at 11:46:59AM -0000, Mathew Elman wrote:
> > I would like to propose adding lazy types for casting
> > builtins in a 
> > lazy fashion. e.g. lazy_tuple which creates a reference to the 
> > source iterable and a morally immutable sequence but only populates 
> > the tupular container when it or the source is used.
> > What are your use-cases for this?
> Does this include things like lazy_list, lazy_float,
> lazy_bool, 
> lazy_str, lazy_bytearray etc?

I would say yes, it should include these types as well. 
The use case is for when you are casting between types a high number of times 
to pass them around, especially into another type and back.

> > An alternative to adding lazy types / lazy type
> > casting (making it 
> > possible to implement these oneself) would be to add method call hooks 
> > to python, since this would allow having a "freeze value" callback 
> > hooked into the __setitem__ and __getitem__ methods.  Hooks may be a 
> > more useful solution for wider use cases as well.
> > Nope, sorry, I don't see how that would work. Here I have a list:
> L = [50, 40, 30, 20, 10]
> 
> Suppose these hooks exist. I want to make a "lazy tuple":
> t = lazy_tuple(L)
> 
> How do these hooks freeze the list?

they don't freeze the list, they freeze the values in the lazy_tuple when the 
list is mutated, so when mutating the list, the values in the tuple are set (if 
they have not been already), so that they aren't also mutated in the 
lazy_tuple. Of course for delete and insert this would mean you might have to 
"freeze" from where the insert/delete occurs to the end of the tuple but that 
is no different than using a normal tuple i.e. iterate over all elements. 
However for setitem where only position i is replaced, the tuple can set its 
value to the original without having to evaluate anything extra.

> What if I have more than one lazy object pointing at the same source?
> s = lazy_str(L)
> 
> And then follow with a different method call?
> L.insert(2, "surprise!")
> 
> I just can't see how this will work.

I don't follow what your point is, sorry. Are you saying that insert is another 
method that can update a list so delitem and setitem hooks would miss it?
The point I was making with hooks is that you _could_ write a lazy class that 
creates freezing hooks for any mutation method. But the hooks would be up to 
the coder to implement and hook into the correct mutation methods.

I also don't see an issue with multiple lazy types pointing to the same 
"source". It would just freeze the values in both of them when updating 
anything in the original.
___
Python-ideas mailing list -- python-ideas@python.org
To unsubscribe send an email to python-ideas-le...@python.org
https://mail.python.org/mailman3/lists/python-ideas.python.org/
Message archived at 
https://mail.python.org/archives/list/python-ideas@python.org/message/YJ4GVP3KOB2WRU2EY3QO2XGNIFJAGZS2/
Code of Conduct: http://python.org/psf/codeofconduct/


[Python-ideas] Lazy Type Casting

2020-12-08 Thread Mathew Elman
I am not sure if this has been suggested before, so my apologies if it has.

I would like to propose adding lazy types for casting builtins in a lazy 
fashion. e.g. `lazy_tuple` which creates a reference to the source iterable and 
a morally immutable sequence but only populates the tupular container when it 
or the source is used.

Note that if the original object is not a built-in, will not be used after 
casting  _or_ is immutable, this is trivial to implement. The difficulty arises 
when this it not the case, since the lazy object needs to also freeze any 
values that are mutated in the original to avoid side-effects.

An alternative to adding lazy types / lazy type casting (making it possible to 
implement these oneself) would be to add method call hooks to python, since 
this would allow having a "freeze value" callback hooked into the __setitem__ 
and __getitem__ methods.  Hooks may be a more useful solution for wider use 
cases as well.
___
Python-ideas mailing list -- python-ideas@python.org
To unsubscribe send an email to python-ideas-le...@python.org
https://mail.python.org/mailman3/lists/python-ideas.python.org/
Message archived at 
https://mail.python.org/archives/list/python-ideas@python.org/message/SDAUO33DVPISBFQ52M2N4WEWPLJ4UDIS/
Code of Conduct: http://python.org/psf/codeofconduct/


[Python-ideas] Re: Make for/while loops nameable.

2020-12-03 Thread Mathew Elman
I personally am +1 for something like this.

What about for use with `continue` as well? e.g. 

> for i in range(10) as i_loop:
> for j in range(i, i + 10) as j_loop:
> if i + j == 9:
> continue i_loop

which will break out of j_loop and go to the next i (as if the `continue` 
statement were used)
___
Python-ideas mailing list -- python-ideas@python.org
To unsubscribe send an email to python-ideas-le...@python.org
https://mail.python.org/mailman3/lists/python-ideas.python.org/
Message archived at 
https://mail.python.org/archives/list/python-ideas@python.org/message/GOGKVVESAV5WZ3Z4BWDBHBYKJYINTLNC/
Code of Conduct: http://python.org/psf/codeofconduct/


[Python-ideas] Re: Adding PyInstaller to the standard library

2020-11-23 Thread Mathew Elman
> That's essentially like Java's JRE. For what it's worth, on my PC the
> JRE is 196M in size. Whereas a full Python distribution is only 94M,
> and the embedded distribution is 15M. So I think Python already has
> that, more or less.

I hadn't realised that, so thanks :)

> But my experience with the JRE is that very few applications actually
> use the "centralised" JRE, preferring to ship an embedded JRE. So the
> evidence from the Java world is that managing a central "runtime
> engine" is not actually as convenient as we're assuming, and the
> arguments for it simply aren't compelling in the real world. (Unix may
> have a different picture - there's a much stronger culture there of
> "depend on system packages" :shrug:)
> Paul

I imagine there would be a way to have an install install the runner if there 
is not one on the machine, and use the existing one if there is, and creating a 
venv in either case. Meaning that using the equivalent of an embedded JRE would 
be obsolete, no? 

I suppose my point is that having a utility for launching a python app from the 
desktop may be sufficient for a lot of use cases.
___
Python-ideas mailing list -- python-ideas@python.org
To unsubscribe send an email to python-ideas-le...@python.org
https://mail.python.org/mailman3/lists/python-ideas.python.org/
Message archived at 
https://mail.python.org/archives/list/python-ideas@python.org/message/WENUAOE5DJHM27MDX2M4MF4VHMLMMIBL/
Code of Conduct: http://python.org/psf/codeofconduct/


[Python-ideas] Re: Adding PyInstaller to the standard library

2020-11-23 Thread Mathew Elman
I suppose functionally there may be little difference, but having an explicit 
"runner" would allow two things:

1. the runner and stdlib for it could be in a compress format itself since it 
doesn't need to provide any utility for editing or navigating human readable 
modules. and so lighter
2. it would handle "venv"ing and creating desktop shortcuts etc that would just 
start the python app in the engine. The reason I mention this here, is because 
others have said that including functionality to deal with this sort of thing 
for _all_ OS would be heavy, where as here it could be more lightweight and 
even not part of the standard python interpreter, just the runner.

Also on systems with python already installed it could be told to use the 
existing python install, if that was desired.
___
Python-ideas mailing list -- python-ideas@python.org
To unsubscribe send an email to python-ideas-le...@python.org
https://mail.python.org/mailman3/lists/python-ideas.python.org/
Message archived at 
https://mail.python.org/archives/list/python-ideas@python.org/message/GEYD5SVEO3YV2NNSLNLNQPAYAHZJOCU6/
Code of Conduct: http://python.org/psf/codeofconduct/


[Python-ideas] Re: Adding PyInstaller to the standard library

2020-11-23 Thread Mathew Elman
> > Oh, and Chrome itself needs to be updated -- only on
> > what, millions of machines? V8 is bundled with Chrome -- you know, kind of 
> > like a
> > PyInstaller app bundles Python ;-)
> > Uhhh... no, that's kind of like how Python bundles Python. That's not
> bundling an app. You update Chrome once, and every app is updated.
> Again, thank you for restating my point, but trying to make it sound
> like a counter-argument.

I would argue this sounds like a case for a "python_runner", i.e. a lightweight 
python vm that can run python apps, e.g. zipapps. Something like the 
blender_runner for blender. Making it explicitly an app that runs via some 
other engine.
 
It would then be a central entry-point that can be updated to a later python 
and all the apps update with it.
It would have to provide a utility for desktop shortcuts to feel like the 
python app was launching natively.
___
Python-ideas mailing list -- python-ideas@python.org
To unsubscribe send an email to python-ideas-le...@python.org
https://mail.python.org/mailman3/lists/python-ideas.python.org/
Message archived at 
https://mail.python.org/archives/list/python-ideas@python.org/message/GVDPNVWNGZEBKBH75OF6QBUN3YBDCEPC/
Code of Conduct: http://python.org/psf/codeofconduct/


[Python-ideas] Re: Adding PyInstaller to the standard library

2020-11-19 Thread Mathew Elman
Perhaps there could be something in the std-lib that allowed packaging into an 
executable but with some limitations, as a toy example: only supporting the 
std-lib dependencies. There is some precedence for minimal implementations 
existing in std-lib and third party libraries being more capable e.g. simple 
http server. So something like PyInstaller would be for when you need something 
more powerful, like support for third party libraries in the toy example 
limitation.

This could amount to adding certain extra features/behaviour to the zipapp 
module and a lightweight python_runner app (something like blender_runner for 
blender)
___
Python-ideas mailing list -- python-ideas@python.org
To unsubscribe send an email to python-ideas-le...@python.org
https://mail.python.org/mailman3/lists/python-ideas.python.org/
Message archived at 
https://mail.python.org/archives/list/python-ideas@python.org/message/LMSQHDWAFBYVPSOP7FFYETPZU66MEUYP/
Code of Conduct: http://python.org/psf/codeofconduct/


[Python-ideas] Re: A python_include() for cgi programming

2020-11-04 Thread Mathew Elman
The recommended way to import files this way is rather to use `importlib`.
___
Python-ideas mailing list -- python-ideas@python.org
To unsubscribe send an email to python-ideas-le...@python.org
https://mail.python.org/mailman3/lists/python-ideas.python.org/
Message archived at 
https://mail.python.org/archives/list/python-ideas@python.org/message/4EE6OJGRDP3LBWSB2ZRAYS6VOEPDR72U/
Code of Conduct: http://python.org/psf/codeofconduct/


[Python-ideas] Re: except-try block

2020-10-12 Thread Mathew Elman
This is quite similar to something I suggested on Python Discussions 
https://discuss.python.org/t/add-way-to-reenter-previous-try-block/4526
___
Python-ideas mailing list -- python-ideas@python.org
To unsubscribe send an email to python-ideas-le...@python.org
https://mail.python.org/mailman3/lists/python-ideas.python.org/
Message archived at 
https://mail.python.org/archives/list/python-ideas@python.org/message/EXWK52CP4P42GJCDX7E6XXDF6V75ZRJO/
Code of Conduct: http://python.org/psf/codeofconduct/


[Python-ideas] Re: Make start, stop, step properties on islice

2020-08-13 Thread Mathew Elman
You're absolutely right, I realized that __len__ would be the maximum possible 
length after posting, and it would likely be more dangerous than helpful
___
Python-ideas mailing list -- python-ideas@python.org
To unsubscribe send an email to python-ideas-le...@python.org
https://mail.python.org/mailman3/lists/python-ideas.python.org/
Message archived at 
https://mail.python.org/archives/list/python-ideas@python.org/message/RHTEFUOMWIGPVHXN46YPTL2RDHHB6RPQ/
Code of Conduct: http://python.org/psf/codeofconduct/


[Python-ideas] Make start, stop, step properties on islice

2020-08-12 Thread Mathew Elman
Is there a reason that itertools.islice does not provide its start, stop and 
step values as attributes, similar to range?
This seems like a sensible and useful thing to have, and would also allow 
islice's to have a __len__.

Mathew
___
Python-ideas mailing list -- python-ideas@python.org
To unsubscribe send an email to python-ideas-le...@python.org
https://mail.python.org/mailman3/lists/python-ideas.python.org/
Message archived at 
https://mail.python.org/archives/list/python-ideas@python.org/message/UQD5GKMAPSPSJ655EQOMZJS42OKBD754/
Code of Conduct: http://python.org/psf/codeofconduct/


[Python-ideas] Re: Idea: Extend "for ... else ..." to allow "for ... if break ..." else

2020-08-06 Thread Mathew Elman
Thank you both for the feedback.

Some pros and cons that occur to me (I may be biased, YMMV):
> Pros:
> (1) It can cleanly separate the handling of break-type exceptions and
> other exceptions, if needed.
> (2) It actually clarifies what the dreaded "else" means!
> (3) it allows you to group your "break" cases using exception
> subclasses (although this is probably OTT for most use cases).
> Cons:
> (4) It's more work.  You have to decide what exceptions to use and
> (most likely) create them.
>
(5) It adds the runtime overhead of setting up the "try" and possibly
> raising the exception.
> (6) Putting (implicitly) try...except around a possibly long for-suite
> feels bad somehow, even though it wouldn't catch other unwanted
> exceptions.
> (7) It does not catch the "zero iterations" case.
>

It is possible that 4 and 7 may be fixed by adding 2 new Exception
subclasses, e.g. `BreakException`, which would "replace" break although
using break would still be possible, and `NoIterationException` (though
this may not be the cleanest approach). The question then becomes what to
do with these when there is no `except`. At the sacrifice of automatically
breaking out of multiple loops, they could be silently ignored unless
caught explicitly?

I do not know well enough how the python interpreter sets up `try-except`
blocks to realistically respond to 5 and 6 but I can indeed see these being
sticking points.

On Thu, 6 Aug 2020 at 08:57, Stephen J. Turnbull <
turnbull.stephen...@u.tsukuba.ac.jp> wrote:

> Mathew Elman writes:
>
>  > Being able to break multiple loops and having "labelled" breaks
>  > would be achievable using `except`, i.e. adding `except` to the
>  > loop statements before `else` like this:
>
> This would certainly be consistent with the existing use of the except
> keyword, unlike the proposal to have it take both exceptions (in 'try'
> statements) and break labels (in 'for' and 'while' statements).
>
> However, we would probably not want to burden all loops with the
> exception-handling machinery, so the compiler would have to do some
> hacky backtracking (I doubt that the arbitrary lookahead needed to
> handle "maybe we got some except clauses coming?" during parsing would
> be acceptable) and fill that in *after* recognizing that there are
> except clauses in this for statement.
>

Would it be so bad to simply wrap for loops with except clauses
automatically that can be clobbered or not?
e.g.

> for x in iterable:
> ...
>
really does something like this

> try:
>
for x in iterable:
> ...
> except Exception:
> raise
>

Meaning that it doesn't need to wait to see if it does and backtrace but
can just trust that there will be the default reraise? Apologies if this is
a stupid question.

Second, generally Python tries to avoid overloading keywords with
> multiple semantics.  The potential for confusion and misunderstanding
> of "except" (which I've suggested myself and now dislike) is pretty
> large I think.
>

I am not sure I follow you here since the `except` is being used in the
same way as in `try...except` so I wouldn't expect a high potential for
confusion, although I suppose that is, ironically, the same line of
thinking as with `for...else`.


> It might be possible to save that level of indentation with this
> syntax:
>
> try for elem in iterable:
> ...
> if should_break(elem):
> raise SomeException
> except SomeException as e:
> handle_break_behaviour(e)
> else:
> print("Did not break")
>
> (and I suppose you could do the same for any control flow statement,
> although I'm not sure offhand that the various keywords are 100%
> disjoint -- that would need to be checked).  But I don't think it's
> worth it.  I don't see enough benefits from this mixing of try and for
> to make it worth the complexity.
>

I agree that this seems to add some complexity but I actually like this a
lot. It would surely also address the issue of the parser knowing it should
be looking for exceptions or not?


>  > I (and others) have suggested this before and no one has said it's a
>  > *bad *option,
>
> It is, though, for the reasons above as well as the reasons Rob gives
> in his parallel followup.
>

Thank you, I appreciate it at least being addressed!

-- 


Notice: 
This email is confidential and may contain copyright material of 
members of the Ocado Group. Opinions and views expressed in this message 
may not necessarily reflect the opinions and views of the members of the 
Ocado Group.

If you are not the intended recipient, please notify us 
immediately and delete all copies of this me

[Python-ideas] Re: Idea: Extend "for ... else ..." to allow "for ... if break ..." else

2020-08-05 Thread Mathew Elman
Being able to break multiple loops and having "labelled" breaks would be
achievable using `except`, i.e. adding `except` to the loop statements
before `else` like this:

for elem in iterable:
> ...
> if should_break(elem):
> raise SomeException
> except SomeException as e:
> handle_break_behaviour(e)
> else:
> print("Did not break")
>

would be sugar for:

try:
> for elem in iterable:
> ...
> if should_break(elem):
> raise SomeException
> except SomeException as e:
> handle_break_behaviour(e)
> else:
> print("Did not break")
>

I (and others) have suggested this before and no one has said it's a
*bad *option,
it's just been ignored, despite seeming to be an intuitive way to
accomplish `else` clarity, "labelled" breaks and breaking from multiple
loops. Is there a reason that this suggestion is worse / no better than
adding special break syntax?

As for an example for labelled breaks how about something of the form:

def insert_ordered_no_duplicates(duplicate_free_list, item):
> for i, elem in enumerate(duplicate_free_list):
> if elem == item:
> break already_present
> if elem > item:
> break location_found
> case already_present:
> return duplicate_free_list
> case location_found:
> new_list = duplicate_free_list[:]
> new_list.insert(i, item)
> return new_list
> new_list = duplicate_free_list[:]
> new_list.append(item)
> return new_list
>

which you can conceivably have a nested case where you don't want to let
duplicate inserts even be attempted like this:

def insert_many_ordered_strictly_no_duplicates(dup_free_list, items):
> new_list = dup_free_list[:]
> for item in items:
> for i, elem in new_list:
> if elem == item:
> break already_present
> if elem > item:
> break location_found
> case already_present:
> break duplicates_attempted
> case location_found:
> new_list.insert(i, item)
> else:
> new_list.append(item)
> case duplicates_attempted:
> return dup_free_list[:]
> return new_list
>


On Wed, 5 Aug 2020 at 13:40, Rob Cliffe via Python-ideas <
python-ideas@python.org> wrote:

> I note that both of these examples could be handled by having a way to
> break out of 2 loops at a time.
> Rob
>
> On 29/07/2020 12:33, Jonathan Fine wrote:
>
> Thank you all, particularly Guido, for your contributions. Having some
> examples will help support the exploration of this idea.
>
> Here's a baby example - searching in a nested loop. Suppose we're looking
> for the word 'apple' in a collection of books. Once we've found it, we stop.
>
> for book in books:
> for page in book:
> if 'apple' in page:
> break
> if break:
> break
>
> However, suppose we say that we only look at the first 5000 or so words in
> each book. (We suppose a page is a list of words.)
>
> This leads to the following code.
>
> for book in books:
> word_count = 0
> for page in book:
> word_count += len(page)
> if word in page:
> break
> if word_count >= 5000:
> break found
> if break found:
> break
>
> At this time, I'd like us to focus on examples of existing code, and
> semantics that might be helpful. I think once we have this, the discussion
> of syntax will be easier.
>
> By the way, the word_count example is as I typed it, but it has a typo.
> Did you spot it when you read it? (I only noticed it when re-reading my
> message.)
>
> Finally, thank you for your contributions. More examples please.
>
> --
> Jonathan
>
>
>
>
>
> ___
> Python-ideas mailing list -- python-ideas@python.org
> To unsubscribe send an email to 
> python-ideas-leave@python.orghttps://mail.python.org/mailman3/lists/python-ideas.python.org/
> Message archived at 
> https://mail.python.org/archives/list/python-ideas@python.org/message/ECALTXEP7M3YWAQCHLPRWPBJRQKQICBC/
> Code of Conduct: http://python.org/psf/codeofconduct/
>
>
> ___
> Python-ideas mailing list -- python-ideas@python.org
> To unsubscribe send an email to python-ideas-le...@python.org
> https://mail.python.org/mailman3/lists/python-ideas.python.org/
> Message archived at
> https://mail.python.org/archives/list/python-ideas@python.org/message/YV4V2FYLT5SNWOCH7TZNXYCQRAQZ6R33/
> Code of Conduct: http://python.org/psf/codeofconduct/
>

-- 


Notice: 
This email is confidential and may contain copyright material of 
members of the Ocado Group. Opinions and views expressed in this message 
may not necessarily reflect the opinions and views of the members of the 
Ocado Group.

If you are not the intended recipient, please notify us 
immediately and delete all 

[Python-ideas] Re: Idea: Extend "for ... else ..." to allow "for ... if break ..." else

2020-07-29 Thread Mathew Elman
On Wed, 29 Jul 2020 at 14:42, Guido van Rossum  wrote:

> On Wed, Jul 29, 2020 at 02:51 Mathew Elman  wrote:
>
>>
>> .
>>
>>> If it *is* useful, it occurs to me that (1) this looks a lot like the
>>> try ... except ... pattern, and (2) breaks are generally perceived as
>>> exceptional exits from a loop.  Instead of "if break [LABEL]", "except
>>> [LABEL]" might work, although the semantic difference between labels
>>> and exceptions might get a ton of pushback.
>>
>> ...
>>>
>> Steve
>>>
>>
>> In the related thread I suggested using `except`, but it was largely
>> ignored.
>>
>>
>> *If* you want tou propose clearer syntax for this, please extend the loop
>>> syntax, not the ‘if’ syntax. So, ‘case ... zero’ makes more sense than ‘if
>>> [not] break’.
>>>
>>
>>> —Guido
>>>
>>
>> So I understand, does this mean that any extended syntax for this should
>> be *totally* new and not draw on existing constructs such as
>> `try-except` or `if-else`?
>> Or just that the additional clarity should come from  extending the loop
>> rather than the implicit `if`?
>>
>
> Actually, given that ‘else:’ already confuses people I very much doubt
> that any other new construct will be acceptable. It is totally five not to
> “solve” this problem at all — all use cases can be done by adding flag
> variables explicitly manipulated by the user’s code.
>
I understand that the "problem" with `else` is aesthetic, though one could
debate the importance of such a problem.

What I mean to ask is, for example,  would having `for-except-else`
(analogous to `try-except-else`) be an acceptable extension of "the loop
syntax, not the ‘if’ syntax"?


>> Mathew
>>
>>
>> Notice:
>> This email is confidential and may contain copyright material of members
>> of the Ocado Group. Opinions and views expressed in this message may not
>> necessarily reflect the opinions and views of the members of the Ocado
>> Group.
>>
>> If you are not the intended recipient, please notify us immediately and
>> delete all copies of this message. Please note that it is your
>> responsibility to scan this message for viruses.
>>
>> References to the "Ocado Group" are to Ocado Group plc (registered in
>> England and Wales with number 7098618) and its subsidiary undertakings (as
>> that expression is defined in the Companies Act 2006) from time to time.
>> The registered office of Ocado Group plc is Buildings One & Two, Trident
>> Place, Mosquito Way, Hatfield, Hertfordshire, AL10 9UL.
>> ___
>> Python-ideas mailing list -- python-ideas@python.org
>> To unsubscribe send an email to python-ideas-le...@python.org
>> https://mail.python.org/mailman3/lists/python-ideas.python.org/
>> Message archived at
>> https://mail.python.org/archives/list/python-ideas@python.org/message/TVTCXQN5KDMQUCFQ7AJES2RISPFD6OTL/
>> Code of Conduct: http://python.org/psf/codeofconduct/
>>
> --
> --Guido (mobile)
>

-- 


Notice: 
This email is confidential and may contain copyright material of 
members of the Ocado Group. Opinions and views expressed in this message 
may not necessarily reflect the opinions and views of the members of the 
Ocado Group.

If you are not the intended recipient, please notify us 
immediately and delete all copies of this message. Please note that it is 
your responsibility to scan this message for viruses.

References to the 
"Ocado Group" are to Ocado Group plc (registered in England and Wales with 
number 7098618) and its subsidiary undertakings (as that expression is 
defined in the Companies Act 2006) from time to time. The registered office 
of Ocado Group plc is Buildings One & Two, Trident Place, Mosquito Way, 
Hatfield, Hertfordshire, AL10 9UL.
___
Python-ideas mailing list -- python-ideas@python.org
To unsubscribe send an email to python-ideas-le...@python.org
https://mail.python.org/mailman3/lists/python-ideas.python.org/
Message archived at 
https://mail.python.org/archives/list/python-ideas@python.org/message/YTC6Z4DHUOXSKS7L6MM4HQ4WSZAGVSET/
Code of Conduct: http://python.org/psf/codeofconduct/


[Python-ideas] Re: Idea: Extend "for ... else ..." to allow "for ... if break ..." else

2020-07-29 Thread Mathew Elman
.

> If it *is* useful, it occurs to me that (1) this looks a lot like the
> try ... except ... pattern, and (2) breaks are generally perceived as
> exceptional exits from a loop.  Instead of "if break [LABEL]", "except
> [LABEL]" might work, although the semantic difference between labels
> and exceptions might get a ton of pushback.

...
>
Steve
>

In the related thread I suggested using `except`, but it was largely
ignored.


*If* you want tou propose clearer syntax for this, please extend the loop
> syntax, not the ‘if’ syntax. So, ‘case ... zero’ makes more sense than ‘if
> [not] break’.
>

> —Guido
>

So I understand, does this mean that any extended syntax for this should be
*totally* new and not draw on existing constructs such as `try-except` or
`if-else`?
Or just that the additional clarity should come from  extending the loop
rather than the implicit `if`?

Mathew

-- 


Notice: 
This email is confidential and may contain copyright material of 
members of the Ocado Group. Opinions and views expressed in this message 
may not necessarily reflect the opinions and views of the members of the 
Ocado Group.

If you are not the intended recipient, please notify us 
immediately and delete all copies of this message. Please note that it is 
your responsibility to scan this message for viruses.

References to the 
"Ocado Group" are to Ocado Group plc (registered in England and Wales with 
number 7098618) and its subsidiary undertakings (as that expression is 
defined in the Companies Act 2006) from time to time. The registered office 
of Ocado Group plc is Buildings One & Two, Trident Place, Mosquito Way, 
Hatfield, Hertfordshire, AL10 9UL.
___
Python-ideas mailing list -- python-ideas@python.org
To unsubscribe send an email to python-ideas-le...@python.org
https://mail.python.org/mailman3/lists/python-ideas.python.org/
Message archived at 
https://mail.python.org/archives/list/python-ideas@python.org/message/TVTCXQN5KDMQUCFQ7AJES2RISPFD6OTL/
Code of Conduct: http://python.org/psf/codeofconduct/


[Python-ideas] Re: New clause in FOR and WHILE instead of ELSE

2020-07-24 Thread Mathew Elman
On Thu, 23 Jul 2020 at 16:25, Stephen J. Turnbull <
turnbull.stephen...@u.tsukuba.ac.jp> wrote:

> Mathew Elman writes:
>
>  > Frankly, saying that a part of a language that is frequently
>  > misunderstood, is *never* allowed to be improved is disappointing
>  > when the suggestion that it can be (somehow) has been so well
>  > received by everyone else.
>
> The highly improbable is frequently well-received.
>
> What can surely be improved is the documentation, specifically the
> Tutorial.  Something like
>
> The else clause of a loop statement has frequently been
> misunderstood.  In a for or while loop *statement*, on each
> iteration, the condition is tested and exactly one of the
> following occurs:
>
> 1.  If truthy, the loop *suite* runs to completion and the test is
> repeated for the next iteration,
> 2.  OR the loop *suite* runs and there is a nonlocal exit such as
> return or break or raise, which exits the statement as well.
> 3.  OTHERWISE the condition is false, and the else suite, if any,
> runs, then the statement is exited.
>
> The emphasis is for contrast in this discussion.  The Language
> Reference already says precisely this, although much more concisely.
>
> I don't expect supporters of "elif not break" etc to think this is
> sufficient, and supporters of the Else Ban similarly.  Please consider
> if this is helps clarify the Tutorial, and if it doesn't get booed
> into oblivion, I'll work up a patch (I think that the section on
> control flow would benefit from some reorganization as well, "just
> stick it in somewhere" is not what I have in mind :-).
>

Credit where credit is due, I think this is definitely an improvement. It
does make it require slightly less meticulous reading to understand `else`.
However, I still think that there is value in improving the `for...else`
and `while...else` intuitiveness, if it can be done at an acceptable cost.
(As is the case with any change)

IMO the solution is not to change `else` but to add an additional with the
opposite meaning that makes the use of `else` with `for` and `while` more
intuitive, such as adding `elif`, which feels natural, and a special
boolean, which perhaps doesn't. Or adding `except` for catching raised
Exceptions  rather than breaks, which makes `else` clearly behave how it
does for `try`. Or another solution that achieves the additional clarity
*without* removing/changing else itself.



> Steve
>

-- 


Notice: 
This email is confidential and may contain copyright material of 
members of the Ocado Group. Opinions and views expressed in this message 
may not necessarily reflect the opinions and views of the members of the 
Ocado Group.

If you are not the intended recipient, please notify us 
immediately and delete all copies of this message. Please note that it is 
your responsibility to scan this message for viruses.

References to the 
"Ocado Group" are to Ocado Group plc (registered in England and Wales with 
number 7098618) and its subsidiary undertakings (as that expression is 
defined in the Companies Act 2006) from time to time. The registered office 
of Ocado Group plc is Buildings One & Two, Trident Place, Mosquito Way, 
Hatfield, Hertfordshire, AL10 9UL.
___
Python-ideas mailing list -- python-ideas@python.org
To unsubscribe send an email to python-ideas-le...@python.org
https://mail.python.org/mailman3/lists/python-ideas.python.org/
Message archived at 
https://mail.python.org/archives/list/python-ideas@python.org/message/TN7G7VPAOUKW7FPCYYU5CZIKNSIQPMPX/
Code of Conduct: http://python.org/psf/codeofconduct/


[Python-ideas] Re: New clause in FOR and WHILE instead of ELSE

2020-07-22 Thread Mathew Elman
On Wed, 22 Jul 2020 at 13:45, Paul Moore  wrote:

> On Wed, 22 Jul 2020 at 13:18, Mathew Elman  wrote:
> >> Ones that retain else on loops are bad because
> >> they end up providing two (typically equally confusing) ways of doing
> >> things.
> >
> > I don't think this is the case. I agree that adding an alternative to
> `else` just to have an alternative is not a good fix, but adding explicit
> ways to refer to when breaking from the loop would make the use of `else`
> as it already is clearer.
> >
> > For example, breaking the change into 2 parts:
> > 1. Adding `elif` to the `for...else` and `while...else` statements seems
> a logical extension. Guido has even said that the else in loops was
> invented by reasoning the connection of `if` to `while` (and then `while`
> to `for`). Perhaps this should be in its own discussion so as not to
> clutter this thread?
>
> IMO, allowing
>
> for ...
> elif x == 2:
> do something
>
> to mean "if we didn't break out of the loop, and x is 2" would be
> really confusing.


I don't think this would be any more confusing than `for...else` already
is, and `while...elif...else` still seems like a logical extension of
`while...else`.

x=0
while x < 10:
delta = get_delta(x)
if delta == 0:
break
x += delta
elif x%2:
print(f"{x} is odd and > 10")
else:
print(f"{x} is even and > 10")



> And to have the elif after a loop be limited to a
> different set of conditions than "ordinary" elif would *also* be
> really confusing.
>

Absolutely! I would not suggest limiting it to any special cases. Hence why
I split up the change. Adding a way to *also* use the elif to check the
state of the loop is a separate discussion. Be that by using `break` as a
special boolean or some other way.


> > 2. Adding a way to use this new `elif` to check the state of the loop.
> Possibly including if it was broken out of or if it was never entered. Such
> as having special local variables that are only defined in the block/frame
> of the loop.
>
> Same logic here - if we allow "elif not break" (for example), it would
> be really confusing to *arbitrarily* only allow that if the elif is
> attached to a loop. So we need to define what
>
> if x == 2:
> do something
> elif not break:
> what?
>

means in general code. And that means inventing rules for the scope of
> "break as an expression".

And in a similar vein, what does it mean to
> pass "break" to a function?
>
> def invert(flag):
> return not flag
>
> for
> ...
> elif invert(break):
> ...
>

That is fair enough, like I have said I am not attached (though others may
be) to the idea of using `break` as a special boolean. Would it be more
feasible to have a variable that persists beyond the scope of the loop and
is not `break` but something else? For example, and this is not 100%
serious but something like : `iter.broken`, `iter.enetered` etc.


>
> It's not that any of these things are *reasonable* to do, it's that
> all the special cases needed to disallow them would be confusing, and
> if we *didn't* disallow them, all of the rules needed to give them
> meaning in (conceded) unreasonable places would be confusing.
>
> The trick here is *not* to look at the case that you expect the
> construct to be used in - obviously it'll look good to you in that
> context, if you like the idea at all. What you need to look at is all
> the other ways it could be applied, and verify that the costs justify
> the improvement that you saw when you first encountered the idea.
>

Good point, I think this is a well made argument for *not* making `break`
have a second meaning.

-- 


Notice: 
This email is confidential and may contain copyright material of 
members of the Ocado Group. Opinions and views expressed in this message 
may not necessarily reflect the opinions and views of the members of the 
Ocado Group.

If you are not the intended recipient, please notify us 
immediately and delete all copies of this message. Please note that it is 
your responsibility to scan this message for viruses.

References to the 
"Ocado Group" are to Ocado Group plc (registered in England and Wales with 
number 7098618) and its subsidiary undertakings (as that expression is 
defined in the Companies Act 2006) from time to time. The registered office 
of Ocado Group plc is Buildings One & Two, Trident Place, Mosquito Way, 
Hatfield, Hertfordshire, AL10 9UL.
___
Python-ideas mailing list -- python-ideas@python.org
To unsubscribe send an email to python-ideas-le...@python.org
https://mail.python.org/mailman3/lists/python-ideas.python.org/
Message archived at 
https://mail.python.org/archives/list/python-ideas@python.org/message/2XU5PSUKBYR3PA6SY635G4XSLELPMXXX/
Code of Conduct: http://python.org/psf/codeofconduct/


[Python-ideas] Re: New clause in FOR and WHILE instead of ELSE

2020-07-22 Thread Mathew Elman
On Wed, 22 Jul 2020 at 12:24, Paul Moore  wrote:

> On Wed, 22 Jul 2020 at 10:54, Stestagg  wrote:
> >
> > I'm (weakly) +1 for the concept of for..else being confusing, weird, and
> somehow not quite suitable/useful for many use-cases where it feels like it
> should.
> >
> > I'm -1 for each of the suggested improvements that I've understood so
> far.
> >
> > I agree that the suggested 'ban' on changes in this area is probably not
> helpful, however it feels like a sloppy way of saying that changes to the
> syntax are very unlikely to be practical, for a couple of annoying, but
> important reasons.
>
> I agree that for/while..else is not immediately obvious. But it's
> useful in some situations, and it *is* used in real-world code.
>
agreed.


> I also agree that all of the proposals I've seen so far are at *least*
> as confusing, and would make the situation worse, not better.
> Generalising a bit, proposals that suggest *removing* else on loops
> are never going to get accepted, because they break existing code for
> no clear advantage.

 again, agreed.

> Ones that retain else on loops are bad because
> they end up providing two (typically equally confusing) ways of doing
> things.
>

I don't think this is the case. I agree that adding an alternative to
`else` just to have an alternative is not a good fix, but adding explicit
ways to refer to when breaking from the loop would make the use of `else`
as it already is clearer.

For example, breaking the change into 2 parts:
1. Adding `elif` to the `for...else` and `while...else` statements seems a
logical extension. Guido has even said that the else in loops was invented
by reasoning the connection of `if` to `while` (and then `while` to `for`).
Perhaps this should be in its own discussion so as not to clutter this
thread?
2. Adding a way to use this new `elif` to check the state of the loop.
Possibly including if it was broken out of or if it was never entered. Such
as having special local variables that are only defined in the block/frame
of the loop.


> I don't think there's going to be any sort of "ban" on changing
> things, but I do think that it's reasonable to point out to people
> that all of this discussion is a waste of energy, and a distraction
> for people trying to follow this list for proposals that *do* have a
> chance of acceptance. The signal to noise ratio on this list can be
> bad at the best of times, and dropping ideas that simply won't work
> would help everyone. That's not to say that ideas that won't work
> aren't welcome - how will anyone learn what's feasible and what isn't
> if we shut down well-intentioned proposals? But proposers (and other
> participants) also need to accept that pushing an idea that isn't
> workable, is unproductive.
>

I agree with you here too, 100%, but it does not feel like we have had said
discussion. I would also make the suggestion that surely this thread,
although noisey, is the right place to continue the discussion in case a
consensus on an approach is reached.

-- 


Notice: 
This email is confidential and may contain copyright material of 
members of the Ocado Group. Opinions and views expressed in this message 
may not necessarily reflect the opinions and views of the members of the 
Ocado Group.

If you are not the intended recipient, please notify us 
immediately and delete all copies of this message. Please note that it is 
your responsibility to scan this message for viruses.

References to the 
"Ocado Group" are to Ocado Group plc (registered in England and Wales with 
number 7098618) and its subsidiary undertakings (as that expression is 
defined in the Companies Act 2006) from time to time. The registered office 
of Ocado Group plc is Buildings One & Two, Trident Place, Mosquito Way, 
Hatfield, Hertfordshire, AL10 9UL.
___
Python-ideas mailing list -- python-ideas@python.org
To unsubscribe send an email to python-ideas-le...@python.org
https://mail.python.org/mailman3/lists/python-ideas.python.org/
Message archived at 
https://mail.python.org/archives/list/python-ideas@python.org/message/QSO7PZE627OVPXJ64PZIFWCWA3LTVSLU/
Code of Conduct: http://python.org/psf/codeofconduct/


[Python-ideas] Re: New clause in FOR and WHILE instead of ELSE

2020-07-22 Thread Mathew Elman
On Wed, 22 Jul 2020 at 04:47, Paul Sokolovsky  wrote:

> Hello,
>
> On Tue, 21 Jul 2020 17:48:35 -0700
> Christopher Barker  wrote:
>
> > how about:
> >
> > for something in some_iterable:
> > some_stuff_with_maybe_a_break
> > else if not break:
> > something_more
> >
> > No new keywords :-)
> >
> > or:
> >
> > for something in some_iterable:
> > some_stuff_with_maybe_a_break
> > else:  # if not break:
> > something_more
>
> This is the most genius solution posted to this thread.
>
> And if the thread didn't die after van Rossum's post, I don't cheer
> hopes it would die now, but let me sprinkle in another "fresh"
> thought. First let me remind how this thread started:
>
> > ELSE-clause in FOR and WHILE has unclear syntax. I suggest new clause
> > instead
>
> Then various people started to throw in variants of even more unclear
> and confusing syntax (like "if" after "for"), with some percentage of
> those people demonstrating not understanding how the original "else"
> works.
>
> But consider following idea: if it's confusing, DO NOT USE it. You
> don't hear that often, but: treat Python as a generic programming
> language, not as a bag of tricks. The fact that most other languages
> don't have extra clause after "for" is enough of a reason to not use it
> in Python either.
>
> The problem isn't that it is unclear, the problem is that it is
misunderstood. If it was unclear what `for...else` means/does then yes,
do-not-use would fix the problem. The fact that it can and *is* *mis*understood
as doing something else means that people have to learn to not use
something that feels like it *should* be usable.

>
> So why it exists at all then? It's there for people who don't find it
> confusing, for very responsible use. As a random example, after
> studying 2 (bytecode) Python compilers and having written my own (so I
> know what code is generated from for-else), I no longer find it
> confusing. I actually found 2 intuitive ways to use that construct, in
> the very compiler mentioned - after all, if you eyeball a Python
> compiler, you either know, or ready to learn, how all language
> constructs work.
>
> For anything else - clear ban. Everyone should consider that too. (But
> please leave the language syntax alone (backwards compatibility, etc.),
> at least that's a suggestion which comes out from van Rossum's post).



Frankly, saying that a part of a language that is frequently misunderstood,
is *never* allowed to be improved is disappointing when the suggestion that
it can be (somehow) has been so well received by everyone else.


>
> > As for the "loop didn't run at all" case: Does anyone find a need for
> > that? Personally, I've found that everytime I do some kind of check
> > for an empty iterable before a loop, it was totally unnecessary.
>
> I find the need for that regularly. And I use the obvious syntax which
> everyone else uses:
>
> if not seq:
> print("This page is intentionally left blank")
> else:
> for i in seq:
> ...
>
> Any adhoc, confusing syntax someone may imagine to add, would go to the
> same "DO NOT USE" category. So, I pray to van Rossum's answer that
> something like that will never be added to the language. (Which is
> hard to hang hopes on, given all the mess added recently.)


Many people offering approaches is not muddling the thread. Clearly, most
people here agree that `for...else` is confusing/unintuitive on it's own,
and could be improved (not removed, but improved). The discussion was
trying to find an improvement that people agree on as well. The reason
there are so many offerings, is probably because everyone has had a similar
thought about it in the past.

-- 


Notice: 
This email is confidential and may contain copyright material of 
members of the Ocado Group. Opinions and views expressed in this message 
may not necessarily reflect the opinions and views of the members of the 
Ocado Group.

If you are not the intended recipient, please notify us 
immediately and delete all copies of this message. Please note that it is 
your responsibility to scan this message for viruses.

References to the 
"Ocado Group" are to Ocado Group plc (registered in England and Wales with 
number 7098618) and its subsidiary undertakings (as that expression is 
defined in the Companies Act 2006) from time to time. The registered office 
of Ocado Group plc is Buildings One & Two, Trident Place, Mosquito Way, 
Hatfield, Hertfordshire, AL10 9UL.
___
Python-ideas mailing list -- python-ideas@python.org
To unsubscribe send an email to python-ideas-le...@python.org
https://mail.python.org/mailman3/lists/python-ideas.python.org/
Message archived at 
https://mail.python.org/archives/list/python-ideas@python.org/message/VLKG6NE4DOX43NZIHSTSSV5POM6AZ2NQ/
Code of Conduct: http://python.org/psf/codeofconduct/


[Python-ideas] Re: New clause in FOR and WHILE instead of ELSE

2020-07-20 Thread Mathew Elman
On Sun, 19 Jul 2020 at 15:43, Олег Комлев  wrote:

> Thank to all disputants.
> It is possible to borrow the keyword "case" from PEP-622 (when it appears
> https://www.python.org/dev/peps/pep-0622). Keyword "case" can be written
> instead of "else/elif".  I.e.
> case COND:
>   ...
> [case COND:
>   ...]
> [case COND:
>   ...]
> All conditions COND must be different. Last  "case COND:" can be replaced
> with "else:".
>

For me this is -1 because "for... case" and "while... case" don't read like
english.

I also think the issue is less what keyword is used from "case", "if",
"except" or "joojoo" rather what the "COND" look like.
Obviously this depends on what the keyword is e.g. for "case"/"if" they
should be predicates, for "except" they should be exceptions and if adding
a new keyword it may be they are not needed.
But I would say deciding on those is the priority.

Side Note:
It does feel like "elif" should be part of the "for-else" and "while-else"
(especially while) compound statements.

-- 


Notice: 
This email is confidential and may contain copyright material of 
members of the Ocado Group. Opinions and views expressed in this message 
may not necessarily reflect the opinions and views of the members of the 
Ocado Group.

If you are not the intended recipient, please notify us 
immediately and delete all copies of this message. Please note that it is 
your responsibility to scan this message for viruses.

References to the 
"Ocado Group" are to Ocado Group plc (registered in England and Wales with 
number 7098618) and its subsidiary undertakings (as that expression is 
defined in the Companies Act 2006) from time to time. The registered office 
of Ocado Group plc is Buildings One & Two, Trident Place, Mosquito Way, 
Hatfield, Hertfordshire, AL10 9UL.
___
Python-ideas mailing list -- python-ideas@python.org
To unsubscribe send an email to python-ideas-le...@python.org
https://mail.python.org/mailman3/lists/python-ideas.python.org/
Message archived at 
https://mail.python.org/archives/list/python-ideas@python.org/message/BUFMJH6JEGEMUFTRUDQUZ3UFBH54QNWP/
Code of Conduct: http://python.org/psf/codeofconduct/


[Python-ideas] Re: New clause in FOR and WHILE instead of ELSE

2020-07-15 Thread Mathew Elman
The point is that `for-else` reads like "do this for loop ELSE (or but if
you can't loop) do this", i.e. roughly equivalent to this:

> try:
> loop_entered = False
> for loop_entered, elem in enumerate(iterable, start=1):
>pass
> assert loop_entered
> except AssertionError:
> print("loop not entered")
>
or

> loop_entered = False
> for loop_entered, elem in enumerate(iterable, start=1):
> pass
> if loop_entered:
> pass
> else:
> print("loop not entered")
>

But that isn't what it means. It means "do this for loop and if you
deliberately break out, continue ELSE (or if you don't break out) do this".
i.e. roughly equivalent to this:

> loop_broken = False
> for elem in iterable:
> if should_break(elem):
> loop_broken = True
> break
> if not loop_broken:
> print("you didn't break from the loop you maybe entered...")
>
or

> loop_broken = False
> for elem in iterable:
> if should_break(elem):
> loop_broken = True
> break
> if loop_broken:
>
pass
>
else:
>
print("you didn't break from the loop you maybe entered...")
>

which is not intuitive because `else` reads like it handles the unexpected
case, which one would have guessed was either breaking out or not entering
in the first place.

On Wed, 15 Jul 2020 at 09:23, Dominik Vilsmeier 
wrote:

> But `finally` with a `for` loop is redundant since the code can be placed
> just after the loop. For `try/except` it's a different situation since the
> exception might bubble up, so "normal" code after the `try` won't be
> reached.
>
> Also `on_break` doesn't seem really important since that code can be
> executed inside the loop right before the `break`.
>
> We already have `else` for `on_finish` and I think when recalling the
> analogy to exceptions it's not that confusing: a `try` block can be exited
> either normally (because all code has been executed) or because it raised
> an exception; here `else` means it exited normally. Similarly a `for` loop
> can terminate either normally by executing all iterations or because a
> `break` occurred; and similarly `else` means it terminated normally.
> On 15.07.20 08:47, Mathew Elman wrote:
>
> But in `for...else` the `else` call isn't always called, so changing
> `else` for `finally` doesn't make sense. What you're suggesting is
> replacing `else` with `on_finish` and adding `finally` and `on_break`.
>
> I agree that having `finally` could make the use cases of `else` clearer,
> but I am not convinced renaming "else" to "on_finish" would help the
> confusion for the 0 iteration case.
>
> I think that since this suggestion doesn't help with the 0 iteration case
> (my first idea here didn't either), it feels like added extra compound
> statements need to be immediately intuitive to be worth having - either
> because they read like a sentence or parallel existing python e.g.
> `try-except-else-finally` or `if-elif-else` etc.
>
>
> On Wed, 15 Jul 2020 at 06:47, Steve Barnes  wrote:
>
>> Can I suggest that for loops the `else` would be a lot clearer if it was
>> spelt `finally` as was done for PEP-0341 for try blocks and that we
>> might possibly need one or more `on_…` clauses such as `on_break` and `
>> on_finish` I think that this would be a lot clearer:
>>
>>
>>
>> for i in range(N):
>>
>> if i > 3:
>>
>> break;
>>
>> on_break:  # Called if loop was broken
>>
>> print(i)
>>
>> on_finish:  # Called if loop was not broken
>>
>> print("Loop Completed")
>>
>> finally:  # Always called (replaces for…else)
>>
>> print("Loop Ended")
>>
>>
>>
>> Which I think would be a lot easier for newcomers to learn than
>> try…for…else…except…else e.g.:
>>
>>
>>
>> try:
>>
>> for i in range(N):
>>
>>if i > 3:
>>
>> break;
>>
>>elif i % 2 == 0:
>>
>> raise ValueError("Odds Only");
>>
>> else: # to if
>>
>> print(i)
>>
>> else:  # Else to loop
>>
>> print("Loop Completed")
>>
>> except ValueError as err:
>>
>> print(err)
>>
>> else:  # to try
>>
>> print("No Exception")
>>
>> finally:
>>
>> print("Try Ended")
>>
>>
>>
>> Where the multitude of elses makes my eyes cross.
>>
>>
>>
>>

[Python-ideas] Re: New clause in FOR and WHILE instead of ELSE

2020-07-15 Thread Mathew Elman
But in `for...else` the `else` call isn't always called, so changing `else`
for `finally` doesn't make sense. What you're suggesting is replacing `else`
with `on_finish` and adding `finally` and `on_break`.

I agree that having `finally` could make the use cases of `else` clearer,
but I am not convinced renaming "else" to "on_finish" would help the
confusion for the 0 iteration case.

I think that since this suggestion doesn't help with the 0 iteration case
(my first idea here didn't either), it feels like added extra compound
statements need to be immediately intuitive to be worth having - either
because they read like a sentence or parallel existing python e.g.
`try-except-else-finally` or `if-elif-else` etc.


On Wed, 15 Jul 2020 at 06:47, Steve Barnes  wrote:

> Can I suggest that for loops the `else` would be a lot clearer if it was
> spelt `finally` as was done for PEP-0341 for try blocks and that we might
> possibly need one or more `on_…` clauses such as `on_break` and `on_finish`
> I think that this would be a lot clearer:
>
>
>
> for i in range(N):
>
> if i > 3:
>
> break;
>
> on_break:  # Called if loop was broken
>
> print(i)
>
> on_finish:  # Called if loop was not broken
>
> print("Loop Completed")
>
> finally:  # Always called (replaces for…else)
>
> print("Loop Ended")
>
>
>
> Which I think would be a lot easier for newcomers to learn than
> try…for…else…except…else e.g.:
>
>
>
> try:
>
> for i in range(N):
>
>if i > 3:
>
> break;
>
>elif i % 2 == 0:
>
> raise ValueError("Odds Only");
>
> else: # to if
>
> print(i)
>
> else:  # Else to loop
>
> print("Loop Completed")
>
> except ValueError as err:
>
> print(err)
>
> else:  # to try
>
> print("No Exception")
>
> finally:
>
> print("Try Ended")
>
>
>
> Where the multitude of elses makes my eyes cross.
>
>
>
> Steve Barnes
> ___
> Python-ideas mailing list -- python-ideas@python.org
> To unsubscribe send an email to python-ideas-le...@python.org
> https://mail.python.org/mailman3/lists/python-ideas.python.org/
> Message archived at
> https://mail.python.org/archives/list/python-ideas@python.org/message/MKAAWV6OT7SRIHTDOAEA3OHV6ZLSGLE2/
> Code of Conduct: http://python.org/psf/codeofconduct/
>

-- 


Notice: 
This email is confidential and may contain copyright material of 
members of the Ocado Group. Opinions and views expressed in this message 
may not necessarily reflect the opinions and views of the members of the 
Ocado Group.

If you are not the intended recipient, please notify us 
immediately and delete all copies of this message. Please note that it is 
your responsibility to scan this message for viruses.

References to the 
"Ocado Group" are to Ocado Group plc (registered in England and Wales with 
number 7098618) and its subsidiary undertakings (as that expression is 
defined in the Companies Act 2006) from time to time. The registered office 
of Ocado Group plc is Buildings One & Two, Trident Place, Mosquito Way, 
Hatfield, Hertfordshire, AL10 9UL.
___
Python-ideas mailing list -- python-ideas@python.org
To unsubscribe send an email to python-ideas-le...@python.org
https://mail.python.org/mailman3/lists/python-ideas.python.org/
Message archived at 
https://mail.python.org/archives/list/python-ideas@python.org/message/3ZPJDOTFCCQALCHIVEIPFJBROG6JSHIY/
Code of Conduct: http://python.org/psf/codeofconduct/


[Python-ideas] Re: New clause in FOR and WHILE instead of ELSE

2020-07-14 Thread Mathew Elman
On Tue, 14 Jul 2020 at 12:38, Dominik Vilsmeier 
wrote:

> On 14.07.20 09:54, Mathew Elman wrote:
>
> What about adding `except` to the compound loop statement?
> That way in cases where there needs to be clarity you can raise a specific
> exception rather than just `break`.
> Keeping the logic of why you "break" the loop inside the loop and would
> also allow multiple reasons for breaking from a for loop to remain clear.
>
> e.g.
>
>
>> for i  in range(N):
>> if i > 3:
>> raise ValueError
>> except ValueError:
>> print(i) # >> 4
>> else:
>> print("Loop not entered")
>>
>
>
> That can be done already today by putting the `for` loop in the `try`
> body.
>
 It can, but my thought was that this would be sugar that made it easier to
follow the logic

> Also here `else` should rather mean `did not raise` as for the normal
> `try/except/else` usage (and similar to how `for/else` means `did not
> break`).
>
Yes sorry, I made an error. I confused myself about what else does, how
ironic. This would be most useful for cases where break and not breaking
were unclear.


> The more interesting part is to detect whether the loop did some work at
> all (i.e. whether the iterable was empty).
>
 This could be done by raising a "silent" exception that is handled by
default (something like StopIteration), when trying to iterate an empty
iterable. If the "NoIteration" exception is not caught explicitly it is
ignored.
Then you could have :

> for i in range(N):
>  if i > 3:
> raise ValueError
> except ValueError:
> print(f"{i} is more than 3")
> except NoIteration:
> print("Loop not entered")
> else:
> print(f"{i} is less than 4")
>

This may not be to everyone's taste, but to me it's better than the current
state of things and clearer than having special if statements after a loop.

> But also this can be done with some small overhead:
>
> loop = Loop(iterable)
> for x in loop:
> pass
> if loop.empty:
> pass
>
> The `Loop` class here wraps the sentinel logic required to detect if the
> iterable was empty.
>
___
> Python-ideas mailing list -- python-ideas@python.org
> To unsubscribe send an email to python-ideas-le...@python.org
> https://mail.python.org/mailman3/lists/python-ideas.python.org/
> Message archived at
> https://mail.python.org/archives/list/python-ideas@python.org/message/ICALEMWZK4RCAKVENV2VRJ7POEQXKSN6/
> Code of Conduct: http://python.org/psf/codeofconduct/
>

-- 


Notice: 
This email is confidential and may contain copyright material of 
members of the Ocado Group. Opinions and views expressed in this message 
may not necessarily reflect the opinions and views of the members of the 
Ocado Group.

If you are not the intended recipient, please notify us 
immediately and delete all copies of this message. Please note that it is 
your responsibility to scan this message for viruses.

References to the 
"Ocado Group" are to Ocado Group plc (registered in England and Wales with 
number 7098618) and its subsidiary undertakings (as that expression is 
defined in the Companies Act 2006) from time to time. The registered office 
of Ocado Group plc is Buildings One & Two, Trident Place, Mosquito Way, 
Hatfield, Hertfordshire, AL10 9UL.
___
Python-ideas mailing list -- python-ideas@python.org
To unsubscribe send an email to python-ideas-le...@python.org
https://mail.python.org/mailman3/lists/python-ideas.python.org/
Message archived at 
https://mail.python.org/archives/list/python-ideas@python.org/message/ZG2Z34A45M5BKTI7AA6A223HQMSBWS4E/
Code of Conduct: http://python.org/psf/codeofconduct/


[Python-ideas] Re: New clause in FOR and WHILE instead of ELSE

2020-07-14 Thread Mathew Elman
What about adding `except` to the compound loop statement?
That way in cases where there needs to be clarity you can raise a specific
exception rather than just `break`.
Keeping the logic of why you "break" the loop inside the loop and would
also allow multiple reasons for breaking from a for loop to remain clear.

e.g.


> for i  in range(N):
> if i > 3:
> raise ValueError
> except ValueError:
> print(i) # >> 4
> else:
> print("Loop not entered")
>


On Tue, 14 Jul 2020 at 05:33, Ethan Furman  wrote:

> On 07/11/2020 09:16 PM, Rob Cliffe via Python-ideas wrote:
>
> > My gut feeling (backed by no evidence) is that dealing with the case of
> zero iterations is not needed frequently enough to cater for it.
>
> My personal experience is that the case of no iterations is frequent
> enough, and a big enough pain to deal with, that if we're making changes we
> should include a way to deal with it.  Currently:
>
>  if empty_iterable:
>  # do whatever
>  else:
>  for it in iterable:
>  # do something
>
> or maybe:
>
>  obj = object
>  for obj in some_iterator:
>  do_stuff()
>  if obj is object:
>  # iterator was empty
>  do_different_stuff()
>
> Either way,
>
>  for obj in iterator:
>  do_stuff
>  elif empty:
>  do_other_stuff()
>
> would be much nicer.
>
> --
> ~Ethan~
> ___
> Python-ideas mailing list -- python-ideas@python.org
> To unsubscribe send an email to python-ideas-le...@python.org
> https://mail.python.org/mailman3/lists/python-ideas.python.org/
> Message archived at
> https://mail.python.org/archives/list/python-ideas@python.org/message/W4C6TNXU7XRUA4XKY2YEQKOENFVTUT25/
> Code of Conduct: http://python.org/psf/codeofconduct/
>

-- 


Notice: 
This email is confidential and may contain copyright material of 
members of the Ocado Group. Opinions and views expressed in this message 
may not necessarily reflect the opinions and views of the members of the 
Ocado Group.

If you are not the intended recipient, please notify us 
immediately and delete all copies of this message. Please note that it is 
your responsibility to scan this message for viruses.

References to the 
"Ocado Group" are to Ocado Group plc (registered in England and Wales with 
number 7098618) and its subsidiary undertakings (as that expression is 
defined in the Companies Act 2006) from time to time. The registered office 
of Ocado Group plc is Buildings One & Two, Trident Place, Mosquito Way, 
Hatfield, Hertfordshire, AL10 9UL.
___
Python-ideas mailing list -- python-ideas@python.org
To unsubscribe send an email to python-ideas-le...@python.org
https://mail.python.org/mailman3/lists/python-ideas.python.org/
Message archived at 
https://mail.python.org/archives/list/python-ideas@python.org/message/YJ5AQMAWVUUFLBEW5KO7R7LBC7NI6FHD/
Code of Conduct: http://python.org/psf/codeofconduct/


[Python-ideas] Re: approximate equality operator ("PEP 485 follow-up")

2020-06-23 Thread Mathew Elman
Well there you go, good point.
I didn't really like it being an operator myself. But I can see having a
math.tolerance class being useful.

On Tue, 23 Jun 2020 at 13:53, Jonathan Goble  wrote:

> On Tue, Jun 23, 2020 at 8:44 AM Mathew Elman 
> wrote:
>
>> Perhaps a more versatile operator would be to introduce a +- operator
>> that would return an object with an __eq__ method that checks for equality
>> in the tolerance i.e
>>
>> a == b +- 0.5
>>
>
> This is already valid syntax, because unary minus is a thing. So this is
> currently parsed as "a == b + (-0.5)".
>
> Reversing it to use -+ won't work because unary plus is also a thing.
>

-- 


Notice: 
This email is confidential and may contain copyright material of 
members of the Ocado Group. Opinions and views expressed in this message 
may not necessarily reflect the opinions and views of the members of the 
Ocado Group.

If you are not the intended recipient, please notify us 
immediately and delete all copies of this message. Please note that it is 
your responsibility to scan this message for viruses.

References to the 
"Ocado Group" are to Ocado Group plc (registered in England and Wales with 
number 7098618) and its subsidiary undertakings (as that expression is 
defined in the Companies Act 2006) from time to time. The registered office 
of Ocado Group plc is Buildings One & Two, Trident Place, Mosquito Way, 
Hatfield, Hertfordshire, AL10 9UL.
___
Python-ideas mailing list -- python-ideas@python.org
To unsubscribe send an email to python-ideas-le...@python.org
https://mail.python.org/mailman3/lists/python-ideas.python.org/
Message archived at 
https://mail.python.org/archives/list/python-ideas@python.org/message/YCQO6WZORWTGCFHY3GQA5C2KVKKGMDT3/
Code of Conduct: http://python.org/psf/codeofconduct/


[Python-ideas] Re: approximate equality operator ("PEP 485 follow-up")

2020-06-23 Thread Mathew Elman
Perhaps a more versatile operator would be to introduce a +- operator that
would return an object with an __eq__ method that checks for equality in
the tolerance i.e

a == b +- 0.5

Although I don't like this either since you could achieve the same thing
with something like this:

class Tolerance:
def __init__(self, upper, lower=None):
self.upper = upper
self.lower = upper if lower is None else lower

def __add__(self, number):
return Tolerance(number+self.upper, number-self.lower)

def __sub__(self, number):
return Tolerance(number-self.upper, number+self.lower)

def __eq__(self, number):
   return self.lower < number < self.upper

a == b + Tolerance(0.5)

So maybe it would be nice to have something like this built into math?



On Thu, 18 Jun 2020 at 17:56, Steven D'Aprano  wrote:

> On Sun, Jun 14, 2020 at 02:39:49PM +0200, Sebastian M. Ernst wrote:
> > Hi all,
> >
> > after just having typed tons of `math.isclose` (see PEP 485 [1]) and
> > `numpy.isclose` calls (while basically using their default tolerances
> > most of the time), I was wondering whether it makes sense to add a
> > matching operator.
>
> I wrote the statistics module in the stdlib, and the tests for that use
> a lot of approximate equality tests:
>
> https://github.com/python/cpython/blob/3.8/Lib/test/test_statistics.py
>
> which includes an approx_equal function that pre-dates the math.isclose
> and a unittest assertApproxEqual method. So I like to think I'm a heavy
> user of approximate comparisons.
>
> I wouldn't use an approximate operator. Not even if it were written with
> the unicode ≈ ALMOST EQUAL TO symbol :-)
>
> The problem is that the operator can only have a single pre-defined
> tolerance (or a pair of tolerances, absolute and relative), which
> would not be very useful in practice. So I would have to swap from the
> operator to a function call, and it is highly unlikely that the operator
> tolerances would be what I need the majority of the time.
>
>
> --
> Steven
> ___
> Python-ideas mailing list -- python-ideas@python.org
> To unsubscribe send an email to python-ideas-le...@python.org
> https://mail.python.org/mailman3/lists/python-ideas.python.org/
> Message archived at
> https://mail.python.org/archives/list/python-ideas@python.org/message/6AWLMPZCLZCUG6BUBV6JF5XHUQYQAYC5/
> Code of Conduct: http://python.org/psf/codeofconduct/
>

-- 


Notice: 
This email is confidential and may contain copyright material of 
members of the Ocado Group. Opinions and views expressed in this message 
may not necessarily reflect the opinions and views of the members of the 
Ocado Group.

If you are not the intended recipient, please notify us 
immediately and delete all copies of this message. Please note that it is 
your responsibility to scan this message for viruses.

References to the 
"Ocado Group" are to Ocado Group plc (registered in England and Wales with 
number 7098618) and its subsidiary undertakings (as that expression is 
defined in the Companies Act 2006) from time to time. The registered office 
of Ocado Group plc is Buildings One & Two, Trident Place, Mosquito Way, 
Hatfield, Hertfordshire, AL10 9UL.
___
Python-ideas mailing list -- python-ideas@python.org
To unsubscribe send an email to python-ideas-le...@python.org
https://mail.python.org/mailman3/lists/python-ideas.python.org/
Message archived at 
https://mail.python.org/archives/list/python-ideas@python.org/message/KTBKOWCSPUUX63PMRO57Z2T6KLPMJGO5/
Code of Conduct: http://python.org/psf/codeofconduct/