Re: [Python-ideas] [Python-Dev] What's the status of PEP 505: None-aware operators?

2017-11-29 Thread Nick Coghlan
On 29 November 2017 at 16:13, David Mertz  wrote:
> Strong -1 still from me. Too special case for syntax. Just write a function
> 'first_non_none()' that can perfectly will handle the need.

That's the equivalent of SQL's COALESCE, and it's insufficient for the
same reason "and" and "or" are syntax rather than builtins: the
function form doesn't provide short-circuiting behaviour.

As far as utility goes, I put it in a similar category to matrix
multiplication: if you don't need it, you don't need it, but when you
do need it, you need it a *lot*.

The use case where these operations come up is when you're working
with partially structured hierarchical data (*cough*JSON*cough*). In
those kinds of structures, None is frequently used as a marker to say
"this entire subtree is missing", and you either want to propagate
that None, or else replace it with something else (and the "something
else" may be a network call to a different service, so you definitely
don't want to do it if you don't need to).

So I'd remind folks to try to avoid the "I don't need this, so nobody
needs this" mistake. It's OK to say "the use case exists, but I still
don't want that particular syntax for it in Python" (I'm personally
inclined to agree with you on that front). It's not OK to try to claim
there are no use cases where the status quo is awkward enough to
become irritating (since it's an empirically false statement that you
don't need to be making).

Cheers,
Nick.

-- 
Nick Coghlan   |   ncogh...@gmail.com   |   Brisbane, Australia
___
Python-ideas mailing list
Python-ideas@python.org
https://mail.python.org/mailman/listinfo/python-ideas
Code of Conduct: http://python.org/psf/codeofconduct/


Re: [Python-ideas] [Python-Dev] What's the status of PEP 505: None-aware operators?

2017-11-29 Thread Kirill Balunov
2017-11-29 11:14 GMT+03:00 Nick Coghlan :


> It's OK to say "the use case exists, but I still
> don't want that particular syntax for it in Python" (I'm personally
> inclined to agree with you on that front). It's not OK to try to claim
> there are no use cases where the status quo is awkward enough to
> become irritating (since it's an empirically false statement that you
> don't need to be making).
>

If the problem with the proposed syntax, but there are cases for use, it
may be worth to bikeshed one more time?

2017-11-29 9:08 GMT+03:00 Steven D'Aprano :

I'd much prefer to read, write and teach the version with ?? over the
> status quo.


Since the proposed semantics is more similar to the idea of "or", may be it
is better to consider something like:

timeout then local_timeout then global_timeout

I do not know how much this is a frequent case to be worthy of a keyword.

With kind regards, -gdg

2017-11-29 11:14 GMT+03:00 Nick Coghlan :

> On 29 November 2017 at 16:13, David Mertz  wrote:
> > Strong -1 still from me. Too special case for syntax. Just write a
> function
> > 'first_non_none()' that can perfectly will handle the need.
>
> That's the equivalent of SQL's COALESCE, and it's insufficient for the
> same reason "and" and "or" are syntax rather than builtins: the
> function form doesn't provide short-circuiting behaviour.
>
> As far as utility goes, I put it in a similar category to matrix
> multiplication: if you don't need it, you don't need it, but when you
> do need it, you need it a *lot*.
>
> The use case where these operations come up is when you're working
> with partially structured hierarchical data (*cough*JSON*cough*). In
> those kinds of structures, None is frequently used as a marker to say
> "this entire subtree is missing", and you either want to propagate
> that None, or else replace it with something else (and the "something
> else" may be a network call to a different service, so you definitely
> don't want to do it if you don't need to).
>
> So I'd remind folks to try to avoid the "I don't need this, so nobody
> needs this" mistake. It's OK to say "the use case exists, but I still
> don't want that particular syntax for it in Python" (I'm personally
> inclined to agree with you on that front). It's not OK to try to claim
> there are no use cases where the status quo is awkward enough to
> become irritating (since it's an empirically false statement that you
> don't need to be making).
>
> Cheers,
> Nick.
>
> --
> Nick Coghlan   |   ncogh...@gmail.com   |   Brisbane, Australia
> ___
> Python-ideas mailing list
> Python-ideas@python.org
> https://mail.python.org/mailman/listinfo/python-ideas
> Code of Conduct: http://python.org/psf/codeofconduct/
>
___
Python-ideas mailing list
Python-ideas@python.org
https://mail.python.org/mailman/listinfo/python-ideas
Code of Conduct: http://python.org/psf/codeofconduct/


[Python-ideas] Add a dict with the attribute access capability

2017-11-29 Thread Serhiy Storchaka
In 3.7 I have removed an old-deprecated plistlib.Dict. [1] Actually it 
already was deprecated when the plistlib module was added to the regular 
stdlib in Python 2.6.


This is a dict subclass which allows to access items as attributes.

d = plistlib.Dict()
d['a'] = 1
assert d.a == 1
d.b = 2
assert d['b'] == 2

Raymond noticed that that capability seemed nice to have.

What do you think about reviving this type as general purpose type in 
collections or types? Perhaps it can be convenient for working with 
JSON, plists, configuration files, databases and in other cases that 
need a dict with string keys.


If reintroduce it, there are open questions.

1. The name of the type.

2. The location of the type. collections or types? Or other variants?

3. How it will collaborate with OrderedDict, defaultdict, etc?

4. Should it be a dict subclass, or a mixin, or a proxy? Or add several 
types?



[1] https://bugs.python.org/issue29196

___
Python-ideas mailing list
Python-ideas@python.org
https://mail.python.org/mailman/listinfo/python-ideas
Code of Conduct: http://python.org/psf/codeofconduct/


Re: [Python-ideas] [Python-Dev] What's the status of PEP 505: None-aware operators?

2017-11-29 Thread Nick Coghlan
On 29 November 2017 at 18:49, Kirill Balunov  wrote:
> 2017-11-29 11:14 GMT+03:00 Nick Coghlan :
>>
>> It's OK to say "the use case exists, but I still
>> don't want that particular syntax for it in Python" (I'm personally
>> inclined to agree with you on that front). It's not OK to try to claim
>> there are no use cases where the status quo is awkward enough to
>> become irritating (since it's an empirically false statement that you
>> don't need to be making).
>
> If the problem with the proposed syntax, but there are cases for use, it may
> be worth to bikeshed one more time?

I don't think enough time has passed since we first discussed it.
Since Guido has already said "not for 3.7", we can give folks another
12+ months to ponder the problem, and then maybe revisit it for 3.8.

Cheers,
Nick.

-- 
Nick Coghlan   |   ncogh...@gmail.com   |   Brisbane, Australia
___
Python-ideas mailing list
Python-ideas@python.org
https://mail.python.org/mailman/listinfo/python-ideas
Code of Conduct: http://python.org/psf/codeofconduct/


Re: [Python-ideas] [Python-Dev] What's the status of PEP 505: None-aware operators?

2017-11-29 Thread Steven D'Aprano
On Wed, Nov 29, 2017 at 09:14:12AM +0200, Serhiy Storchaka wrote:
> 29.11.17 08:08, Steven D'Aprano пише:
> >Perl is hardly the only language with null-coalescing operators -- we
> >might better describe ?? as being familiar to C#, PHP, Swift and Dart.
> >That's two mature, well-known languages and two up-and-coming languages.
> 
> What is the syntax of the ternary operator in these languages?

All four use:

condition ? first : second

for the ternary if operator.


-- 
Steve
___
Python-ideas mailing list
Python-ideas@python.org
https://mail.python.org/mailman/listinfo/python-ideas
Code of Conduct: http://python.org/psf/codeofconduct/


Re: [Python-ideas] [Python-Dev] What's the status of PEP 505: None-aware operators?

2017-11-29 Thread Elazar
בתאריך יום ד׳, 29 בנוב׳ 2017, 11:46, מאת Steven D'Aprano ‏<
st...@pearwood.info>:

> On Wed, Nov 29, 2017 at 09:14:12AM +0200, Serhiy Storchaka wrote:
> > 29.11.17 08:08, Steven D'Aprano пише:
> > >Perl is hardly the only language with null-coalescing operators -- we
> > >might better describe ?? as being familiar to C#, PHP, Swift and Dart.
> > >That's two mature, well-known languages and two up-and-coming languages.
> >
> > What is the syntax of the ternary operator in these languages?
>
> All four use:
>
> condition ? first : second
>
> for the ternary if operator.
>

This suggests something like "ifNone" keyword :

x = a ifNone b ifNone c

Elazar
___
Python-ideas mailing list
Python-ideas@python.org
https://mail.python.org/mailman/listinfo/python-ideas
Code of Conduct: http://python.org/psf/codeofconduct/


Re: [Python-ideas] [Python-Dev] What's the status of PEP 505: None-aware operators?

2017-11-29 Thread Lele Gaifax
Kirill Balunov  writes:

> Since the proposed semantics is more similar to the idea of "or", may be it
> is better to consider something like:
>
> timeout then local_timeout then global_timeout
>
> I do not know how much this is a frequent case to be worthy of a keyword.

That sounds awkward... what about

  timeout else local_timeout else global_timeout

instead?

ciao, lele.
-- 
nickname: Lele Gaifax | Quando vivrò di quello che ho pensato ieri
real: Emanuele Gaifas | comincerò ad aver paura di chi mi copia.
l...@metapensiero.it  | -- Fortunato Depero, 1929.

___
Python-ideas mailing list
Python-ideas@python.org
https://mail.python.org/mailman/listinfo/python-ideas
Code of Conduct: http://python.org/psf/codeofconduct/


Re: [Python-ideas] [Python-Dev] What's the status of PEP 505: None-aware operators?

2017-11-29 Thread Elazar
בתאריך יום ד׳, 29 בנוב׳ 2017, 12:29, מאת Lele Gaifax ‏:

> Kirill Balunov  writes:
>
> > Since the proposed semantics is more similar to the idea of "or", may be
> it
> > is better to consider something like:
> >
> > timeout then local_timeout then global_timeout
> >
> > I do not know how much this is a frequent case to be worthy of a keyword.
>
> That sounds awkward... what about
>
>   timeout else local_timeout else global_timeout
>
> instead?
>

I think then and else can be ruled out since they can be very confusing
when used in a conditinal statement or a comprehension.

x = a if x else y else b  # wait. what?

Elazar
___
Python-ideas mailing list
Python-ideas@python.org
https://mail.python.org/mailman/listinfo/python-ideas
Code of Conduct: http://python.org/psf/codeofconduct/


Re: [Python-ideas] Proposal: allow length_hint to specify infinite iterators

2017-11-29 Thread Antoine Pitrou
On Wed, 29 Nov 2017 09:39:57 +0200
Serhiy Storchaka 
wrote:
> 29.11.17 03:34, Steven D'Aprano пише:
> > This wastes the opportunity to fail fast on operations which cannot
> > possibly succeed, e.g. list(count()) must eventually fail with
> > MemoryError. Or worse: if the OS starts thrashing trying to meet the
> > memory requests, you can lock up the computer.
> > 
> > I propose that we:
> > 
> > (1) extend the __length_hint__ protocol to allow iterators to report
> > that they are infinite;
> > 
> > (2) and recommend that consumers of iterators (such as list) that
> > require finite input should fail fast in the event of an infinite
> > iterator.  
> 
> Infinite iterators are rare. And count() is even more special in the 
> sense that iterating it doesn't have side effects and is not interruptible.

Not to mention that many infinite iterators cannot be predicted in
advance to be infinite.  Only the more trivial cases such as count()
would apply (but not a takewhile() involving count(), for example).

Regards

Antoine.


___
Python-ideas mailing list
Python-ideas@python.org
https://mail.python.org/mailman/listinfo/python-ideas
Code of Conduct: http://python.org/psf/codeofconduct/


Re: [Python-ideas] How assignment should work with generators?

2017-11-29 Thread Alon Snir
On Wed, Nov 29, 2017 at 5:46 AM, Alon Snir  wrote:
> I would like to mention that the issue of assignment to a target list, is 
> also relevant to the case of elementwise assignment to a mutable sequence 
> (e.g. lists and arrays). Here as well, the rhs of the assignment statement 
> states the number of elements to be assigned. Consequently, the following 
> example will get into infinite loop:
>
 from itertools import count
 A = []
 A[:] = count()
>
> Writing "A[:2] = count()" will cause the same result.
> Here as well, it is currently safer to use islice if the rhs is a generator 
> or an iterator. e.g.:
>
 it = count()
 A[:] = islice(it,2)
>
> In my opinion, it is be better to devise a solution that could be applied in 
> both cases. Maybe a new kind of assignment operator that will be dedicated to 
> this kind of assignment. i.e. elementwise assignment with restriction on the 
> number of elements to be assigned, based on the length of the lhs object (or 
> the number of targets in the target list).
>

ChrisA wrote:
Hmm. The trouble is that slice assignment doesn't have a fixed number of 
targets. If you say "x, y = spam", there's a clear indication that 'spam' needs 
to provide exactly two values; but "A[:] = spam" could have any number of 
values, and it'll expand or shrink the list accordingly.

Rhodri James wrote:
Flatly, no.  It is better not to ask for things you don't want in the first 
place, in this case the infinite sequence.
Still, don't let me discourage you from working on this.  If you can define how 
such an assignment would work, or even the length of A[:] as an assignment 
target, I'm not going to dismiss it out of hand.


My answer:

The idea is to define an alternative assignment rule, that is to assign exactly 
as many elements as the current length of the lhs object (without expanding or 
shrinking it). Suppose "?=" is the operator for the alternative assignment 
rule; A=[None]*2; and "iterator" is any iterator (finite or infinite). In this 
case, the following code:

>>> A ?= iterator

would behave like this:

>>> A[:] = islice(iterator, 2)  # where 2 is the length of A

And as suggested earlier for the case of assignment to a target list, the 
following code:

>>> x, y ?= iterator

would behave like this:

>>> x, y = islice(iterator, 2)  # where 2 is the number of targets

Regarding the length issue:
Is there any difficulty in finding the length of a sliced sequence? After all, 
the range object has a len method. Therefore, the length of A[s] (where s is a 
slice object) could be evaluated as follows:

>>> len(range(*s.indices(len(A 
___
Python-ideas mailing list
Python-ideas@python.org
https://mail.python.org/mailman/listinfo/python-ideas
Code of Conduct: http://python.org/psf/codeofconduct/


Re: [Python-ideas] [Python-Dev] What's the status of PEP 505: None-aware operators?

2017-11-29 Thread Serhiy Storchaka

29.11.17 11:45, Steven D'Aprano пише:

On Wed, Nov 29, 2017 at 09:14:12AM +0200, Serhiy Storchaka wrote:

29.11.17 08:08, Steven D'Aprano пише:

Perl is hardly the only language with null-coalescing operators -- we
might better describe ?? as being familiar to C#, PHP, Swift and Dart.
That's two mature, well-known languages and two up-and-coming languages.


What is the syntax of the ternary operator in these languages?


All four use:

 condition ? first : second

for the ternary if operator.


If all four use ?, it is natural that in operators which are shortcuts 
of the ternary operator they use ?. But in Python the bar of introducing 
? is higher.


___
Python-ideas mailing list
Python-ideas@python.org
https://mail.python.org/mailman/listinfo/python-ideas
Code of Conduct: http://python.org/psf/codeofconduct/


Re: [Python-ideas] How assignment should work with generators?

2017-11-29 Thread Rhodri James

On 28/11/17 23:15, Alon Snir wrote:

On Wed, Nov 29, 2017 at 5:46 AM, Alon Snir  wrote:

I would like to mention that the issue of assignment to a target list, is also 
relevant to the case of elementwise assignment to a mutable sequence (e.g. 
lists and arrays). Here as well, the rhs of the assignment statement states the 
number of elements to be assigned. Consequently, the following example will get 
into infinite loop:


from itertools import count
A = []
A[:] = count()


Writing "A[:2] = count()" will cause the same result.
Here as well, it is currently safer to use islice if the rhs is a generator or 
an iterator. e.g.:


it = count()
A[:] = islice(it,2)


In my opinion, it is be better to devise a solution that could be applied in 
both cases. Maybe a new kind of assignment operator that will be dedicated to 
this kind of assignment. i.e. elementwise assignment with restriction on the 
number of elements to be assigned, based on the length of the lhs object (or 
the number of targets in the target list).



ChrisA wrote:
Hmm. The trouble is that slice assignment doesn't have a fixed number of targets. If you say 
"x, y = spam", there's a clear indication that 'spam' needs to provide exactly two 
values; but "A[:] = spam" could have any number of values, and it'll expand or shrink the 
list accordingly.

Rhodri James wrote:
Flatly, no.  It is better not to ask for things you don't want in the first 
place, in this case the infinite sequence.
Still, don't let me discourage you from working on this.  If you can define how 
such an assignment would work, or even the length of A[:] as an assignment 
target, I'm not going to dismiss it out of hand.


My answer:

The idea is to define an alternative assignment rule, that is to assign exactly as many elements as 
the current length of the lhs object (without expanding or shrinking it). Suppose "?=" is 
the operator for the alternative assignment rule; A=[None]*2; and "iterator" is any 
iterator (finite or infinite). In this case, the following code:


A ?= iterator


would behave like this:


A[:] = islice(iterator, 2)  # where 2 is the length of A


And as suggested earlier for the case of assignment to a target list, the 
following code:


x, y ?= iterator


would behave like this:


x, y = islice(iterator, 2)  # where 2 is the number of targets


You're still getting -1000 from me on this.  You want to introduce magic 
syntax to make writing sloppy code easier.  That's two big barriers you 
aren't getting over.



--
Rhodri James *-* Kynesim Ltd
___
Python-ideas mailing list
Python-ideas@python.org
https://mail.python.org/mailman/listinfo/python-ideas
Code of Conduct: http://python.org/psf/codeofconduct/


Re: [Python-ideas] [Python-Dev] What's the status of PEP 505: None-aware operators?

2017-11-29 Thread Stephan Houben
What about more English-like syntax:

X or else Y

E.g.

cache.get(foo) or else expensive_call(foo)

Stephan


Op 29 nov. 2017 12:54 schreef "Serhiy Storchaka" :

29.11.17 11:45, Steven D'Aprano пише:

On Wed, Nov 29, 2017 at 09:14:12AM +0200, Serhiy Storchaka wrote:
>
>> 29.11.17 08:08, Steven D'Aprano пише:
>>
>>> Perl is hardly the only language with null-coalescing operators -- we
>>> might better describe ?? as being familiar to C#, PHP, Swift and Dart.
>>> That's two mature, well-known languages and two up-and-coming languages.
>>>
>>
>> What is the syntax of the ternary operator in these languages?
>>
>
> All four use:
>
>  condition ? first : second
>
> for the ternary if operator.
>

If all four use ?, it is natural that in operators which are shortcuts of
the ternary operator they use ?. But in Python the bar of introducing ? is
higher.


___
Python-ideas mailing list
Python-ideas@python.org
https://mail.python.org/mailman/listinfo/python-ideas
Code of Conduct: http://python.org/psf/codeofconduct/
___
Python-ideas mailing list
Python-ideas@python.org
https://mail.python.org/mailman/listinfo/python-ideas
Code of Conduct: http://python.org/psf/codeofconduct/


Re: [Python-ideas] [Python-Dev] What's the status of PEP 505: None-aware operators?

2017-11-29 Thread Nick Coghlan
On 29 November 2017 at 21:53, Serhiy Storchaka  wrote:
> 29.11.17 11:45, Steven D'Aprano пише:
>> On Wed, Nov 29, 2017 at 09:14:12AM +0200, Serhiy Storchaka wrote:
>>> What is the syntax of the ternary operator in these languages?
>>
>> All four use:
>>
>>  condition ? first : second
>>
>> for the ternary if operator.
>
> If all four use ?, it is natural that in operators which are shortcuts of
> the ternary operator they use ?. But in Python the bar of introducing ? is
> higher.

It's also noteworthy that they all offer "&&" and "||" as short
circuiting "and" and "or" operators. When you have that pattern
established, then "??" fits right in.

With Python's only spelling for the logical operators being "and" and
"or", the cryptic unpronounceable nature of "??" becomes much harder
to ignore.

   "a and b" -> pronounced "a and b"
   "a or b" -> pronounced "a or b"
   "a ?? b" -> pronounced "a  b"

The only potentially pronounceable versions I've been able to come up
with are a fair bit longer:

"a if def else b" -> pronounced "a if defined, else b"
"a if ?? is not None else b" -> pronounced "a if the leftmost
operand is not None, else b"
"a if ?? is None else ??.b" -> pronounced "a if the leftmost
operand is None, else the leftmost operand dot b"

(The last two examples there are a version where "??" appearing in
either the condition expression or the RHS of a conditional expression
would cause the leftmost operand to be eagerly evaluated, placed in a
hidden temporary variable and then referenced multiple times as a
subexpression. A similar construct could then also be used in filter
expressions in comprehensions to refer back to the loop's result
clause: "[f(x) for x in iterable if ?? is not None]". It's still
magical and hard to look up syntax, but "??" as a magic placeholder to
say "Reference the leftmost operand in the current expression here,
but still only evaluate it once" seems nicer to me than using it as a
cryptic binary operator)

Cheers,
Nick.

-- 
Nick Coghlan   |   ncogh...@gmail.com   |   Brisbane, Australia
___
Python-ideas mailing list
Python-ideas@python.org
https://mail.python.org/mailman/listinfo/python-ideas
Code of Conduct: http://python.org/psf/codeofconduct/


Re: [Python-ideas] [Python-Dev] What's the status of PEP 505: None-aware operators?

2017-11-29 Thread Nick Coghlan
On 29 November 2017 at 22:38, Stephan Houben  wrote:
> What about more English-like syntax:
>
> X or else Y

The problem with constructs like this is that they look like they
should mean the same thing as "X or Y".

Cheers,
Nick.

-- 
Nick Coghlan   |   ncogh...@gmail.com   |   Brisbane, Australia
___
Python-ideas mailing list
Python-ideas@python.org
https://mail.python.org/mailman/listinfo/python-ideas
Code of Conduct: http://python.org/psf/codeofconduct/


Re: [Python-ideas] [Python-Dev] What's the status of PEP 505: None-aware operators?

2017-11-29 Thread Stephan Houben
What about a more general:

A if  B else C

which would allow

A if is not None else C

but also e.g.

A if >= 1 else 0

Stephan

Op 29 nov. 2017 13:41 schreef "Nick Coghlan" :

> On 29 November 2017 at 22:38, Stephan Houben  wrote:
> > What about more English-like syntax:
> >
> > X or else Y
>
> The problem with constructs like this is that they look like they
> should mean the same thing as "X or Y".
>
> Cheers,
> Nick.
>
> --
> Nick Coghlan   |   ncogh...@gmail.com   |   Brisbane, Australia
>
___
Python-ideas mailing list
Python-ideas@python.org
https://mail.python.org/mailman/listinfo/python-ideas
Code of Conduct: http://python.org/psf/codeofconduct/


Re: [Python-ideas] [Python-Dev] What's the status of PEP 505: None-aware operators?

2017-11-29 Thread Serhiy Storchaka

29.11.17 14:39, Nick Coghlan пише:

 "a if def else b" -> pronounced "a if defined, else b"


I understand "a if defined, else b" as

try:
result = a
except (NameError, AttributeError, LookupError):
result = b

The problem is that None is not undefined. This is a regular value. 
Seems it is not so special in Python as NULL or undef in other 
languages. Python even don't have a special purposed 
NullPointerException (or NoneError).


___
Python-ideas mailing list
Python-ideas@python.org
https://mail.python.org/mailman/listinfo/python-ideas
Code of Conduct: http://python.org/psf/codeofconduct/


Re: [Python-ideas] [Python-Dev] What's the status of PEP 505: None-aware operators?

2017-11-29 Thread Paul Moore
On 29 November 2017 at 12:41, Nick Coghlan  wrote:
> On 29 November 2017 at 22:38, Stephan Houben  wrote:
>> What about more English-like syntax:
>>
>> X or else Y
>
> The problem with constructs like this is that they look like they
> should mean the same thing as "X or Y".

Keyword based and multi-word approaches also break down much faster
when you get more terms.

X or else Y

looks OK (ignoring Nick's comment - I could pick another keyword-based
proposal, but I'm too lazy to look for one I like), but when you have
4 options,

X or else Y or else Z or else W

the benefit isn't as obvious. Use lower-case and longer names

item_one or else item_two or else list_one[the_index] or dict_one['key_one']

and it becomes just a muddle of words.

Conversely, punctuation-based examples look worse with shorter
variables and with expressions rather than identifiers:

item_one ?? item_two ?? another_item ?? one_more_possibility

vs

x ?? y[2] ?? kw['id'] ?? 3 + 7

IMO, this is a case where artificial examples are unusually bad at
conveying the actual feel of a proposal. It's pretty easy to turn
someone's acceptable-looking example into an incomprehensible mess,
just by changing variable names and example terms. So I think it's
critically important for any proposal along these lines (even just
posts to the mailing list, and definitely for a PEP), that it's argued
in terms of actual code examples in current projects that would
reasonably be modified to use the proposed syntax. And people wanting
to be particularly honest in their proposals should probably include
both best-case and worst-case examples of readability.

Paul

PS Also, I want a pony. (I really do understand that the above is not
realistic, but maybe I can hope that at least anyone writing a PEP
take it into consideration :-))
___
Python-ideas mailing list
Python-ideas@python.org
https://mail.python.org/mailman/listinfo/python-ideas
Code of Conduct: http://python.org/psf/codeofconduct/


Re: [Python-ideas] [Python-Dev] What's the status of PEP 505: None-aware operators?

2017-11-29 Thread Serhiy Storchaka

29.11.17 15:01, Stephan Houben пише:

What about a more general:

A if  B else C

which would allow

A if is not None else C

but also e.g.

A if >= 1 else 0


This look the most "natural" to me. I.e. the least "unnatural". If we 
even will introduce a new special syntax I will prefer this syntax.


The only disadvantage is that this will prevent introducing "angular 
parenthesis" in future: A if  == B else C.


___
Python-ideas mailing list
Python-ideas@python.org
https://mail.python.org/mailman/listinfo/python-ideas
Code of Conduct: http://python.org/psf/codeofconduct/


Re: [Python-ideas] Add a dict with the attribute access capability

2017-11-29 Thread Daniel Moisset
As reference of prior art, there is https://pypi.python.org/pypi/munch in
PyPI

On 29 November 2017 at 05:52, Serhiy Storchaka  wrote:

> In 3.7 I have removed an old-deprecated plistlib.Dict. [1] Actually it
> already was deprecated when the plistlib module was added to the regular
> stdlib in Python 2.6.
>
> This is a dict subclass which allows to access items as attributes.
>
> d = plistlib.Dict()
> d['a'] = 1
> assert d.a == 1
> d.b = 2
> assert d['b'] == 2
>
> Raymond noticed that that capability seemed nice to have.
>
> What do you think about reviving this type as general purpose type in
> collections or types? Perhaps it can be convenient for working with JSON,
> plists, configuration files, databases and in other cases that need a dict
> with string keys.
>
> If reintroduce it, there are open questions.
>
> 1. The name of the type.
>
> 2. The location of the type. collections or types? Or other variants?
>
> 3. How it will collaborate with OrderedDict, defaultdict, etc?
>
> 4. Should it be a dict subclass, or a mixin, or a proxy? Or add several
> types?
>
>
> [1] https://bugs.python.org/issue29196
>
> ___
> Python-ideas mailing list
> Python-ideas@python.org
> https://mail.python.org/mailman/listinfo/python-ideas
> Code of Conduct: http://python.org/psf/codeofconduct/
>



-- 
Daniel F. Moisset - UK Country Manager - Machinalis Limited
www.machinalis.co.uk 
Skype: @dmoisset T: + 44 7398 827139

1 Fore St, London, EC2Y 9DT

Machinalis Limited is a company registered in England and Wales. Registered
number: 10574987.
___
Python-ideas mailing list
Python-ideas@python.org
https://mail.python.org/mailman/listinfo/python-ideas
Code of Conduct: http://python.org/psf/codeofconduct/


Re: [Python-ideas] [Python-Dev] What's the status of PEP 505: None-aware operators?

2017-11-29 Thread Elazar
On Wed, Nov 29, 2017 at 3:12 PM Serhiy Storchaka 
wrote:

> 29.11.17 15:01, Stephan Houben пише:
> > What about a more general:
> >
> > A if  B else C
> >
> > which would allow
> >
> > A if is not None else C
> >
> > but also e.g.
> >
> > A if >= 1 else 0
>
> This look the most "natural" to me. I.e. the least "unnatural". If we
> even will introduce a new special syntax I will prefer this syntax.
>
> The only disadvantage is that this will prevent introducing "angular
> parenthesis" in future: A if  == B else C.
>
>
Also, how do you treat more complex conditions? do you prohibit them?

A if >= 0 and < 2 else 0
B if >= 0 or < -1 else -1
C if and B else A   # i.e. C if C and B else E
D if -y else E  # is this an unary minus or a binary operation?

If any of these is allowed, it might confuse people.
It also break the ability to extract subexpression to variables.

(I kinda like this idea, but it doesn't look like a small, simple change to
the language, whereas ?? does).

Elazar
___
Python-ideas mailing list
Python-ideas@python.org
https://mail.python.org/mailman/listinfo/python-ideas
Code of Conduct: http://python.org/psf/codeofconduct/


Re: [Python-ideas] [Python-Dev] What's the status of PEP 505: None-aware operators?

2017-11-29 Thread David Mertz
I didn't say no use case exists, but rather "too special case." And/or
shortcutting is great, but truthiness feels much more general than noneness
to me.

But yes, 'first_non_none()" might have to address laziness in some manner,
depending on the use case. Zero argument lambdas and expression quoting are
the usual hacks (yes, both ugly in their own ways).

On Nov 29, 2017 12:14 AM, "Nick Coghlan"  wrote:

On 29 November 2017 at 16:13, David Mertz  wrote:
> Strong -1 still from me. Too special case for syntax. Just write a
function
> 'first_non_none()' that can perfectly will handle the need.

That's the equivalent of SQL's COALESCE, and it's insufficient for the
same reason "and" and "or" are syntax rather than builtins: the
function form doesn't provide short-circuiting behaviour.

As far as utility goes, I put it in a similar category to matrix
multiplication: if you don't need it, you don't need it, but when you
do need it, you need it a *lot*.

The use case where these operations come up is when you're working
with partially structured hierarchical data (*cough*JSON*cough*). In
those kinds of structures, None is frequently used as a marker to say
"this entire subtree is missing", and you either want to propagate
that None, or else replace it with something else (and the "something
else" may be a network call to a different service, so you definitely
don't want to do it if you don't need to).

So I'd remind folks to try to avoid the "I don't need this, so nobody
needs this" mistake. It's OK to say "the use case exists, but I still
don't want that particular syntax for it in Python" (I'm personally
inclined to agree with you on that front). It's not OK to try to claim
there are no use cases where the status quo is awkward enough to
become irritating (since it's an empirically false statement that you
don't need to be making).

Cheers,
Nick.

--
Nick Coghlan   |   ncogh...@gmail.com   |   Brisbane, Australia
___
Python-ideas mailing list
Python-ideas@python.org
https://mail.python.org/mailman/listinfo/python-ideas
Code of Conduct: http://python.org/psf/codeofconduct/


Re: [Python-ideas] How assignment should work with generators?

2017-11-29 Thread C Anthony Risinger
On Mon, Nov 27, 2017 at 3:49 PM, Greg Ewing 
wrote:

> C Anthony Risinger wrote:
>
>> * Perhaps existence of `__len__` should influence unpacking? There is a
>> semantic difference (and typically a visual one too) between 1-to-1
>> matching a fixed-width sequence/container on the RHS to identifiers on the
>> LHS, even if they look similar (ie. "if RHS has a length make it fit,
>> otherwise don't").
>>
>
> -1. There's a convention that an iterator can implement __len__
> to provide a hint about the number of items it will return
> (useful for preallocating space, etc.) It would be very
> annoying if such an iterator behaved differently from other
> iterators when unpacking.
>

Is __len__ a viable option now that __length_hint__ has been identified for
hints? IOW, if it's possible to know the full length of RHS ahead of time,
and the LHS is also fixed width, then unpack like today else unpack lazily.

This does make unpacking behave slightly different if the RHS is `Sized`
(per ABC, has __len__), but that doesn't seem too unreasonable. It's
different after all.

Using Ellipsis, eg. `a, b, ... = it()`, seems like a OK approach too but
it's unfortunate we are effectively working around the current
force-matching behavior of unpacking... is this the appropriate default? Is
there precedence or guidance elsewhere?

`a, b, ...` to me says "pull out a and b and throw away the rest", sort of
like the spread operator in JS/ECMA. The mere presence of more characters
(...) implies something else will *happen* to the remaining items, not that
they will be skipped.

What about the explicit RHS unpacking idea? Kirill commented on this
approach but I'm not sure others did:

>>> a, b = iter([1, 2, 3]); a, b
(1, 2)

>>> a, b = *iter([1, 2, 3]); a, b
Traceback (most recent call last):
  File "", line 1, in 
ValueError: too many values to unpack (expected 2)

This reads very clearly to me that the RHS is expected to be 100%
unraveled, and would work with any iterable in the same way.

Thanks,
___
Python-ideas mailing list
Python-ideas@python.org
https://mail.python.org/mailman/listinfo/python-ideas
Code of Conduct: http://python.org/psf/codeofconduct/


Re: [Python-ideas] Logging Levels

2017-11-29 Thread Mike Miller

Hi,

As mentioned, using logging everywhere has some advantages.  It doesn't have to 
be added later on, and it avoided a decent fraction of the work porting to 
Python 3.  Have found users tend to like the labeling of messages, from INFO to 
ERROR.  We skip the time stamp on the console and send to stdout.


And with a new-file template, it isn't a burden to set it and argparse up in new 
scripts. (--verbose etc)


-Mike


On 2017-11-28 20:45, Nick Coghlan wrote:

On 29 November 2017 at 06:46, Mike Miller  wrote:

Hi, the reason I use note is that I want it to be output by default.  So it
must be above warning, or perhaps the default level changed.


If the message to be displayed is part of the actual UX of a command
line tool, our advice is "You don't want the logging module, you want
the print() builtin":
https://docs.python.org/3/howto/logging.html#when-to-use-logging

As a relevant technical detail, it's also worth noting that the
default handler emits messages on stderr, while CLI UX messages should
generally be displayed on stdout.

Cheers,
Nick.


___
Python-ideas mailing list
Python-ideas@python.org
https://mail.python.org/mailman/listinfo/python-ideas
Code of Conduct: http://python.org/psf/codeofconduct/


[Python-ideas] Immutable dictionaries

2017-11-29 Thread Asen Bozhilov
This is my first post here. I have strong experience with JavaScript and
I'm lucky that I could move forward to Python.
What I miss in Python are immutable dictionaries. They are especially
useful for configurations and call functions which expect dictionary as
argument.  In my opinion they would let a place for underlying
optimizations.

I'd like to propose also literaling syntax for immutable dictionaries.

immutable_dict = (
'key1' : 'value1',
'key2' : 'value2'
)

This syntax is not ambiguous with expression statements and tuple literals,
but it requires a bit lookahed during the parsing.

I would appreciate your opinions on the topic. Most interesting for me is
why they are not already part of the language?

Kind regards,
Asen Bozhilov
___
Python-ideas mailing list
Python-ideas@python.org
https://mail.python.org/mailman/listinfo/python-ideas
Code of Conduct: http://python.org/psf/codeofconduct/


Re: [Python-ideas] [Python-Dev] What's the status of PEP 505: None-aware operators?

2017-11-29 Thread David Mertz
I like much of the thinking in Random's approach. But I still think None
isn't quite special enough to warrant it's own syntax.

However, his '(or None: name.strip()[4:].upper())' makes me realize that
what is being asked in all the '?(', '?.', '?[' syntax ideas is a kind of
ternary expression.  Except the ternary isn't based on whether a predicate
holds, but rather on whether an exception occurs (AttributeError, KeyError,
TypeError).  And the fallback in the ternary is always None rather than
being general.

I think we could generalize this to get something both more Pythonic and
more flexible.  E.g.:

val = name.strip()[4:].upper() except None

This would just be catching all errors, which is perhaps too broad.  But it
*would* allow a fallback other than None:

val = name.strip()[4:].upper() except -1

I think some syntax could be possible to only "catch" some exceptions and
let others propagate.  Maybe:

val = name.strip()[4:].upper() except (AttributeError, KeyError): -1

I don't really like throwing a colon in an expression though.  Perhaps some
other word or symbol could work instead.  How does this read:

val = name.strip()[4:].upper() except -1 in (AttributeError, KeyError)

Where the 'in' clause at the end would be optional, and default to
'Exception'.

I'll note that what this idea DOES NOT get us is:

  val = timeout ?? local_timeout ?? global_timeout

Those values that are "possibly None" don't raise exceptions, so they
wouldn't apply to this syntax.

Yours, David...


On Wed, Nov 29, 2017 at 9:03 AM, Random832  wrote:

> On Tue, Nov 28, 2017, at 15:31, Raymond Hettinger wrote:
> >
> > > I also cc python-dev to see if anybody here is strongly in favor or
> against this inclusion.
> >
> > Put me down for a strong -1.   The proposal would occasionally save a few
> > keystokes but comes at the expense of giving Python a more Perlish look
> > and a more arcane feel.
> >
> > One of the things I like about Python is that I can walk non-programmers
> > through the code and explain what it does.  The examples in PEP 505 look
> > like a step in the wrong direction.  They don't "look like Python" and
> > make me feel like I have to decrypt the code to figure-out what it does.
> >
> > timeout ?? local_timeout ?? global_timeout
> > 'foo' in (None ?? ['foo', 'bar'])
> > requested_quantity ?? default_quantity * price
> > name?.strip()[4:].upper()
> > user?.first_name.upper()
>
> Since we're looking at different syntax for the ?? operator, I have a
> suggestion for the ?. operator - and related ?[] and ?() that appeared
> in some of the proposals. How about this approach?
>
> Something like (or None: ...) as a syntax block in which any operation
> [lexically within the expression, not within e.g. called functions, so
> it's different from simply catching AttributeError etc, even if that
> could be limited to only catching when the operand is None] on None that
> is not valid for None will yield None instead.
>
> This isn't *entirely* equivalent, but offers finer control.
>
> v = name?.strip()[4:].upper() under the old proposal would be more or
> less equivalent to:
>
> v = name.strip()[4:].upper() if name is not None else None
>
> Whereas, you could get the same result with:
> (or None: name.strip()[4:].upper())
>
> Though that would technically be equivalent to these steps:
> v = name.strip if name is not None else None
> v = v() if v "
> v = v[4:] """
> v = v.upper """
> v = v() """
>
> The compiler could optimize this case since it knows none of the
> operations are valid on None. This has the advantage of being explicit
> about what scope the modified rules apply to, rather than simply
> implicitly being "to the end of the chain of dot/bracket/call operators"
>
> It could also be extended to apply, without any additional syntax, to
> binary operators (result is None if either operand is None) (or None: a
> + b), for example, could return None if either a or b is none.
>
> [I think I proposed this before with the syntax ?(...), the (or None:
> ...) is just an idea to make it look more like Python.]
> ___
> Python-Dev mailing list
> python-...@python.org
> https://mail.python.org/mailman/listinfo/python-dev
> Unsubscribe: https://mail.python.org/mailman/options/python-dev/
> mertz%40gnosis.cx
>



-- 
Keeping medicines from the bloodstreams of the sick; food
from the bellies of the hungry; books from the hands of the
uneducated; technology from the underdeveloped; and putting
advocates of freedom in prisons.  Intellectual property is
to the 21st century what the slave trade was to the 16th.
___
Python-ideas mailing list
Python-ideas@python.org
https://mail.python.org/mailman/listinfo/python-ideas
Code of Conduct: http://python.org/psf/codeofconduct/


Re: [Python-ideas] Immutable dictionaries

2017-11-29 Thread David Mertz
https://www.python.org/dev/peps/pep-0416/

Also: https://pypi.python.org/pypi/frozendict

On Wed, Nov 29, 2017 at 9:30 AM, Asen Bozhilov 
wrote:

> This is my first post here. I have strong experience with JavaScript and
> I'm lucky that I could move forward to Python.
> What I miss in Python are immutable dictionaries. They are especially
> useful for configurations and call functions which expect dictionary as
> argument.  In my opinion they would let a place for underlying
> optimizations.
>
> I'd like to propose also literaling syntax for immutable dictionaries.
>
> immutable_dict = (
> 'key1' : 'value1',
> 'key2' : 'value2'
> )
>
> This syntax is not ambiguous with expression statements and tuple
> literals, but it requires a bit lookahed during the parsing.
>
> I would appreciate your opinions on the topic. Most interesting for me is
> why they are not already part of the language?
>
> Kind regards,
> Asen Bozhilov
>
> ___
> Python-ideas mailing list
> Python-ideas@python.org
> https://mail.python.org/mailman/listinfo/python-ideas
> Code of Conduct: http://python.org/psf/codeofconduct/
>
>


-- 
Keeping medicines from the bloodstreams of the sick; food
from the bellies of the hungry; books from the hands of the
uneducated; technology from the underdeveloped; and putting
advocates of freedom in prisons.  Intellectual property is
to the 21st century what the slave trade was to the 16th.
___
Python-ideas mailing list
Python-ideas@python.org
https://mail.python.org/mailman/listinfo/python-ideas
Code of Conduct: http://python.org/psf/codeofconduct/


Re: [Python-ideas] Immutable dictionaries

2017-11-29 Thread Random832
On Wed, Nov 29, 2017, at 12:30, Asen Bozhilov wrote:
> I would appreciate your opinions on the topic. Most interesting for me is
> why they are not already part of the language?

See the rejection notes at https://www.python.org/dev/peps/pep-0416/
___
Python-ideas mailing list
Python-ideas@python.org
https://mail.python.org/mailman/listinfo/python-ideas
Code of Conduct: http://python.org/psf/codeofconduct/


Re: [Python-ideas] Add a dict with the attribute access capability

2017-11-29 Thread Nick Timkovich
On Wed, Nov 29, 2017 at 7:21 AM, Daniel Moisset 
wrote:

> As reference of prior art, there is https://pypi.python.org/pypi/munch in
> PyPI
>

Box is also popular as it permits deeper nesting:
https://pypi.python.org/pypi/python-box/ https://github.com/cdgriffith/Box
Addict is similar: https://pypi.python.org/pypi/addict/2.1.1
https://github.com/mewwts/addict and I've seen AttrDict a few times in code
I maintain: https://pypi.python.org/pypi/attrdict
https://github.com/bcj/AttrDict

With a cursory search, also found:
* DotMap: https://pypi.python.org/pypi/dotmap
https://github.com/drgrib/dotmap
* EasyDict https://pypi.python.org/pypi/easydict
https://github.com/makinacorpus/easydict
* Treedict (older) https://pypi.python.org/pypi/treedict
* Bunch (older) https://pypi.python.org/pypi/bunch

...I spy a theme :P

Haven't dug into them that much, but I'd try to answer most questions with
how they do it. I'm not sure if the recursive 'items as attributes within
items as attributes...' feature is a can of worms or if it's something like
defaultdict(dict), but with more levels. Getting deeply nested items with
dots seems to be the usual use (i.e. complicated JSONs), and I think the
degree of laziness in creating/setting nested items is variable.

Nick
___
Python-ideas mailing list
Python-ideas@python.org
https://mail.python.org/mailman/listinfo/python-ideas
Code of Conduct: http://python.org/psf/codeofconduct/


Re: [Python-ideas] Logging Levels

2017-11-29 Thread Mike Miller
Hi, IMHO the prior decision(s) are too conservative.  Reading the bugs, we can 
see lots of folks reinventing the wheel with common use cases for no good 
reason.  I also gave examples in the log4j, docs, and web apps world that these 
levels are recognized needs.


An addition would represent a very tiny fractional increase in the complexity of 
the logging module, from ~6 to ~8 in one small corner.  It's not like we're 
adding human expressions to cats and piles of poo here are we?  ;-)


The builtin java logging suffers from backwards compatibility with an awkward 
initial design.  log4j doesn't (nor we) have that problem, but it includes some 
cases suggested.


In short, have been using note and fatal for years productively.  Not a strong 
proponent of trace and have survived without it so far, but if it were there I'd 
have used it a few times over the years.




On 2017-11-28 12:17, Serhiy Storchaka wrote:

28.11.17 21:45, Guido van Rossum пише:
These look like good improvements. I think you should make an issue on 
bugs.python.org  describing your proposal and if you 
can submit a PR that implements it.


See https://bugs.python.org/issue31732

It was discussed and rejected. Citing Raymond: "Overall, this seems rehash and 
second guess the discussions and decisions made 15 years ago when PEP 282 was 
accepted."


The set of logging levels is not closed. The user can extend it to cover more 
specialized uses by logging.addLevelName(). There are disadvantages of having 
too much standard names for logging levels (as we can see in Java).


___
Python-ideas mailing list
Python-ideas@python.org
https://mail.python.org/mailman/listinfo/python-ideas
Code of Conduct: http://python.org/psf/codeofconduct/


Re: [Python-ideas] [Python-Dev] What's the status of PEP 505: None-aware operators?

2017-11-29 Thread Eric V. Smith

> On Nov 29, 2017, at 12:40 PM, David Mertz  wrote:
> 
> I like much of the thinking in Random's approach. But I still think None 
> isn't quite special enough to warrant it's own syntax.
> 
> However, his '(or None: name.strip()[4:].upper())' makes me realize that what 
> is being asked in all the '?(', '?.', '?[' syntax ideas is a kind of ternary 
> expression.  Except the ternary isn't based on whether a predicate holds, but 
> rather on whether an exception occurs (AttributeError, KeyError, TypeError).  
> And the fallback in the ternary is always None rather than being general.
> 
> I think we could generalize this to get something both more Pythonic and more 
> flexible.  E.g.:
> 
> val = name.strip()[4:].upper() except None
> 
> This would just be catching all errors, which is perhaps too broad.  But it 
> *would* allow a fallback other than None:
> 
> val = name.strip()[4:].upper() except -1
> 
> I think some syntax could be possible to only "catch" some exceptions and let 
> others propagate.  Maybe:
> 
> val = name.strip()[4:].upper() except (AttributeError, KeyError): -1
> 
> I don't really like throwing a colon in an expression though.  Perhaps some 
> other word or symbol could work instead.  How does this read:
> 
> val = name.strip()[4:].upper() except -1 in (AttributeError, KeyError)
> 
> Where the 'in' clause at the end would be optional, and default to 
> 'Exception'.
> 
> I'll note that what this idea DOES NOT get us is:
> 
>   val = timeout ?? local_timeout ?? global_timeout
> 
> Those values that are "possibly None" don't raise exceptions, so they 
> wouldn't apply to this syntax.

See the rejected PEP 463 for Exception catching expressions. 

Eric. 

> 
> Yours, David...
> 
> 
>> On Wed, Nov 29, 2017 at 9:03 AM, Random832  wrote:
>> On Tue, Nov 28, 2017, at 15:31, Raymond Hettinger wrote:
>> >
>> > > I also cc python-dev to see if anybody here is strongly in favor or 
>> > > against this inclusion.
>> >
>> > Put me down for a strong -1.   The proposal would occasionally save a few
>> > keystokes but comes at the expense of giving Python a more Perlish look
>> > and a more arcane feel.
>> >
>> > One of the things I like about Python is that I can walk non-programmers
>> > through the code and explain what it does.  The examples in PEP 505 look
>> > like a step in the wrong direction.  They don't "look like Python" and
>> > make me feel like I have to decrypt the code to figure-out what it does.
>> >
>> > timeout ?? local_timeout ?? global_timeout
>> > 'foo' in (None ?? ['foo', 'bar'])
>> > requested_quantity ?? default_quantity * price
>> > name?.strip()[4:].upper()
>> > user?.first_name.upper()
>> 
>> Since we're looking at different syntax for the ?? operator, I have a
>> suggestion for the ?. operator - and related ?[] and ?() that appeared
>> in some of the proposals. How about this approach?
>> 
>> Something like (or None: ...) as a syntax block in which any operation
>> [lexically within the expression, not within e.g. called functions, so
>> it's different from simply catching AttributeError etc, even if that
>> could be limited to only catching when the operand is None] on None that
>> is not valid for None will yield None instead.
>> 
>> This isn't *entirely* equivalent, but offers finer control.
>> 
>> v = name?.strip()[4:].upper() under the old proposal would be more or
>> less equivalent to:
>> 
>> v = name.strip()[4:].upper() if name is not None else None
>> 
>> Whereas, you could get the same result with:
>> (or None: name.strip()[4:].upper())
>> 
>> Though that would technically be equivalent to these steps:
>> v = name.strip if name is not None else None
>> v = v() if v "
>> v = v[4:] """
>> v = v.upper """
>> v = v() """
>> 
>> The compiler could optimize this case since it knows none of the
>> operations are valid on None. This has the advantage of being explicit
>> about what scope the modified rules apply to, rather than simply
>> implicitly being "to the end of the chain of dot/bracket/call operators"
>> 
>> It could also be extended to apply, without any additional syntax, to
>> binary operators (result is None if either operand is None) (or None: a
>> + b), for example, could return None if either a or b is none.
>> 
>> [I think I proposed this before with the syntax ?(...), the (or None:
>> ...) is just an idea to make it look more like Python.]
>> ___
>> Python-Dev mailing list
>> python-...@python.org
>> https://mail.python.org/mailman/listinfo/python-dev
>> Unsubscribe: 
>> https://mail.python.org/mailman/options/python-dev/mertz%40gnosis.cx
> 
> 
> 
> -- 
> Keeping medicines from the bloodstreams of the sick; food 
> from the bellies of the hungry; books from the hands of the 
> uneducated; technology from the underdeveloped; and putting 
> advocates of freedom in prisons.  Intellectual property is
> to the 21st century what the slave trade was to the 16th.
> ___

Re: [Python-ideas] [Python-Dev] What's the status of PEP 505: None-aware operators?

2017-11-29 Thread Barry Warsaw
On Nov 29, 2017, at 12:40, David Mertz  wrote:

> I think some syntax could be possible to only "catch" some exceptions and let 
> others propagate.  Maybe:
> 
>val = name.strip()[4:].upper() except (AttributeError, KeyError): -1
> 
> I don't really like throwing a colon in an expression though.  Perhaps some 
> other word or symbol could work instead.  How does this read:
> 
>val = name.strip()[4:].upper() except -1 in (AttributeError, KeyError)

I don’t know whether I like any of this  but I think a more natural 
spelling would be:

   val = name.strip()[4:].upper() except (AttributeError, KeyError) as -1

which could devolve into:

   val = name.strip()[4:].upper() except KeyError as -1

or:

   val = name.strip()[4:].upper() except KeyError # Implicit `as None`

I would *not* add any spelling for an explicit bare-except equivalent.  You 
would have to write:

   val = name.strip()[4:].upper() except Exception as -1

Cheers,
-Barry



signature.asc
Description: Message signed with OpenPGP
___
Python-ideas mailing list
Python-ideas@python.org
https://mail.python.org/mailman/listinfo/python-ideas
Code of Conduct: http://python.org/psf/codeofconduct/


Re: [Python-ideas] Immutable dictionaries

2017-11-29 Thread Victor Stinner
2017-11-29 18:30 GMT+01:00 Asen Bozhilov :
> I'd like to propose also literaling syntax for immutable dictionaries.
>
> immutable_dict = (
> 'key1' : 'value1',
> 'key2' : 'value2'
> )

Since Python 3.3, you can write:

vstinner@apu$ python3
Python 3.6.3 (default, Oct  9 2017, 12:07:10)
>>> import types
>>> immutable_dict = types.MappingProxyType({"key": "value"})

>>> immutable_dict.pop('key')
AttributeError: 'mappingproxy' object has no attribute 'pop'

>>> immutable_dict['key'] = 'value2'
TypeError: 'mappingproxy' object does not support item assignment

>>> immutable_dict['key2'] = 'value3'
TypeError: 'mappingproxy' object does not support item assignment

Maybe not the ideal syntax, but it already works without having to
modify the Python syntax, and it works on Python 3.3 and newer ;-)

Victor
___
Python-ideas mailing list
Python-ideas@python.org
https://mail.python.org/mailman/listinfo/python-ideas
Code of Conduct: http://python.org/psf/codeofconduct/


Re: [Python-ideas] generator vs iterator etc. (was: How assignment should work with generators?)

2017-11-29 Thread Stephen J. Turnbull
Steven D'Aprano writes:

 > > The two iterators have the same duck-type, the generator is different.
 > 
 > How is the generator different?

My bad, I got the comparison backward.  The generator *is* different,
but it's because the generator has *extra* public methods, not fewer.

Sorry for the noise.

___
Python-ideas mailing list
Python-ideas@python.org
https://mail.python.org/mailman/listinfo/python-ideas
Code of Conduct: http://python.org/psf/codeofconduct/


Re: [Python-ideas] Immutable dictionaries

2017-11-29 Thread Barry Warsaw
David Mertz wrote:
> https://www.python.org/dev/peps/pep-0416/

PEP 351 (also rejected) is related to this.

-Barry

___
Python-ideas mailing list
Python-ideas@python.org
https://mail.python.org/mailman/listinfo/python-ideas
Code of Conduct: http://python.org/psf/codeofconduct/


Re: [Python-ideas] Add a dict with the attribute access capability

2017-11-29 Thread Barry Warsaw
Serhiy Storchaka wrote:
> In 3.7 I have removed an old-deprecated plistlib.Dict. [1] Actually it
> already was deprecated when the plistlib module was added to the regular
> stdlib in Python 2.6.
> 
> Raymond noticed that that capability seemed nice to have.

So nice in fact that I'm sure I've reimplemented something similar
several times. :)

> What do you think about reviving this type as general purpose type in
> collections or types? Perhaps it can be convenient for working with
> JSON, plists, configuration files, databases and in other cases that
> need a dict with string keys.
> 
> If reintroduce it, there are open questions.
> 
> 1. The name of the type.
> 
> 2. The location of the type. collections or types? Or other variants?
> 
> 3. How it will collaborate with OrderedDict, defaultdict, etc?
> 
> 4. Should it be a dict subclass, or a mixin, or a proxy? Or add several
> types?

I also wonder whether PEP 557 dataclasses could provide this except in
the opposite direction, e.g. by optionally adding __getitem__ support.

-Barry


___
Python-ideas mailing list
Python-ideas@python.org
https://mail.python.org/mailman/listinfo/python-ideas
Code of Conduct: http://python.org/psf/codeofconduct/


Re: [Python-ideas] Repurpose `assert' into a general-purpose check

2017-11-29 Thread Barry Warsaw

Nathan Schneider wrote:

> I think it would be interesting to investigate how assert statements are
> used in the wild. I can think of three kinds of uses:

assert statements are also a form of executable documentation.  It says
something like "I think the internal state of my code must be this way,
otherwise I don't really understand what I wrote".

Now, maybe you could argue that such use should be enabled
unconditionally, but I disagree since usually your understanding of the
state of your code is correct, so the additional checks are unnecessary,
and people *do* use -O and -OO in practice.  And these days it's even
more practical to do so, given the `opt-*` level of pyc tagging:

% python3 -c "import foo"
% python3 -O -c "import foo"
% python3 -OO -c "import foo"
% ls foo/__pycache__/
__init__.cpython-36.opt-1.pyc   __init__.cpython-36.pyc
__init__.cpython-36.opt-2.pyc

I also wonder how this would interact with pytest's um, 'hijacking' of
the assert statement.

Cheers,
-Barry

___
Python-ideas mailing list
Python-ideas@python.org
https://mail.python.org/mailman/listinfo/python-ideas
Code of Conduct: http://python.org/psf/codeofconduct/


Re: [Python-ideas] [Python-Dev] What's the status of PEP 505: None-aware operators?

2017-11-29 Thread David Mertz
True enough. I remember the prior discussion, but didn't look up the PEP
number. I know it's hard to revisit these ideas, but occasionally it works,
especially if a nicer spelling is found (Barry proposed some a bit
different than my ideas)

On Nov 29, 2017 9:55 AM, "Eric V. Smith"  wrote:


On Nov 29, 2017, at 12:40 PM, David Mertz  wrote:

I like much of the thinking in Random's approach. But I still think None
isn't quite special enough to warrant it's own syntax.

However, his '(or None: name.strip()[4:].upper())' makes me realize that
what is being asked in all the '?(', '?.', '?[' syntax ideas is a kind of
ternary expression.  Except the ternary isn't based on whether a predicate
holds, but rather on whether an exception occurs (AttributeError, KeyError,
TypeError).  And the fallback in the ternary is always None rather than
being general.

I think we could generalize this to get something both more Pythonic and
more flexible.  E.g.:

val = name.strip()[4:].upper() except None

This would just be catching all errors, which is perhaps too broad.  But it
*would* allow a fallback other than None:

val = name.strip()[4:].upper() except -1

I think some syntax could be possible to only "catch" some exceptions and
let others propagate.  Maybe:

val = name.strip()[4:].upper() except (AttributeError, KeyError): -1

I don't really like throwing a colon in an expression though.  Perhaps some
other word or symbol could work instead.  How does this read:

val = name.strip()[4:].upper() except -1 in (AttributeError, KeyError)

Where the 'in' clause at the end would be optional, and default to
'Exception'.

I'll note that what this idea DOES NOT get us is:

  val = timeout ?? local_timeout ?? global_timeout

Those values that are "possibly None" don't raise exceptions, so they
wouldn't apply to this syntax.


See the rejected PEP 463 for Exception catching expressions.

Eric.


Yours, David...


On Wed, Nov 29, 2017 at 9:03 AM, Random832  wrote:

> On Tue, Nov 28, 2017, at 15:31, Raymond Hettinger wrote:
> >
> > > I also cc python-dev to see if anybody here is strongly in favor or
> against this inclusion.
> >
> > Put me down for a strong -1.   The proposal would occasionally save a few
> > keystokes but comes at the expense of giving Python a more Perlish look
> > and a more arcane feel.
> >
> > One of the things I like about Python is that I can walk non-programmers
> > through the code and explain what it does.  The examples in PEP 505 look
> > like a step in the wrong direction.  They don't "look like Python" and
> > make me feel like I have to decrypt the code to figure-out what it does.
> >
> > timeout ?? local_timeout ?? global_timeout
> > 'foo' in (None ?? ['foo', 'bar'])
> > requested_quantity ?? default_quantity * price
> > name?.strip()[4:].upper()
> > user?.first_name.upper()
>
> Since we're looking at different syntax for the ?? operator, I have a
> suggestion for the ?. operator - and related ?[] and ?() that appeared
> in some of the proposals. How about this approach?
>
> Something like (or None: ...) as a syntax block in which any operation
> [lexically within the expression, not within e.g. called functions, so
> it's different from simply catching AttributeError etc, even if that
> could be limited to only catching when the operand is None] on None that
> is not valid for None will yield None instead.
>
> This isn't *entirely* equivalent, but offers finer control.
>
> v = name?.strip()[4:].upper() under the old proposal would be more or
> less equivalent to:
>
> v = name.strip()[4:].upper() if name is not None else None
>
> Whereas, you could get the same result with:
> (or None: name.strip()[4:].upper())
>
> Though that would technically be equivalent to these steps:
> v = name.strip if name is not None else None
> v = v() if v "
> v = v[4:] """
> v = v.upper """
> v = v() """
>
> The compiler could optimize this case since it knows none of the
> operations are valid on None. This has the advantage of being explicit
> about what scope the modified rules apply to, rather than simply
> implicitly being "to the end of the chain of dot/bracket/call operators"
>
> It could also be extended to apply, without any additional syntax, to
> binary operators (result is None if either operand is None) (or None: a
> + b), for example, could return None if either a or b is none.
>
> [I think I proposed this before with the syntax ?(...), the (or None:
> ...) is just an idea to make it look more like Python.]
> ___
> Python-Dev mailing list
> python-...@python.org
> https://mail.python.org/mailman/listinfo/python-dev
> Unsubscribe: https://mail.python.org/mailman/options/python-dev/mertz%
> 40gnosis.cx
>



-- 
Keeping medicines from the bloodstreams of the sick; food
from the bellies of the hungry; books from the hands of the
uneducated; technology from the underdeveloped; and putting
advocates of freedom in prison

Re: [Python-ideas] Add a dict with the attribute access capability

2017-11-29 Thread Ivan Levkivskyi
On 29 November 2017 at 20:11, Barry Warsaw  wrote:

> Serhiy Storchaka wrote:
> > In 3.7 I have removed an old-deprecated plistlib.Dict. [1] Actually it
> > already was deprecated when the plistlib module was added to the regular
> > stdlib in Python 2.6.
> >
> > Raymond noticed that that capability seemed nice to have.
>
> So nice in fact that I'm sure I've reimplemented something similar
> several times. :)
>
> > What do you think about reviving this type as general purpose type in
> > collections or types? Perhaps it can be convenient for working with
> > JSON, plists, configuration files, databases and in other cases that
> > need a dict with string keys.
> >
> > If reintroduce it, there are open questions.
> >
> > 1. The name of the type.
> >
> > 2. The location of the type. collections or types? Or other variants?
> >
> > 3. How it will collaborate with OrderedDict, defaultdict, etc?
> >
> > 4. Should it be a dict subclass, or a mixin, or a proxy? Or add several
> > types?
>
> I also wonder whether PEP 557 dataclasses could provide this except in
> the opposite direction, e.g. by optionally adding __getitem__ support.
>

This was discussed in https://github.com/ericvsmith/dataclasses/issues/21
and it was decided to postpone this.

--
Ivan
___
Python-ideas mailing list
Python-ideas@python.org
https://mail.python.org/mailman/listinfo/python-ideas
Code of Conduct: http://python.org/psf/codeofconduct/


Re: [Python-ideas] [Python-Dev] What's the status of PEP 505: None-aware operators?

2017-11-29 Thread Greg Ewing

Nick Coghlan wrote:


What about more English-like syntax:

X or else Y


The problem with constructs like this is that they look like they
should mean the same thing as "X or Y".


How about:

   x otherwise y

It looks different enough from "or" that you're not going
to accidentally read it that way when skimming.

The meaning is something you'll have to learn if you don't
know, but at least it's a word that can be googled for.

--
Greg
___
Python-ideas mailing list
Python-ideas@python.org
https://mail.python.org/mailman/listinfo/python-ideas
Code of Conduct: http://python.org/psf/codeofconduct/


Re: [Python-ideas] [Python-Dev] What's the status of PEP 505: None-aware operators?

2017-11-29 Thread Greg Ewing

Stephan Houben wrote:


X or else Y


Sounds like a Python dialect for Mafia use.

   customer.repay(loan) or else apply(baseball_bat, customer.kneecaps)

--
Greg
___
Python-ideas mailing list
Python-ideas@python.org
https://mail.python.org/mailman/listinfo/python-ideas
Code of Conduct: http://python.org/psf/codeofconduct/


Re: [Python-ideas] [Python-Dev] What's the status of PEP 505: None-aware operators?

2017-11-29 Thread Greg Ewing

Stephan Houben wrote:


A if is not None else C


Reading that gives me the feeling that something in my
brain has slipped a tooth.

It would read better with some kind of pronoun in there:

   A if it is not None else C

Hypercard's Hypertalk had a special variable "it" that
worked sort of like that.

--
Greg
___
Python-ideas mailing list
Python-ideas@python.org
https://mail.python.org/mailman/listinfo/python-ideas
Code of Conduct: http://python.org/psf/codeofconduct/


Re: [Python-ideas] How assignment should work with generators?

2017-11-29 Thread Greg Ewing

C Anthony Risinger wrote:
Is __len__ a viable option now that __length_hint__ has been identified 
for hints?


No, I misremembered that feature, sorry.

But I still don't like the idea of changing behaviour
depending on whether the RHS "looks like" an iterator
or not.

I'm not sure how to explain why I feel that way, but
I think it's because the proposal would make the
behaviour depend on the presence or otherwise of a
method that's not actually used by the operation
being performed. Unpacking doesn't need to know the
length in advance, so it shouldn't care whether there
is a __len__ method.

--
Greg
___
Python-ideas mailing list
Python-ideas@python.org
https://mail.python.org/mailman/listinfo/python-ideas
Code of Conduct: http://python.org/psf/codeofconduct/


Re: [Python-ideas] [Python-Dev] What's the status of PEP 505: None-aware operators?

2017-11-29 Thread Stephan Houben
Op 29 nov. 2017 22:35 schreef "Greg Ewing" :


It would read better with some kind of pronoun in there:

   A if it is not None else C

Hypercard's Hypertalk had a special variable "it" that
worked sort of like that.


I  considered that,  but there are two issues.

1. Backward-incompatible change

2. The semantics of
A if B else C
now depends on if B contains 'it',
in which case A gets evaluated unconditionally and prior to B.
What if evaluation of 'it' is itself conditional, e.g.

print("hello") if a or it else print("goodbye")

Note that in the

A if  B else C

proposal the evaluation of the implicit 'it' is never conditional in that
way.

Stephan



-- 
Greg

___
Python-ideas mailing list
Python-ideas@python.org
https://mail.python.org/mailman/listinfo/python-ideas
Code of Conduct: http://python.org/psf/codeofconduct/
___
Python-ideas mailing list
Python-ideas@python.org
https://mail.python.org/mailman/listinfo/python-ideas
Code of Conduct: http://python.org/psf/codeofconduct/


Re: [Python-ideas] How assignment should work with generators?

2017-11-29 Thread Greg Ewing

C Anthony Risinger wrote:

`a, b, ...` to me says "pull out a and b and throw away the rest"... 

> The mere presence of more
characters (...) implies something else will *happen* to the remaining 
items, not that they will be skipped.


It seems that many people think about unpacking rather
differently from the way I do. I think the difference
is procedural vs. declarative.

To my way of thinking, something like

   a, b, c = x

is a pattern-matching operation. It's declaring that
x is a sequence of three things, and giving names to
those things. It's not saying to *do* anything to x.

With that interpretation,

   a, b, ... = x

is declaring that x is a sequence of at least two
items, and giving names to the first two. The ellipsis
just means that there could be more items, but we
don't want to give them names.

On the other hand, some people seem to be interpreting
the word "unpack" as in "unpack a suitcase", i.e. the
suitcase is empty afterwards. But unpacking has never
meant that in Python! If it did, then

   x = [1, 2, 3]
   a, b, c = x

would leave x == [] afterwards.

The only case where unpacking behaves like that is when
the rhs is an iterator rather than a sequence, in which
case a side effect is unavoidable. The question then is
what the side effect should be.

I would argue that, since the side effect is something
that's not really wanted, it should be as *small* as
possible. By that argument,

   a, b, ... = some_iterator

should do as *little* as possible to fulfill what's
being asked, i.e. give names to the first two items
produced by the rhs. Consuming those two items is
unavoidable, but there's no need to consume any more.

As for the "extra syntax", we only need it because we've
defined the existing unpacking syntax to imply verifying
that the rhs has exactly the same length as the pattern.

We now want to express patterns which don't impose
a length constraint, so we need to write them some
other way.

--
Greg
___
Python-ideas mailing list
Python-ideas@python.org
https://mail.python.org/mailman/listinfo/python-ideas
Code of Conduct: http://python.org/psf/codeofconduct/


Re: [Python-ideas] [Python-Dev] What's the status of PEP 505: None-aware operators?

2017-11-29 Thread Chris Angelico
On Thu, Nov 30, 2017 at 8:56 AM, Stephan Houben  wrote:
>
>
> Op 29 nov. 2017 22:35 schreef "Greg Ewing" :
>
>
> It would read better with some kind of pronoun in there:
>
>A if it is not None else C
>
> Hypercard's Hypertalk had a special variable "it" that
> worked sort of like that.
>
>
> I  considered that,  but there are two issues.
>
> 1. Backward-incompatible change
>
> 2. The semantics of
> A if B else C
> now depends on if B contains 'it',
> in which case A gets evaluated unconditionally and prior to B.
> What if evaluation of 'it' is itself conditional, e.g.
>
> print("hello") if a or it else print("goodbye")
>
> Note that in the
>
> A if  B else C
>
> proposal the evaluation of the implicit 'it' is never conditional in that
> way.

The only way would be for "it" to be a keyword. You can't misinterpret
"A if pass is not None else C", or "A if def is not None else C", as
they're currently syntax errors. Obviously we don't want the word "it"
to become a keyword (massive breakage right there), and I'm pretty
sure there's no existing keyword that actually makes sense here, so
this proposal would depend on coming up with a useful word that
wouldn't collide too much. I'm -0.9 unless someone can find the
perfect word.

ChrisA
___
Python-ideas mailing list
Python-ideas@python.org
https://mail.python.org/mailman/listinfo/python-ideas
Code of Conduct: http://python.org/psf/codeofconduct/


Re: [Python-ideas] Repurpose `assert' into a general-purpose check

2017-11-29 Thread Petr Viktorin

On 11/29/2017 08:31 PM, Barry Warsaw wrote:


Nathan Schneider wrote:


I think it would be interesting to investigate how assert statements are
used in the wild. I can think of three kinds of uses:


assert statements are also a form of executable documentation.  It says
something like "I think the internal state of my code must be this way,
otherwise I don't really understand what I wrote".

Now, maybe you could argue that such use should be enabled
unconditionally, but I disagree since usually your understanding of the
state of your code is correct, so the additional checks are unnecessary,
and people *do* use -O and -OO in practice.  And these days it's even
more practical to do so, given the `opt-*` level of pyc tagging:

% python3 -c "import foo"
% python3 -O -c "import foo"
% python3 -OO -c "import foo"
% ls foo/__pycache__/
__init__.cpython-36.opt-1.pyc   __init__.cpython-36.pyc
__init__.cpython-36.opt-2.pyc

I also wonder how this would interact with pytest's um, 'hijacking' of
the assert statement.


Pytest compiles from source, and uses its own cache tags which look like 
".cpython-36-PYTEST.pyc".


https://github.com/pytest-dev/pytest/blob/master/_pytest/assertion/rewrite.py


___
Python-ideas mailing list
Python-ideas@python.org
https://mail.python.org/mailman/listinfo/python-ideas
Code of Conduct: http://python.org/psf/codeofconduct/


Re: [Python-ideas] [Python-Dev] What's the status of PEP 505: None-aware operators?

2017-11-29 Thread Steven D'Aprano
On Wed, Nov 29, 2017 at 06:49:14AM -0800, David Mertz wrote:
> I didn't say no use case exists, but rather "too special case." And/or
> shortcutting is great, but truthiness feels much more general than noneness
> to me.

Of course truthiness is much more general than Noneness -- and that's 
precisely the problem with using `or`. It's too general.

If you haven't read the PEP, you should, because this is extensively 
discussed there. One of the problems the author discusses is that `or` 
is recommended on Stackoverflow as the best way to perform short-cutting 
None tests, often with no caveats given.

We've been here before. Python old-timers may remember the former 
idiomatic way to get a ternary if expression:

condition and first or second

which was also buggy (if first happens to be falsey, second is returned 
even when condition is true).



-- 
Steve
___
Python-ideas mailing list
Python-ideas@python.org
https://mail.python.org/mailman/listinfo/python-ideas
Code of Conduct: http://python.org/psf/codeofconduct/


Re: [Python-ideas] [Python-Dev] What's the status of PEP 505: None-aware operators?

2017-11-29 Thread MRAB

On 2017-11-29 21:27, Greg Ewing wrote:

Nick Coghlan wrote:


What about more English-like syntax:

X or else Y


The problem with constructs like this is that they look like they
should mean the same thing as "X or Y".


How about:

 x otherwise y

It looks different enough from "or" that you're not going
to accidentally read it that way when skimming.

The meaning is something you'll have to learn if you don't
know, but at least it's a word that can be googled for.

It has the disadvantage that it's quite long. How about "alt" 
(abbreviation for "alternatively"):


x alt y
___
Python-ideas mailing list
Python-ideas@python.org
https://mail.python.org/mailman/listinfo/python-ideas
Code of Conduct: http://python.org/psf/codeofconduct/


Re: [Python-ideas] How assignment should work with generators?

2017-11-29 Thread Brendan Barnwell

On 2017-11-29 14:21, Greg Ewing wrote:

C Anthony Risinger wrote:


`a, b, ...` to me says "pull out a and b and throw away the rest"...

  > The mere presence of more

characters (...) implies something else will *happen* to the remaining
items, not that they will be skipped.


It seems that many people think about unpacking rather
differently from the way I do. I think the difference
is procedural vs. declarative.

To my way of thinking, something like

 a, b, c = x

is a pattern-matching operation. It's declaring that
x is a sequence of three things, and giving names to
those things. It's not saying to *do* anything to x.

With that interpretation,

 a, b, ... = x

is declaring that x is a sequence of at least two
items, and giving names to the first two. The ellipsis
just means that there could be more items, but we
don't want to give them names.

On the other hand, some people seem to be interpreting
the word "unpack" as in "unpack a suitcase", i.e. the
suitcase is empty afterwards. But unpacking has never
meant that in Python! If it did, then

 x = [1, 2, 3]
 a, b, c = x

would leave x == [] afterwards.

The only case where unpacking behaves like that is when
the rhs is an iterator rather than a sequence, in which
case a side effect is unavoidable. The question then is
what the side effect should be.


	That's an interesting analysis, but I don't think your view is really 
the right one.  It *is* unpacking a suitcase, it's just that *if 
necessary* the suitcase is constructed just in time for you to unpack 
it.  In other words, the suitcase is not the list [1, 2, 3], but an 
iterator over this list.  This is the same as the behavior for "for" 
loops: if you do "for item in [1, 2, 3]", the actual thing you're 
unrolling is an iterator over the list.  In some sense the point of the 
iterable/iterator distinction is to distinguish suitcases (iterators) 
from things-that-produce-suitcases-on-demand (iterables).  It's just 
that Python syntax (very nicely) allows us to omit the explicit iter() 
call.  The fact that iteration is taking place is specified by the 
context; that could be a for loop, or it could be multiple assignment 
targets, but it's iteration all the same.



I would argue that, since the side effect is something
that's not really wanted, it should be as *small* as
possible. By that argument,

 a, b, ... = some_iterator

should do as *little* as possible to fulfill what's
being asked, i.e. give names to the first two items
produced by the rhs. Consuming those two items is
unavoidable, but there's no need to consume any more.


	I see your point, but I think that middle ground doesn't really give 
the benefits of either.  If you expect your suitcase to remain unopened, 
it's pretty cold comfort to find that someone has opened it and taken 
only your pants and shoes but left the rest.  If the side effect isn't 
wanted, you really need the RHS to be something that isn't affected 
(i.e., a re-iterable).  It does seem that in some cases you may want the 
iterator to be exhausted, and in others not, but I don't think it's a 
good idea to try to "hide" the unpacking by limiting the number of 
iterations.  The important difference is between any irreversible 
unpacking at all, and none at all.



--
Brendan Barnwell
"Do not follow where the path may lead.  Go, instead, where there is no 
path, and leave a trail."

   --author unknown
___
Python-ideas mailing list
Python-ideas@python.org
https://mail.python.org/mailman/listinfo/python-ideas
Code of Conduct: http://python.org/psf/codeofconduct/


Re: [Python-ideas] Add a dict with the attribute access capability

2017-11-29 Thread Chris Barker
On Wed, Nov 29, 2017 at 12:52 AM, Serhiy Storchaka 
wrote:

> This is a dict subclass which allows to access items as attributes.
>
> d = plistlib.Dict()
> d['a'] = 1
> assert d.a == 1
> d.b = 2
> assert d['b'] == 2
>


> What do you think about reviving this type as general purpose type in
> collections or types


Am I I the only one that thinks this is a "Bad Idea"?

For me, it simply confuses even more the question of "is this code or is
this data?" -- which is a difficult enough design question in a dynamic
language.

And the couple of libraries I"ve worked with that do this I liked at first,
but grew to find problematic.

The key problem is that keys in dicts can be anything immutable, while
names have a lot more restrictions on them. And in a case like this, you
can't use a key that happens to be the same as an existing dict attribute
-- at least not in the same way.

In particular, I've struggled with the netCDF4 lib and Colander.

I've used netCDF4 more, so I'll talk about that:

netCDF4 is a Python wrapper around the netcdf scientific data file format.
netcdf has "variables" whiuch hold arrays of data, and attributes (for meta
data).

The netCDF4 python lib wraps a native netcdf4 variable with a python object
that python attributes (names) for each of the netcdf variable attributes.
Pretty nifty, really, you can do things like:

vel = dataset.variables['velocity']

print("velocity is in units of:", vel.units)

kinda cool, but in fact it gets harder to deal with in "real code" as
opposed to quicky scripts than if variables has a dict-like attribute:

print("velocity is in units of:", vel.atts['units'])

Why? because netcdf variables can have arbitrary attributes, so your code
tends to be hard-coded for specific data sets, and breaks fast if the data
files are not compliant.

That's what I mean by the difference between code and data -- the
attributes of a netcdf variable is data -- not code.

Granted, with Python, you can use try: except AttributeError, and setattr,
and all that to work with these attributes as though they are data, but
then you lose all the advantages of having them as attributes anyway. setattr
and the like shulud be used for when metaprogramign is called for - not for
everyday data manipulation.

Oh, and it's also uglier to get/set values in bulk (though the proposed
dict_with_attributes would present both APIs, so not as restrictive.)

You also have problems with keys that mirror actual attributes. So you use
the dict interface to deal with those -- but if you have to choose your
interface according to what the values of the data are -- you've got the
whole, it's not code, it's data! problem again.

Anyway -- those are my $0.02 -- from experience working with such things in
the real world, with real code, and real data

-Chris

-- 

Christopher Barker, Ph.D.
Oceanographer

Emergency Response Division
NOAA/NOS/OR&R(206) 526-6959   voice
7600 Sand Point Way NE   (206) 526-6329   fax
Seattle, WA  98115   (206) 526-6317   main reception

chris.bar...@noaa.gov
___
Python-ideas mailing list
Python-ideas@python.org
https://mail.python.org/mailman/listinfo/python-ideas
Code of Conduct: http://python.org/psf/codeofconduct/


Re: [Python-ideas] Add a dict with the attribute access capability

2017-11-29 Thread Ethan Furman

On 11/29/2017 03:34 PM, Chris Barker wrote:


Am I I the only one that thinks this is a "Bad Idea"?


No, you're not.


For me, it simply confuses even more the question of "is this code or is this 
data?" -- which is a difficult enough
design question in a dynamic language.


As one of those who have created their own version of AttrDict, I can say it's both neat and tricky to use.  I'm happy 
to have it* as a third-party package, but I don't think it belongs in the stdlib.


--
~Ethan~


* attribute-access dicts in general, not mine in particular

___
Python-ideas mailing list
Python-ideas@python.org
https://mail.python.org/mailman/listinfo/python-ideas
Code of Conduct: http://python.org/psf/codeofconduct/


Re: [Python-ideas] Add a dict with the attribute access capability

2017-11-29 Thread Rob Cliffe

On 29/11/2017 23:34, Chris Barker wrote:



On Wed, Nov 29, 2017 at 12:52 AM, Serhiy Storchaka 
mailto:storch...@gmail.com>> wrote:


This is a dict subclass which allows to access items as attributes.

d = plistlib.Dict()
d['a'] = 1
assert d.a == 1
d.b = 2
assert d['b'] == 2

What do you think about reviving this type as general purpose type
in collections or types


Am I I the only one that thinks this is a "Bad Idea"?

For me, it simply confuses even more the question of "is this code or 
is this data?" -- which is a difficult enough design question in a 
dynamic language.


And the couple of libraries I"ve worked with that do this I liked at 
first, but grew to find problematic.



I have also implemented something like this (as a convenience, to hold a 
row from an SQL table).  But it never occurred to me that there should 
be something like it in the stdlib.

Rob Cliffe
___
Python-ideas mailing list
Python-ideas@python.org
https://mail.python.org/mailman/listinfo/python-ideas
Code of Conduct: http://python.org/psf/codeofconduct/


Re: [Python-ideas] Immutable dictionaries

2017-11-29 Thread Rob Cliffe



On 29/11/2017 17:30, Asen Bozhilov wrote:
This is my first post here. I have strong experience with JavaScript 
and I'm lucky that I could move forward to Python.
What I miss in Python are immutable dictionaries. They are especially 
useful for configurations and call functions which expect dictionary 
as argument.  In my opinion they would let a place for underlying 
optimizations.


I'd like to propose also literaling syntax for immutable dictionaries.

immutable_dict = (
    'key1' : 'value1',
    'key2' : 'value2'
)

This syntax is not ambiguous with expression statements and tuple 
literals, but it requires a bit lookahed during the parsing.



This is sort of a subset of an idea I once posted on Python-Ideas: 
Dictionaries, sets and lists (etc. ?) could have a mutable flag, and 
once it was set to False you could neither change it back nor change the 
object.  (OK there might be some backdoor hacks, this is Python.)  This 
would avoid having to explain to beginners "Why does Python have lists 
and tuples?" because instead of a tuple, all you need is an immutable 
list.  (Or if you prefer, instead of a list, all you need is a mutable 
tuple.)

Rob Cliffe
___
Python-ideas mailing list
Python-ideas@python.org
https://mail.python.org/mailman/listinfo/python-ideas
Code of Conduct: http://python.org/psf/codeofconduct/


Re: [Python-ideas] [Python-Dev] What's the status of PEP 505: None-aware operators?

2017-11-29 Thread electronnn
I, too, think that this is too special a case for a dedicated syntax but so
far I prefer:

  x None-or y

The meaning is more clear to me. None-or is like regular or except that y
is evaluated only if x is None.

On Thu, Nov 30, 2017 at 2:35 AM, MRAB  wrote:

> On 2017-11-29 21:27, Greg Ewing wrote:
>
>> Nick Coghlan wrote:
>>
>> What about more English-like syntax:

 X or else Y

>>>
>>> The problem with constructs like this is that they look like they
>>> should mean the same thing as "X or Y".
>>>
>>
>> How about:
>>
>>  x otherwise y
>>
>> It looks different enough from "or" that you're not going
>> to accidentally read it that way when skimming.
>>
>> The meaning is something you'll have to learn if you don't
>> know, but at least it's a word that can be googled for.
>>
>> It has the disadvantage that it's quite long. How about "alt"
> (abbreviation for "alternatively"):
>
> x alt y
>
> ___
> Python-ideas mailing list
> Python-ideas@python.org
> https://mail.python.org/mailman/listinfo/python-ideas
> Code of Conduct: http://python.org/psf/codeofconduct/
>
___
Python-ideas mailing list
Python-ideas@python.org
https://mail.python.org/mailman/listinfo/python-ideas
Code of Conduct: http://python.org/psf/codeofconduct/


Re: [Python-ideas] Add a dict with the attribute access capability

2017-11-29 Thread Steven D'Aprano
On Wed, Nov 29, 2017 at 10:52:51AM +0200, Serhiy Storchaka wrote:

> In 3.7 I have removed an old-deprecated plistlib.Dict. [1] Actually it 
> already was deprecated when the plistlib module was added to the regular 
> stdlib in Python 2.6.
> 
> This is a dict subclass which allows to access items as attributes.


Isn't that a trivial subclass?

class AttrDict(dict):
def __init__(self, *args, **kw):
super().__init__(*args, **kw)
self.__dict__ = self

Possibly apart from a nicer repr, have I missed anything?



> Raymond noticed that that capability seemed nice to have.
> 
> What do you think about reviving this type as general purpose type in 
> collections or types? Perhaps it can be convenient for working with 
> JSON, plists, configuration files, databases and in other cases that 
> need a dict with string keys.

I doubt that it is as convenient as you think. Most of the time I work 
with external data, I don't know the keys in advance, so I couldn't use 
obj.attr syntax. Configuration files (and equivalent) are possibly an 
exception.

But in general I'm suspicious of using attribute access for key lookups. 
I cannot help feeling that, while laziness and hubris are virtues in 
programmers, this is *too* lazy. This conflates two distinct concepts, 
attributes and key/value pairs. Attributes are conceptually part of the 
object, as in dog.tail or car.engine, or data about the object, like 
page.top_margin or engine.capacity. Key/value data is not.

Another way to look at this would be to say that deleting attributes 
is rare and unusual, while deleting keys is generally frequent and 
commonplace.

Its not a completely hard distinction, I acknowledge that its already a 
bit fuzzy, but I'm not sure it is a good idea to make it even fuzzier.

Consequently I'm strongly opposed to making this standard behaviour for 
dict and other mappings, but I'm neutral about making it opt-in for a 
distinct mapping type.



> If reintroduce it, there are open questions.
> 
> 1. The name of the type.

AttrDict seems like the obvious name.


> 2. The location of the type. collections or types? Or other variants?

It is a mapping, which is a collection, so collections.


> 3. How it will collaborate with OrderedDict, defaultdict, etc?

Does it need to?


> 4. Should it be a dict subclass, or a mixin, or a proxy? Or add several 
> types?

Aren't these implementation details?



-- 
Steve
___
Python-ideas mailing list
Python-ideas@python.org
https://mail.python.org/mailman/listinfo/python-ideas
Code of Conduct: http://python.org/psf/codeofconduct/


Re: [Python-ideas] How assignment should work with generators?

2017-11-29 Thread Steven D'Aprano
On Thu, Nov 30, 2017 at 10:49:19AM +1300, Greg Ewing wrote:
> C Anthony Risinger wrote:
> >Is __len__ a viable option now that __length_hint__ has been identified 
> >for hints?
> 
> No, I misremembered that feature, sorry.
> 
> But I still don't like the idea of changing behaviour
> depending on whether the RHS "looks like" an iterator
> or not.

The reason I oppose that is that in all other ways related to iteration, 
iterators are a perfect substitute for any other iterable:

  for x in iterable: pass
  list(iterable)
  function(*iterable)
  a, *b, c = iterable
  a, *b = iterable


all behave identically whether iterable is a list or an iterator. This 
would make the last example, and only that, behave differently depending 
on whether you pass an iterator or some other iterable.



-- 
Steve
___
Python-ideas mailing list
Python-ideas@python.org
https://mail.python.org/mailman/listinfo/python-ideas
Code of Conduct: http://python.org/psf/codeofconduct/


Re: [Python-ideas] How assignment should work with generators?

2017-11-29 Thread Steven D'Aprano
On Thu, Nov 30, 2017 at 11:21:48AM +1300, Greg Ewing wrote:

> It seems that many people think about unpacking rather
> differently from the way I do. I think the difference
> is procedural vs. declarative.
> 
> To my way of thinking, something like
> 
>a, b, c = x
> 
> is a pattern-matching operation. It's declaring that
> x is a sequence of three things, and giving names to
> those things. It's not saying to *do* anything to x.

I hadn't thought of that interpretation before, but now that Greg 
mentions it, its so obvious-in-hindsight that I completely agree with 
it. I think that we should promote this as the "one obvious" 
interpretation.

Obviously as a practical matter, there are some x (namely iterators) 
where you cannot extract items without modifying x, but in all other 
cases I think that the pattern-matching interpretation is superiour.


> With that interpretation,
> 
>a, b, ... = x
> 
> is declaring that x is a sequence of at least two
> items, and giving names to the first two. The ellipsis
> just means that there could be more items, but we
> don't want to give them names.

Indeed.


> On the other hand, some people seem to be interpreting
> the word "unpack" as in "unpack a suitcase", i.e. the
> suitcase is empty afterwards. But unpacking has never
> meant that in Python! If it did, then
> 
>x = [1, 2, 3]
>a, b, c = x
> 
> would leave x == [] afterwards.
>
> The only case where unpacking behaves like that is when
> the rhs is an iterator rather than a sequence, in which
> case a side effect is unavoidable. The question then is
> what the side effect should be.
> 
> I would argue that, since the side effect is something
> that's not really wanted, it should be as *small* as
> possible. By that argument,
> 
>a, b, ... = some_iterator
> 
> should do as *little* as possible to fulfill what's
> being asked, i.e. give names to the first two items
> produced by the rhs. Consuming those two items is
> unavoidable, but there's no need to consume any more.

I'm still in 100% agreement with all of this.


> As for the "extra syntax", we only need it because we've
> defined the existing unpacking syntax to imply verifying
> that the rhs has exactly the same length as the pattern.
> 
> We now want to express patterns which don't impose
> a length constraint, so we need to write them some
> other way.

To be clear, I'm still luke-warm on the need for this, I think islice is 
adequate, but if others believe this is a use-case important enough for 
a syntactic solution, I've come around to making ... my prefered syntax.


-- 
Steve
___
Python-ideas mailing list
Python-ideas@python.org
https://mail.python.org/mailman/listinfo/python-ideas
Code of Conduct: http://python.org/psf/codeofconduct/


Re: [Python-ideas] How assignment should work with generators?

2017-11-29 Thread Steven D'Aprano
On Wed, Nov 29, 2017 at 03:08:43PM -0800, Brendan Barnwell wrote:
> On 2017-11-29 14:21, Greg Ewing wrote:

> >On the other hand, some people seem to be interpreting
> >the word "unpack" as in "unpack a suitcase", i.e. the
> >suitcase is empty afterwards. But unpacking has never
> >meant that in Python! If it did, then
> >
> > x = [1, 2, 3]
> > a, b, c = x
> >
> >would leave x == [] afterwards.
> >
> >The only case where unpacking behaves like that is when
> >the rhs is an iterator rather than a sequence, in which
> >case a side effect is unavoidable. The question then is
> >what the side effect should be.
> 
>   That's an interesting analysis, but I don't think your view is 
>   really the right one.  It *is* unpacking a suitcase, it's just that *if 
> necessary* the suitcase is constructed just in time for you to unpack 
> it.  In other words, the suitcase is not the list [1, 2, 3], but an 
> iterator over this list.


At the point that you are conjuring from thin air an invisible suitcase 
that is an exact clone of the original suitcase, in order to unpack the 
clone without disturbing the original, I think the metaphor is so far 
from the real-world unpacking of suitcases that it no longer applies.

Besides, it's not even correct to say that an invisible suitcase 
(iterator) is constructed.


# Python 3.5
py> dis.dis("a, b, c = [97, 98, x]")
  1   0 LOAD_CONST   0 (97)
  3 LOAD_CONST   1 (98)
  6 LOAD_NAME0 (x)
  9 ROT_THREE
 10 ROT_TWO
 11 STORE_NAME   1 (a)
 14 STORE_NAME   2 (b)
 17 STORE_NAME   3 (c)
 20 LOAD_CONST   2 (None)
 23 RETURN_VALUE



Before iterators existed, Python had sequence unpacking going back to at 
least Python 1.5 if not older, so even if Python used a temporary and 
invisible iterator *now* that has not always been the case and it might 
not be the case in the future or in alternate interpreters.

Even if Python *sometimes* builds a temporary and invisible iterator, it 
doesn't do it all the time, and when it does, it is pure implementation, 
not interface. The interpreter is free to do whatever it likes behind 
the scenes, but there's no iterator involved in the high-level Python 
statement:

a, b, c = [1, 2, 3]

That code involves a list and three assignment targets, that is all.


> This is the same as the behavior for "for" 
> loops: if you do "for item in [1, 2, 3]", the actual thing you're 
> unrolling is an iterator over the list.

No, the actual thing *I* am unrolling is exactly what I write in my 
code, which is the list [1, 2, 3].

I don't care what the Python interpreter iterates over internally, so 
long as the results are the same. It can use an iterator, or unroll the 
loop at compile-time, or turn it into recursion over a linked list for 
all I care.

As much as possible, we should avoid thinking about implementation 
details when trying to understand high-level semantics of Python code. 
Otherwise, our mental models become obsolete when the implementation 
changes.

Or worse, we become incapable of thinking about better implementations 
(or better high-level semantics!) because the current implementation is 
so entwined with our understanding of the high-level semantics of the 
code. If we had allowed the old sequence protocol implementation to take 
priority over the abstract, high-level concept of iteration, we wouldn't 
have iterators today.



-- 
Steve
___
Python-ideas mailing list
Python-ideas@python.org
https://mail.python.org/mailman/listinfo/python-ideas
Code of Conduct: http://python.org/psf/codeofconduct/


Re: [Python-ideas] How assignment should work with generators?

2017-11-29 Thread Brendan Barnwell

On 2017-11-29 20:43, Steven D'Aprano wrote:

At the point that you are conjuring from thin air an invisible suitcase
that is an exact clone of the original suitcase, in order to unpack the
clone without disturbing the original, I think the metaphor is so far
from the real-world unpacking of suitcases that it no longer applies.


	It is not an exact clone of the original suitcase, because the original 
suitcase is a collection with stable contents (i.e., cannot be 
exhausted), but the "clone" (the iterator) CAN be exhausted.  It 
iterates over the same *values*, but that doesn't mean it's the same thing.



Besides, it's not even correct to say that an invisible suitcase
(iterator) is constructed.


# Python 3.5
py> dis.dis("a, b, c = [97, 98, x]")
   1   0 LOAD_CONST   0 (97)
   3 LOAD_CONST   1 (98)
   6 LOAD_NAME0 (x)
   9 ROT_THREE
  10 ROT_TWO
  11 STORE_NAME   1 (a)
  14 STORE_NAME   2 (b)
  17 STORE_NAME   3 (c)
  20 LOAD_CONST   2 (None)
  23 RETURN_VALUE



Before iterators existed, Python had sequence unpacking going back to at
least Python 1.5 if not older, so even if Python used a temporary and
invisible iterator *now* that has not always been the case and it might
not be the case in the future or in alternate interpreters.

Even if Python *sometimes* builds a temporary and invisible iterator, it
doesn't do it all the time, and when it does, it is pure implementation,
not interface. The interpreter is free to do whatever it likes behind
the scenes, but there's no iterator involved in the high-level Python
statement:

 a, b, c = [1, 2, 3]

That code involves a list and three assignment targets, that is all.


	The code only has a list and three assignment targets, but that doesn't 
mean that that's all it "involves".  The expression "a + b" only has two 
variables and a plus sign, but it involves a call to __add__ which is 
not explicitly represented.  Things like this aren't implementation 
details.  Indeed, they're precisely the opposite: they are a high level 
specification of an API for how syntax is converted into semantics.





This is the same as the behavior for "for"
loops: if you do "for item in [1, 2, 3]", the actual thing you're
unrolling is an iterator over the list.


No, the actual thing *I* am unrolling is exactly what I write in my
code, which is the list [1, 2, 3].

I don't care what the Python interpreter iterates over internally, so
long as the results are the same. It can use an iterator, or unroll the
loop at compile-time, or turn it into recursion over a linked list for
all I care.

As much as possible, we should avoid thinking about implementation
details when trying to understand high-level semantics of Python code.
Otherwise, our mental models become obsolete when the implementation
changes.


	Don't you see a bit of irony in arguing based on the compiled bytecode, 
and then saying you don't care about implementation details? :-)  Here 
is a simpler example:


class Foo(object):
def __iter__(self):
print("You tried to call iter on me!")

>>> a, b, c = Foo()
You tried to call iter on me!
Traceback (most recent call last):
  File "", line 1, in 
a, b, c = Foo()
TypeError: iter() returned non-iterator of type 'NoneType'

	You can see that iter() is called, even though "exactly what I wrote in 
the code" is not iter(Foo()) but just Foo().  The "implementation 
detail" is that this function call is concealed within a bytecode called 
"UNPACK_SEQUENCE".  Another implementation detail is that in your 
example that bytecode not used, but that's only because you decompiled 
an expression with a literal list.  If you do "x = [1, 2, 3]" and then 
decompile "a, b, c = x", you will see the UNPACK_SEQUENCE bytecode.


	These details of the bytecode are implementation details.  What is not 
an implementation detail is the iteration protocol, which is exactly the 
kind of high-level semantic thing you're talking about.  The iteration 
protocol says that when you go to iterate over something, iter() is 
called on it, and then next() is called on the result of that call.


	Because of this, I am loath to pretend that whether "a, b, c = x" is 
"like unpacking a suitcase" depends on whether x happens to be a list, 
some other iterable, or some other iterator.  The end result in all 
cases is that the thing that actually doles out the items is an 
iterator.  Sometimes that iterator is connected to a stable base (some 
kind of collection) that can be re-iterated; sometimes it isn't.  But 
that doesn't change the iteration protocol.  The interpreter is not free 
to do what it likes behind the scenes; an implementation that did not 
call __iter__ in the above case would be errroneous.  __iter__ is part 
of the interface of any type that defines it.


--
Brendan Barnwell
"D

Re: [Python-ideas] How assignment should work with generators?

2017-11-29 Thread Greg Ewing

Brendan Barnwell wrote:
That's an interesting analysis, but I don't think your view is 
really the right one.  It *is* unpacking a suitcase, it's just that *if 
necessary* the suitcase is constructed just in time for you to unpack 
it.


I don't think that's right. An iterator created from a sequence
is not a container in its own right, it's something that provides
access to a container. It's not a suitcase, it's a view of the
contents of a suitcase.

If you expect your suitcase to remain unopened, 
it's pretty cold comfort to find that someone has opened it and taken 
only your pants and shoes but left the rest.


So you think it's somehow better if he takes *all* of your
clothes instead?

Here's another way to think about it. If it's acceptable to
exhaust the iterator when only the first few items are
requested, then you're planning to throw the iterator
away afterwards. In that case, what purpose is served by
extracting the rest of the items? Remember, the ellipsis
explicitly says you don't care how many more items there
are.

The only reason I can think of is if you're relying on
side effects performed by the iterator, which is a
pretty obscure way to design code. If the iterator
really must be exhausted for some reason, it would be
better to be explicit about it, e.g.

   a, b, ... = spam_iterator
   for _ in spam_iterator:
  pass # Mustn't leave any spam in the fridge or it will go bad

--
Greg
___
Python-ideas mailing list
Python-ideas@python.org
https://mail.python.org/mailman/listinfo/python-ideas
Code of Conduct: http://python.org/psf/codeofconduct/


Re: [Python-ideas] How assignment should work with generators?

2017-11-29 Thread Steve Barnes


On 28/11/2017 23:15, Alon Snir wrote:
> On Wed, Nov 29, 2017 at 5:46 AM, Alon Snir  wrote:
>> I would like to mention that the issue of assignment to a target list, is 
>> also relevant to the case of elementwise assignment to a mutable sequence 
>> (e.g. lists and arrays). Here as well, the rhs of the assignment statement 
>> states the number of elements to be assigned. Consequently, the following 
>> example will get into infinite loop:
>>
> from itertools import count
> A = []
> A[:] = count()
>>
>> Writing "A[:2] = count()" will cause the same result.
>> Here as well, it is currently safer to use islice if the rhs is a generator 
>> or an iterator. e.g.:
>>
> it = count()
> A[:] = islice(it,2)
>>
>> In my opinion, it is be better to devise a solution that could be applied in 
>> both cases. Maybe a new kind of assignment operator that will be dedicated 
>> to this kind of assignment. i.e. elementwise assignment with restriction on 
>> the number of elements to be assigned, based on the length of the lhs object 
>> (or the number of targets in the target list).
>>
> 
> ChrisA wrote:
> Hmm. The trouble is that slice assignment doesn't have a fixed number of 
> targets. If you say "x, y = spam", there's a clear indication that 'spam' 
> needs to provide exactly two values; but "A[:] = spam" could have any number 
> of values, and it'll expand or shrink the list accordingly.
> 
> Rhodri James wrote:
> Flatly, no.  It is better not to ask for things you don't want in the first 
> place, in this case the infinite sequence.
> Still, don't let me discourage you from working on this.  If you can define 
> how such an assignment would work, or even the length of A[:] as an 
> assignment target, I'm not going to dismiss it out of hand.
> 
> 
> My answer:
> 
> The idea is to define an alternative assignment rule, that is to assign 
> exactly as many elements as the current length of the lhs object (without 
> expanding or shrinking it). Suppose "?=" is the operator for the alternative 
> assignment rule; A=[None]*2; and "iterator" is any iterator (finite or 
> infinite). In this case, the following code:
> 
 A ?= iterator
> 
> would behave like this:
> 
 A[:] = islice(iterator, 2)  # where 2 is the length of A
> 
> And as suggested earlier for the case of assignment to a target list, the 
> following code:
> 
 x, y ?= iterator
> 
> would behave like this:
> 
 x, y = islice(iterator, 2)  # where 2 is the number of targets
> 
> Regarding the length issue:
> Is there any difficulty in finding the length of a sliced sequence? After 
> all, the range object has a len method. Therefore, the length of A[s] (where 
> s is a slice object) could be evaluated as follows:
> 
 len(range(*s.indices(len(A

Just a thought but what about a syntax something along the lines of:

a, b, *remainder = iterable

Where remainder becomes the iterable with the first two values consumed 
by assigning to a & b. If the iterator has less than 2 values, (in the 
above case), remaining it should error, if it has exactly 2 then 
remainder would become an exhausted iterable. Of course the user could 
also use:

a, b, *iterable = iterable

Others may differ but this syntax has a lot of similarity to the f(a, b, 
*args) syntax, possibly enough that most users could understand it.



-- 
Steve (Gadget) Barnes
Any opinions in this message are my personal opinions and do not reflect 
those of my employer.

---
This email has been checked for viruses by AVG.
http://www.avg.com

___
Python-ideas mailing list
Python-ideas@python.org
https://mail.python.org/mailman/listinfo/python-ideas
Code of Conduct: http://python.org/psf/codeofconduct/