[Python-ideas] Re: Ability to set precedence of classdict (returned from __prepare__) for a metaclass type

2019-10-21 Thread Steve Jorgensen
Andrew Barnert wrote:
> On Oct 20, 2019, at 03:36, Steve Jorgensen ste...@stevej.name wrote:

> And there are multiple PyPI projects that build Django choices on top of 
> Enum, which
> show that the only thing you need is to override __getitem__ to replace its 
> mapping
> behavior with sequence behavior. I believe this was also one of the examples 
> of what you
> can build for yourself on top of EnumMeta in Nick Coghlan’s blog post 
> explaining the
> design of enum.
> Maybe the additional functionality in Enum gets in your way for some reason I 
> don’t
> understand, that doesn’t affect other people who want Django choices. But 
> otherwise, I
> don’t see how it really is any different.
> And again, none of this different-from-Enum behavior is relevant to your 
> problem
> anyway. The fact that you think it is, and think it can’t be done with Enum, 
> makes it
> harder to understand where the actual problem is. Maybe you’re not just 
> trying to do the
> same magic that all the autoenum/simplenum/etc. packages on PyPI and the PoC 
> code from the
> PEP and the section in Nick’s blog post all do (in a couple different ways), 
> or maybe it’s
> insufficiently magic for your purposes, but without knowing how and why it’s 
> different or
> insufficient it’s impossible to know whether there’s an actual limitation to 
> fix in
> Python, or just a problem in your design or implementation that could be 
> easily fixed to
> work in existing Python.

So… You're exactly right. I just had a very limited understanding of what enum 
was about and had not dug into it deeply enough to find out how flexible it 
really is.

Here's an implementation that I came up with in a short hacking session using 
enum.

Tests:

from choices import ChoiceEnum, Label as L


def test_creates_auto_valued_auto_labeled_choices():
class Food(ChoiceEnum):
APPLE = ()
ICED_TEA = ()

assert tuple(tuple(fc) for fc in Food) == (
('APPLE', 'Apple'),
('ICED_TEA', 'Iced Tea'),
)


def test_creates_auto_labeled_choices_with_given_values():
class Food(ChoiceEnum):
APPLE = 1
ICED_TEA = 2

assert tuple(tuple(fc) for fc in Food) == (
(1, 'Apple'),
(2, 'Iced Tea'),
)


def test_creates_choices_with_given_values_and_labels():
class Food(ChoiceEnum):
CHICKEN_MCNUGGETS = (1, 'Chicken McNuggets')
CHICKEN_PROVENCAL = (2, 'Chicken Provençal')

assert tuple(tuple(fc) for fc in Food) == (
(1, 'Chicken McNuggets'),
(2, 'Chicken Provençal'),
)


def test_creates_auto_valued_choices_with_given_values():
class Food(ChoiceEnum):
CHX_MN = L('Chicken McNuggets')
CHX_PV = L('Chicken Provençal')

assert tuple(tuple(fc) for fc in Food) == (
('CHX_MN', 'Chicken McNuggets'),
('CHX_PV', 'Chicken Provençal'),
)

Implementation:

from enum import Enum


class ChoiceEnum(Enum):
def __init__(self, src=None, label=None):
super().__init__()

if isinstance(src, Label):
value = None
label = str(src)
else:
value = src

self._value_ = self.name if value is None else value
self.label = label or _label_from_name(self.name)

def __getitem__(self, idx):
if idx == 0:
return self.value
elif idx == 1:
return self.label
else:
raise IndexError('Index value must be 0 or 1')

def __len__(self):
return 2


class Label(str):
pass


def _label_from_name(name):
return name.replace('_', ' ').title()
___
Python-ideas mailing list -- python-ideas@python.org
To unsubscribe send an email to python-ideas-le...@python.org
https://mail.python.org/mailman3/lists/python-ideas.python.org/
Message archived at 
https://mail.python.org/archives/list/python-ideas@python.org/message/SPSAC7RF2W5IYZ2F45MIAUHSWJMXGAQ5/
Code of Conduct: http://python.org/psf/codeofconduct/


[Python-ideas] Re: PEP 584: Add + and += operators to the built-in dict class.

2019-10-21 Thread Richard Musil
On Tue, Oct 22, 2019 at 12:05 AM Jan Greis  wrote:

> On 21/10/2019 21:14, Dominik Vilsmeier wrote:
> > Exactly, so the dict "+" behavior would match the set "|" behavior,
> preserving the keys. But how many users will be concerned about whether the
> keys are going to be preserved? I guess almost everybody will want to know
> what happens with the values, and that question remains unanswered by just
> looking at the "+" or "|" syntax. It's reasonable to assume that values are
> preserved as well, i.e. `d1 + d2` adds the missing keys from `d2` to `d1`.
> Of course, once you know that "+" is actually similar to "update" you can
> infer that the last value wins.
>
> There's one reason for + which I feel is being missed (though I think
> someone may have briefly mentioned it last time this topic was brought
> up): If we look at the behaviour of dict literals, adding two dicts
> actually behaves like concatenation in the sense that
>
> {"key1": "val1", "key2": "val2", "key1": "val3"} == {"key1": "val3",
> "key2": "val2"}
>
> which is exactly what we would get by adding {"key1": "val1", "key2":
> "val2"} and {"key1": "val3"}
>

It is not a "concatenation" though, because you lost {"key1": "val1"} in
the process. The concatenation is not _just_ "writing something after
something", you can do it with anything, but the actual operation,
producing the result.

Richard

>
> so using + we would actually have
>
> {"key1": "val1", "key2": "val2"} + {"key1": "val3"} ==  {"key1": "val1",
> "key2": "val2", "key1": "val3"}
> ___
> Python-ideas mailing list -- python-ideas@python.org
> To unsubscribe send an email to python-ideas-le...@python.org
> https://mail.python.org/mailman3/lists/python-ideas.python.org/
> Message archived at
> https://mail.python.org/archives/list/python-ideas@python.org/message/IRU66KNSTIG2FYE2KCGTCZHWYT22HC44/
> Code of Conduct: http://python.org/psf/codeofconduct/
>
___
Python-ideas mailing list -- python-ideas@python.org
To unsubscribe send an email to python-ideas-le...@python.org
https://mail.python.org/mailman3/lists/python-ideas.python.org/
Message archived at 
https://mail.python.org/archives/list/python-ideas@python.org/message/DSPL3DQXUYIDWR3QCOE7FFMPHDXMGTNI/
Code of Conduct: http://python.org/psf/codeofconduct/


[Python-ideas] Re: Extending @ syntax to allow expressions

2019-10-21 Thread Cameron Simpson

On 21Oct2019 20:41, Andrew Barnert  wrote:

On Oct 21, 2019, at 19:53, Cameron Simpson  wrote:

On 21Oct2019 17:18, Yonatan Zunger  wrote:
I came across a case which *might* be a use case for a syntax extension, but 
I'm not sure. Wanted to get feedback from the group.

*The extension: *Extend the decorator syntax from
decorator ::=  "@" dotted_name ["(" [argument_list [","]] ")"] NEWLINE

to
decorator ::= "@" expression NEWLINE

where the expression must return a callable that accepts a function of the
indicated signature as its argument.

[...]
Personally, I have 2 concerns. 1: this introduces a lot of scope for 
arbitrary complexity after the @ versus the extremely readable 
"name(...)" form.


This seems like a consenting-adults thing. Any flexible syntax can be abused to 
write unreadable code, but unless there’s a good reason to suspect it will be 
abused often (and/or won’t be used helpfully very often) that’s not much of an 
argument against it. I don’t think many people would write horrible arbitrary 
decorator expressions, except for the kind of people who already do horrible 
unpythonic things like writing a ten-line function as a lambda just to assign 
it to a variable anyway.


Maybe so. I still have personal reluctance to open such a door without a 
good reason.



2: I'm not sure what this would to to uses of "@" as an operator, as has been 
suggested various times for various laudable reasons; remember that an @decorator or 
other function definition is just another statement, and arbitrary expressions are 
already statements.


I don’t understand this. @ already exists as an operator, and already takes 
arbitrary expressions for the left and right operands, with no parser 
ambiguity. What future worthwhile suggestions to that existing syntax are you 
imagining that might break that?


None. I've not thought it through other than that suddenly arbitrary 
expressions can occur here where before they could not.


Even if you’re imagining that people might want @ to be a unary prefix 
operator as well as a binary operator (like + and -), how does 
restricting decorator syntax help ambiguity there? Surely you’d want 
the @ operator to be able to take a dotted-name operand.


I guess so. My concerns here are looking specious.

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


[Python-ideas] Re: Ability to set precedence of classdict (returned from __prepare__) for a metaclass type

2019-10-21 Thread Steve Jorgensen
Andrew Barnert wrote:
> On Oct 20, 2019, at 03:36, Steve Jorgensen ste...@stevej.name wrote:
> Maybe the additional functionality in Enum gets in your way for some reason I 
> don’t
> understand, that doesn’t affect other people who want Django choices. But 
> otherwise, I
> don’t see how it really is any different.
> And again, none of this different-from-Enum behavior is relevant to your 
> problem
> anyway. The fact that you think it is, and think it can’t be done with Enum, 
> makes it
> harder to understand where the actual problem is. Maybe you’re not just 
> trying to do the
> same magic that all the autoenum/simplenum/etc. packages on PyPI and the PoC 
> code from the
> PEP and the section in Nick’s blog post all do (in a couple different ways), 
> or maybe it’s
> insufficiently magic for your purposes, but without knowing how and why it’s 
> different or
> insufficient it’s impossible to know whether there’s an actual limitation to 
> fix in
> Python, or just a problem in your design or implementation that could be 
> easily fixed to
> work in existing Python.

I had obviously had only skimmed the info on `Enum`. I was not really aware of 
it before it was mentioned in reply to my request. I have probably just 
misunderstood what enum does or does not do and should dig into it some more. I 
will do that next.
___
Python-ideas mailing list -- python-ideas@python.org
To unsubscribe send an email to python-ideas-le...@python.org
https://mail.python.org/mailman3/lists/python-ideas.python.org/
Message archived at 
https://mail.python.org/archives/list/python-ideas@python.org/message/BPG6KSFN2IZUTST7WLP2K6KJ4DZQ6LEM/
Code of Conduct: http://python.org/psf/codeofconduct/


[Python-ideas] Re: Extending @ syntax to allow expressions

2019-10-21 Thread Steve Jorgensen
Steve Jorgensen wrote:
> had not thought of that. That actually does work. :)
> I would say that means there is no need for a new feature, but would it make 
> sense for
> this idiom to be documented in a PEP or some other easily discoverable place?

Sorry. I forgot to quote for context.

Random832 wrote:
> On Mon, Oct 21, 2019, at 22:30, Random832 wrote:
> > On Mon, Oct 21, 2019, at 22:00, Steve Jorgensen
> > wrote:
> > I think some idea like this might be worth
> > proposing. the first idea 
> > that comes to my mind is to allow the name of a decorator to be an 
> > fstring using @'...' or @"..." syntax.
> > If, for example, you have method_type = 'class', then you could 
> > decorate a method using @'{method_type}method'.
> > I'm not sure if this is a very good example (there's no "normalmethod" 
> > to return no decorator, and staticmethod typically needs a different 
> > function signature with no self/cls)... and for any nontrivial case I 
> > can imagine, it's taken care of by the ability to call a function. For 
> > example, for your case you can simply
> > def m(method_type):
> > if method_type == 'static': return staticmethod
> > elif method_type == 'class': return classmethod
> > elif method_type == 'normal': return lambda f: f
> > else:  # do what here? are you extending with additional 
> > "foomethod" decorators?
> > and then do @m(method_type).
> > Sorry, when posting this, I hadn't seen Yonatan Zunger's original post yet, 
> > only
> this reply. I do see the utility for that suggestion, but not really for this 
> one allowing
> a decorator to be a string that will be evaluated. [and if you really want 
> yours
> literally, you could simply do @eval(f'{method_type}method'), or something 
> else in case
> method_type may contain characters that are not part of an identifier.
___
Python-ideas mailing list -- python-ideas@python.org
To unsubscribe send an email to python-ideas-le...@python.org
https://mail.python.org/mailman3/lists/python-ideas.python.org/
Message archived at 
https://mail.python.org/archives/list/python-ideas@python.org/message/7F23UO4UGPJFUA47SM5PEZH7BIWYLRCA/
Code of Conduct: http://python.org/psf/codeofconduct/


[Python-ideas] Re: Extending @ syntax to allow expressions

2019-10-21 Thread Steve Jorgensen
had not thought of that. That actually does work. :)

I would say that means there is no need for a new feature, but would it make 
sense for this idiom to be documented in a PEP or some other easily 
discoverable place?
___
Python-ideas mailing list -- python-ideas@python.org
To unsubscribe send an email to python-ideas-le...@python.org
https://mail.python.org/mailman3/lists/python-ideas.python.org/
Message archived at 
https://mail.python.org/archives/list/python-ideas@python.org/message/UXNSPY5DSPTJK2RLTSBFH42CCRTRLLEI/
Code of Conduct: http://python.org/psf/codeofconduct/


[Python-ideas] Re: Extending @ syntax to allow expressions

2019-10-21 Thread Cameron Simpson

On 21Oct2019 17:18, Yonatan Zunger  wrote:
I came across a case which *might* be a use case for a syntax 
extension, but I'm not sure. Wanted to get feedback from the group.


*The extension: *Extend the decorator syntax from

decorator ::=  "@" dotted_name ["(" [argument_list [","]] ")"] NEWLINE

to

decorator ::= "@" expression NEWLINE

where the expression must return a callable that accepts a function of the
indicated signature as its argument.


Personally, I have 2 concerns. 1: this introduces a lot of scope for 
arbitrary complexity after the @ versus the extremely readable 
"name(...)" form. 2: I'm not sure what this would to to uses of "@" as 
an operator, as has been suggested various times for various laudable 
reasons; remember that an @decorator or other function definition is 
just another statement, and arbitrary expressions are already 
statements.


*The motivating case: *I'm using function decorators to define cron 
jobs in

my system, with the rather nice syntax "@cronJob(parameters) def
myFunction(standard args)". The decorator registers the function, this
causes all sorts of magic to occur, and out the other end of the pipe jobs
run in production. It's working very nicely. However, we'd like to improve
the syntax to allow different cron configurations for the job in different
production environments. Since the default-plus-overrides model is natural
for the actual use cases, a nice way to do this would be to replace the
cronJob function with a class whose __init__ and __call__ methods
respectively load up the parameters and do the actual work of registration,
but which also has an override() method that lets you specify
per-environment overrides and then returns self. This would allow a syntax
like:

@CronJob('job-name', params...).override('dev', more-params...)
def myFunction(...)

However, this is invalid syntax in Python 3.8 because you can't have a
general expression in a decorator statement. Instead, the nearest option is

myJob = CronJob('job-name', params...).override('dev', more-params...)
@myJob
def myFunction(...)

Which is uglier for no obvious benefit.


Maybe a better form, already supported, might be this:

   @CronJob('job-name', params...)
   @cron_override('dev', more-params...)
   def the_function...

i.e. decorate the decorated function. I would choose to write it like 
the above, even though the decorators run from inside to out, amounting 
to having @cron_override prepare an environment specific decoration and 
@CronJob just be the "default for an otherwise unspecified environment" 
decoration.


No new syntax needed. And it reads nicely, at least to my eye.

You will probably run into some resistance if there's no case for your 
syntax which can't be addressed with the nested decoration above (or 
something equivalent - the point here isn't that what I've written above 
is a great thing (though I like it) but that it requires no new syntax).


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


[Python-ideas] Re: Extending @ syntax to allow expressions

2019-10-21 Thread Jonathan Goble
On Mon, Oct 21, 2019 at 8:21 PM Yonatan Zunger  wrote:
>
> Hey everyone,
>
> I came across a case which might be a use case for a syntax extension, but 
> I'm not sure. Wanted to get feedback from the group.

[...]

> @CronJob('job-name', params...).override('dev', more-params...)
> def myFunction(...)

Could you modify the signature of CronJob's __init__ method to accept
override parameters as a dict or list in a keyword argument? Then this
example would look something like this:

@CronJob('job-name', params..., dev=more-params...)
def myFunction(...)

Internally, you could even keep the .override() method and have
__init__ call that method to do the work. The signature of __init__
could then either include an explicit keyword argument (defaulting to
None) for each environment you need to account for, or if there are
too many, a **kwargs catch-all from which you extract what you need.
___
Python-ideas mailing list -- python-ideas@python.org
To unsubscribe send an email to python-ideas-le...@python.org
https://mail.python.org/mailman3/lists/python-ideas.python.org/
Message archived at 
https://mail.python.org/archives/list/python-ideas@python.org/message/RMFG43ZU2GAYWRSAS45VRU4QOZUJI257/
Code of Conduct: http://python.org/psf/codeofconduct/


[Python-ideas] Re: Extending @ syntax to allow expressions

2019-10-21 Thread Random832
On Mon, Oct 21, 2019, at 22:30, Random832 wrote:
> On Mon, Oct 21, 2019, at 22:00, Steve Jorgensen wrote:
> > I think some idea like this might be worth proposing. the first idea 
> > that comes to my mind is to allow the name of a decorator to be an 
> > fstring using `@'...'` or `@"..."` syntax.
> > 
> > If, for example, you have `method_type = 'class'`, then you could 
> > decorate a method using `@'{method_type}method'`.
> 
> I'm not sure if this is a very good example (there's no "normalmethod" 
> to return no decorator, and staticmethod typically needs a different 
> function signature with no self/cls)... and for any nontrivial case I 
> can imagine, it's taken care of by the ability to call a function. For 
> example, for your case you can simply
> 
> def m(method_type):
> if method_type == 'static': return staticmethod
> elif method_type == 'class': return classmethod
> elif method_type == 'normal': return lambda f: f
> else:  # do what here? are you extending with additional 
> "foomethod" decorators?
> 
> and then do @m(method_type).

Sorry, when posting this, I hadn't seen Yonatan Zunger's original post yet, 
only this reply. I do see the utility for that suggestion, but not really for 
this one allowing a decorator to be a string that will be evaluated. [and if 
you *really* want yours literally, you could simply do 
@eval(f'{method_type}method'), or something else in case method_type may 
contain characters that are not part of an identifier.
___
Python-ideas mailing list -- python-ideas@python.org
To unsubscribe send an email to python-ideas-le...@python.org
https://mail.python.org/mailman3/lists/python-ideas.python.org/
Message archived at 
https://mail.python.org/archives/list/python-ideas@python.org/message/PSD2KJ5NJMIKNWL6M3KJV3GH5C3R74BE/
Code of Conduct: http://python.org/psf/codeofconduct/


[Python-ideas] Re: Extending @ syntax to allow expressions

2019-10-21 Thread Random832
On Mon, Oct 21, 2019, at 22:00, Steve Jorgensen wrote:
> I think some idea like this might be worth proposing. the first idea 
> that comes to my mind is to allow the name of a decorator to be an 
> fstring using `@'...'` or `@"..."` syntax.
> 
> If, for example, you have `method_type = 'class'`, then you could 
> decorate a method using `@'{method_type}method'`.

I'm not sure if this is a very good example (there's no "normalmethod" to 
return no decorator, and staticmethod typically needs a different function 
signature with no self/cls)... and for any nontrivial case I can imagine, it's 
taken care of by the ability to call a function. For example, for your case you 
can simply

def m(method_type):
if method_type == 'static': return staticmethod
elif method_type == 'class': return classmethod
elif method_type == 'normal': return lambda f: f
else:  # do what here? are you extending with additional "foomethod" 
decorators?

and then do @m(method_type).
___
Python-ideas mailing list -- python-ideas@python.org
To unsubscribe send an email to python-ideas-le...@python.org
https://mail.python.org/mailman3/lists/python-ideas.python.org/
Message archived at 
https://mail.python.org/archives/list/python-ideas@python.org/message/PYLVZTNDQAV5WIV4W3OFFAIUMH3EDJFU/
Code of Conduct: http://python.org/psf/codeofconduct/


[Python-ideas] Re: Extending @ syntax to allow expressions

2019-10-21 Thread Steve Jorgensen
I think some idea like this might be worth proposing. the first idea that comes 
to my mind is to allow the name of a decorator to be an fstring using `@'...'` 
or `@"..."` syntax.

If, for example, you have `method_type = 'class'`, then you could decorate a 
method using `@'{method_type}method'`.
___
Python-ideas mailing list -- python-ideas@python.org
To unsubscribe send an email to python-ideas-le...@python.org
https://mail.python.org/mailman3/lists/python-ideas.python.org/
Message archived at 
https://mail.python.org/archives/list/python-ideas@python.org/message/SL5ZKSQU6IOCOUY5SWJ6GGG7JKRY5B5U/
Code of Conduct: http://python.org/psf/codeofconduct/


[Python-ideas] Re: Copying a multiple values of a dict to another with a lot easier syntax

2019-10-21 Thread Bar Harel
I believe you made a mess.

For all attribute getting needs, I think operator.attrgetter should
suffice. No need to implement it yourself.

For attribute setting needs, maybe we can add an equivalent
operator.attrsetter. I can see myself using it from time to time.

Easy solution, solves the problem, makes sense, we can even implement an
itemsetter much like itemgetter for completeness, as the implementation
will probably be easy and well understood.

What do you say?

-- Bar Harel

On Tue, Oct 22, 2019, 3:25 AM Kyle Lahnakoski 
wrote:

>
> On 2019-10-21 10:44, gedizgu...@gmail.com wrote:
> > m and n are lists or dicts or enumerates or classes or anything it can
> be assigned like following:
> >
> > instead of :
> >
> > m.a=n.a;
> > m.b=n.b;
> > m.c=n.c;
> > ...
> >
> > I suggest:
> >
> > a,b,c of m to n ;
>
> Interesting.  I also saw this type of redundancy in my code. Instead of
> making a function, like `copy_attrs()` I changed my APIs to accept
> over-specified attributes.  Instead, I would write
>
> m = n
>
> ... or simply use `n` where `m` was expected.  Yes, `n` would have more
> attributes than needed, but that is solved by ensuring the receiver can
> gracefully reject the extra attributes; I decorate pedantic functions
> that complain about extra parameters.
>
> In your other example, I would write:
>
> adiv=document.createElement("div")
> adiv.style = comp
>
> There is the problem of unfortunate namespace overlap; where the
> destination expects some attribute X and the source has an attribute of
> the same name, X,  but the value is wrong.  But this is not a large
> problem: You can plan your attribute names on a program-wide scale so
> that the same attribute name means the same thing across your whole
> program, and different attribute names mean different things across your
> whole program.  This does not require too much forward planning, rather
> more refactoring as you rename parameters to match, or differ, as
> needed.  This is what the ES6 structuring/destructuring is  promoting.
> Consider a function that uses `adiv`:
>
> drawBox = (adiv) => {
>  const {x, y, height, width} = adiv.style;
> }
>
> the extra attributes of `comp` are ignored; specific attribute copying
> is not required.
>
>
> ___
> Python-ideas mailing list -- python-ideas@python.org
> To unsubscribe send an email to python-ideas-le...@python.org
> https://mail.python.org/mailman3/lists/python-ideas.python.org/
> Message archived at
> https://mail.python.org/archives/list/python-ideas@python.org/message/FY24FAGNQAGTA5CRZCI2WWEGF5RQPPPD/
> Code of Conduct: http://python.org/psf/codeofconduct/
>
___
Python-ideas mailing list -- python-ideas@python.org
To unsubscribe send an email to python-ideas-le...@python.org
https://mail.python.org/mailman3/lists/python-ideas.python.org/
Message archived at 
https://mail.python.org/archives/list/python-ideas@python.org/message/CG2F7P3VAJOFQMU3SD6FSQYXOSYTZI5B/
Code of Conduct: http://python.org/psf/codeofconduct/


[Python-ideas] Re: PEP 584: Add + and += operators to the built-in dict class.

2019-10-21 Thread Steven D'Aprano
On Tue, Oct 22, 2019 at 12:03:02AM +0200, Jan Greis wrote:

> There's one reason for + which I feel is being missed (though I think 
> someone may have briefly mentioned it last time this topic was brought 
> up): If we look at the behaviour of dict literals, adding two dicts 
> actually behaves like concatenation in the sense that
> 
> {"key1": "val1", "key2": "val2", "key1": "val3"} == {"key1": "val3", 
> "key2": "val2"}

That's in the PEP.

https://www.python.org/dev/peps/pep-0584/#id26


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


[Python-ideas] Re: Copying a multiple values of a dict to another with a lot easier syntax

2019-10-21 Thread Kyle Lahnakoski


On 2019-10-21 10:44, gedizgu...@gmail.com wrote:

m and n are lists or dicts or enumerates or classes or anything it can be 
assigned like following:

instead of :

m.a=n.a;
m.b=n.b;
m.c=n.c;
...

I suggest:

a,b,c of m to n ;


Interesting.  I also saw this type of redundancy in my code. Instead of 
making a function, like `copy_attrs()` I changed my APIs to accept 
over-specified attributes.  Instead, I would write


m = n

... or simply use `n` where `m` was expected.  Yes, `n` would have more 
attributes than needed, but that is solved by ensuring the receiver can 
gracefully reject the extra attributes; I decorate pedantic functions 
that complain about extra parameters.


In your other example, I would write:

adiv=document.createElement("div")
adiv.style = comp

There is the problem of unfortunate namespace overlap; where the 
destination expects some attribute X and the source has an attribute of 
the same name, X,  but the value is wrong.  But this is not a large 
problem: You can plan your attribute names on a program-wide scale so 
that the same attribute name means the same thing across your whole 
program, and different attribute names mean different things across your 
whole program.  This does not require too much forward planning, rather 
more refactoring as you rename parameters to match, or differ, as 
needed.  This is what the ES6 structuring/destructuring is  promoting. 
Consider a function that uses `adiv`:


drawBox = (adiv) => {
    const {x, y, height, width} = adiv.style;
}

the extra attributes of `comp` are ignored; specific attribute copying 
is not required.



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


[Python-ideas] Extending @ syntax to allow expressions

2019-10-21 Thread Yonatan Zunger
Hey everyone,

I came across a case which *might* be a use case for a syntax extension,
but I'm not sure. Wanted to get feedback from the group.

*The extension: *Extend the decorator syntax from

decorator ::=  "@" dotted_name ["(" [argument_list [","]] ")"] NEWLINE

to

decorator ::= "@" expression NEWLINE

where the expression must return a callable that accepts a function of the
indicated signature as its argument.

*The motivating case: *I'm using function decorators to define cron jobs in
my system, with the rather nice syntax "@cronJob(parameters) def
myFunction(standard args)". The decorator registers the function, this
causes all sorts of magic to occur, and out the other end of the pipe jobs
run in production. It's working very nicely. However, we'd like to improve
the syntax to allow different cron configurations for the job in different
production environments. Since the default-plus-overrides model is natural
for the actual use cases, a nice way to do this would be to replace the
cronJob function with a class whose __init__ and __call__ methods
respectively load up the parameters and do the actual work of registration,
but which also has an override() method that lets you specify
per-environment overrides and then returns self. This would allow a syntax
like:

@CronJob('job-name', params...).override('dev', more-params...)
def myFunction(...)

However, this is invalid syntax in Python 3.8 because you can't have a
general expression in a decorator statement. Instead, the nearest option is

myJob = CronJob('job-name', params...).override('dev', more-params...)
@myJob
def myFunction(...)

Which is uglier for no obvious benefit.

*Possible pros and cons: *

This extends the existing syntax in a way that's very intuitive w.r.t. the
current one -- the docs say "A function definition may be wrapped by one or
more decorator expressions. Decorator expressions are evaluated when the
function is defined, in the scope that contains the function definition.
The result must be a callable, which is invoked with the function object as
the only argument. The returned value is bound to the function name instead
of the function object. Multiple decorators are applied in nested fashion."
It's not obvious from the syntax why the decorator expression *needs* to
have this limited form.

It increases consistency, by eliminating this one unusual use of dotted
expressions as special relative to other expressions. (NB this is the only
call to ast_for_dotted_expr in ast.c!)

The meaning of the operation remains unambiguous, and is just as accessible
to tools like linters, type checkers, and syntax highlighters, as the @
operator simply modifies the succeeding expression.

On the downside, it's more flexible, and so offers more chances for a user
to shoot themselves in the foot.

It's somewhat of a corner case, so it's not obvious that the syntax
extension is worth it.


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


[Python-ideas] Re: PEP 584: Add + and += operators to the built-in dict class.

2019-10-21 Thread Brandt Bucher
Meitham Jamaa wrote:
> The fact dict is a mutable object makes this PEP very complicated.
> Let's say we have this example:
> x = {'a': 1, 'b': 2, 'c': {'c': 3}}
>   y = {'d': 4, 'c': {'c': 5}}
> If we were to merge the two dicts together, such as:
> x.update(y)
> Then we expect y to have been updated and look like:
> {'a': 1, 'b': 2, 'c': {'c': 5}, 'd': 4}
> x['c'] is now the same object of y['c'] and any updates
> to
> either is reflected on the other.

I really don't see how this is any different than list concatenation with 
+/+=...

x = [1, 2]
y = [{'c': 3}]
x += y

x[-1] and y[-1] now refer to the same object, and any updates in one will be 
reflected in the other. It would be surprising if they didn't!
___
Python-ideas mailing list -- python-ideas@python.org
To unsubscribe send an email to python-ideas-le...@python.org
https://mail.python.org/mailman3/lists/python-ideas.python.org/
Message archived at 
https://mail.python.org/archives/list/python-ideas@python.org/message/C4ZUYX75I3D43IZQYBGDTKTLGTHPI4K4/
Code of Conduct: http://python.org/psf/codeofconduct/


[Python-ideas] Re: PEP 584: Add + and += operators to the built-in dict class.

2019-10-21 Thread Meitham Jamaa
The fact ``dict`` is a mutable object makes this PEP very complicated.  





Let's say we have this example: 





  x = {'a': 1, 'b': 2, 'c': {'c': 3}}   


  y = {'d': 4, 'c': {'c': 5}}   





If we were to merge the two dicts together, such as:





  x.update(y)   





Then we expect ``y`` to have been updated and look like:





  {'a': 1, 'b': 2, 'c': {'c': 5}, 'd': 4}   





``x['c']`` is now the same object of ``y['c']`` and any updates to  


either is reflected on the other.   





Now if we have ``z = x + y``.  Should ``z`` be a new shallow copy?  Deep


copy?  Or completely new dict with no references to neither ``x`` or


``y``?  





If we limit the merge operator to ``inplace`` update, then we could have


two options, ``update`` and ``deepupdate``.   

[Python-ideas] Re: PEP 584: Add + and += operators to the built-in dict class.

2019-10-21 Thread Jan Greis

On 21/10/2019 21:14, Dominik Vilsmeier wrote:

Exactly, so the dict "+" behavior would match the set "|" behavior, preserving the keys. But how many users will be 
concerned about whether the keys are going to be preserved? I guess almost everybody will want to know what happens with the values, and 
that question remains unanswered by just looking at the "+" or "|" syntax. It's reasonable to assume that values are 
preserved as well, i.e. `d1 + d2` adds the missing keys from `d2` to `d1`. Of course, once you know that "+" is actually similar 
to "update" you can infer that the last value wins.


There's one reason for + which I feel is being missed (though I think 
someone may have briefly mentioned it last time this topic was brought 
up): If we look at the behaviour of dict literals, adding two dicts 
actually behaves like concatenation in the sense that


{"key1": "val1", "key2": "val2", "key1": "val3"} == {"key1": "val3", 
"key2": "val2"}


which is exactly what we would get by adding {"key1": "val1", "key2": 
"val2"} and {"key1": "val3"}


so using + we would actually have

{"key1": "val1", "key2": "val2"} + {"key1": "val3"} ==  {"key1": "val1", 
"key2": "val2", "key1": "val3"}

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


[Python-ideas] Re: PEP 584: Add + and += operators to the built-in dict class.

2019-10-21 Thread Dominik Vilsmeier
Steven D'Aprano wrote:
> On Sat, Oct 19, 2019 at 02:02:43PM -0400, David Mertz wrote:
> > The plus operation on two dictionaries feels far more
> > natural as a
> > vectorised merge, were it to mean anything.  E.g., I'd expect
> > {'a': 5, 'b': 4} + {'a': 3, 'b': 1}
> > {'a': 8, 'b': 5}
> > Outside of Counter when would this behaviour be useful?

For example one could use dicts to represent data tables, with the keys being 
either indices or column names and the values being lists (rows or columns). 
Then for joining two such tables it would be desirable if values are added, 
because then you could simply do `joint_table = table1 + table2`.

Or having a list of records from different sources:

purchases_online = {'item1': [datetime1, datetime2, ...], 'item2': ...}
purchases_store = {'item1': [datetime3, datetime4, ...], ...}
purchases_overall = purchases_online + purchases_store  # Records should be 
concatenated.
# Then doing some analysis on the overall purchases.

`pandas.Series` also behaves dict-like (almost) and does add the values on "+".

> I expect that this feels natural to you because you're thinking about 
> simple (dare I say "toy"?) examples like the above, rather than 
> practical use-cases like "merging multiple preferences":
> prefs = defaults + system_prefs + user_prefs
> 
> # or if you prefer the alternative syntax
> prefs = defaults | system_prefs | user_prefs
> 
> (Note that in this case, the lack of commutativity is a good thing: we 
> want the last seen value to win.)

In this case you'd have to infer the order of precedence from the variable 
names, not the "+" syntax itself. I.e. if you had spelled it `a + b + c` I 
would have no idea whether `a` or `c` has highest precedence. Compare that with 
a "directed" operator symbol (again, I'm not particularly arguing for "<<"):

prefs = defaults << system_prefs << user_prefs

Here it becomes immediately clear that `system_prefs` supersedes `defaults` and 
`user_prefs` supersedes the other two. A drawback of "+"  here is that you 
can't infer this information from the syntax itself.

Also I'm not sure if this is a good example, since in case something in 
`system_prefs` changes you'd have to recompute the whole thing (`prefs`), since 
you can't tell whether that setting was overwritten by `user_prefs`. I think in 
such a case it would be better to use `collections.ChainMap` for providing a 
hierarchy of preferences, which let's you easily update each level.

> Dicts are a key:value store, not a multiset, and outside of specialised 
> subclasses like Counter, we can't expect that adding the values is 
> meaningful or even possible. "Adding the values" is too specialised and 
> not general enough for dicts, as a slightly less toy example might show:
> d = ({'customerID': 12932063,
>   'purchaseHistory': ,
>   'name': 'Joe Consumer',
>   'rewardsID': 391187} 
>   + {'name': 'Jane Consumer', 'rewardsID': 445137}
>   )
> 
> Having d['name'] to be 'Joe ConsumerJane Consumer' and d['rewardsID'] to 
> be 836324 would be the very opposite of useful behaviour.

I agree that adding the values doesn't make sense for that example but neither 
does updating the values. Why would you want to take a record corresponding to 
"Joe Consumer" and partially update it with data from another consumer ("Jane 
Consumer")? Actually I couldn't tell what the result of that example should be.
___
Python-ideas mailing list -- python-ideas@python.org
To unsubscribe send an email to python-ideas-le...@python.org
https://mail.python.org/mailman3/lists/python-ideas.python.org/
Message archived at 
https://mail.python.org/archives/list/python-ideas@python.org/message/ASKUQIDTVYW2EJ6JBOPJ5QZOKYRH62UC/
Code of Conduct: http://python.org/psf/codeofconduct/


[Python-ideas] Re: PEP 584: Add + and += operators to the built-in dict class.

2019-10-21 Thread Dominik Vilsmeier
Steven D'Aprano wrote:
> On Sat, Oct 19, 2019 at 02:02:43PM -0400, David Mertz wrote:
> > The plus operation on two dictionaries feels far more
> > natural as a
> > vectorised merge, were it to mean anything.  E.g., I'd expect
> > {'a': 5, 'b': 4} + {'a': 3, 'b': 1}
> > {'a': 8, 'b': 5}
> > Outside of Counter when would this behaviour be useful?

For example one could use dicts to represent data tables, with the keys being 
either indices or column names and the values being lists (rows or columns). 
Then for joining two such tables it would be desirable if values are added, 
because then you could simply do `joint_table = table1 + table2`.

Or having a list of records from different sources:

purchases_online = {'item1': [datetime1, datetime2, ...], 'item2': ...}
purchases_store = {'item1': [datetime3, datetime4, ...], ...}
purchases_overall = purchases_online + purchases_store  # Records should be 
concatenated.
# Then doing some analysis on the overall purchases.

`pandas.Series` also behaves dict-like (almost) and does add the values on "+".

> I expect that this feels natural to you because you're thinking about 
> simple (dare I say "toy"?) examples like the above, rather than 
> practical use-cases like "merging multiple preferences":
> prefs = defaults + system_prefs + user_prefs
> 
> # or if you prefer the alternative syntax
> prefs = defaults | system_prefs | user_prefs
> 
> (Note that in this case, the lack of commutativity is a good thing: we 
> want the last seen value to win.)

In this case you'd have to infer the order of precedence from the variable 
names, not the "+" syntax itself. I.e. if you had spelled it `a + b + c` I 
would have no idea whether `a` or `c` has highest precedence. Compare that with 
a "directed" operator symbol (again, I'm not particularly arguing for "<<"):

prefs = defaults << system_prefs << user_prefs

Here it becomes immediately clear that `system_prefs` supersedes `defaults` and 
`user_prefs` supersedes the other two. A drawback of "+"  here is that you 
can't infer this information from the syntax itself.

Also I'm not sure if this is a good example, since in case something in 
`system_prefs` changes you'd have to recompute the whole thing (`prefs`), since 
you can't tell whether that setting was overwritten by `user_prefs`. I think in 
such a case it would be better to use `collections.ChainMap` for providing a 
hierarchy of preferences, which let's you easily update each level.

> Dicts are a key:value store, not a multiset, and outside of specialised 
> subclasses like Counter, we can't expect that adding the values is 
> meaningful or even possible. "Adding the values" is too specialised and 
> not general enough for dicts, as a slightly less toy example might show:
> d = ({'customerID': 12932063,
>   'purchaseHistory': ,
>   'name': 'Joe Consumer',
>   'rewardsID': 391187} 
>   + {'name': 'Jane Consumer', 'rewardsID': 445137}
>   )
> 
> Having d['name'] to be 'Joe ConsumerJane Consumer' and d['rewardsID'] to 
> be 836324 would be the very opposite of useful behaviour.

I agree that adding the values doesn't make sense for that example but neither 
does updating the values. Why would you want to take a record corresponding to 
"Joe Consumer" and partially update it with data from another consumer ("Jane 
Consumer")? Actually I couldn't tell what the result of that example should be.
___
Python-ideas mailing list -- python-ideas@python.org
To unsubscribe send an email to python-ideas-le...@python.org
https://mail.python.org/mailman3/lists/python-ideas.python.org/
Message archived at 
https://mail.python.org/archives/list/python-ideas@python.org/message/WBPF4GIJSXED2GPCX4XK3XYUVBRBLKUJ/
Code of Conduct: http://python.org/psf/codeofconduct/


[Python-ideas] Re: PEP 584: Add + and += operators to the built-in dict class.

2019-10-21 Thread Dominik Vilsmeier
Steven D'Aprano wrote:
> On Sun, Oct 20, 2019 at 11:29:54PM -, Dominik Vilsmeier wrote:
> > The question is, why would someone who has experience
> > with adding 
> > counters but never felt the need to add dicts, assume that this 
> > behavior is specialized in Counter and not inherited by
> > dict.
> > I think you might mean inherited from dict? dict doesn't inherit 
> Counter's behaviour because Counter is the subclass and dict the parent 
> class.

Yes, sorry for the confusion, I meant "inherited from". One of the occasional 
non-native speaker issues :-)

> > Maybe at some point they'll encounter a scenario
> > where they need to 
> > recursive-merge (the Counter style) two dicts and then they might 
> > assume that they just need to add the dicts
> > Okay. So what? If they do this, it will be a mistake. Programmers make 
> mistakes thousands of times a day, it is neither our responsibility nor 
> within our power to prevent them all.
> Programmer error is not a good reason to reject a feature.

But it is the responsibility to assists programmers and help them make as few 
errors as possible by providing a clear and unambiguous syntax. If a specific 
syntax feature is ambiguous in its meaning, it's more likely to be an attractor 
of errors.

> > since they're familiar 
> > with this behavior from Counter and Counter subclasses
> > dict so 
> > it's reasonable to assume this behavior is inherited.
> > No it isn't reasonable. Counters are designed to count. Their values 
> are supposed to be ints, usually positive ints. dicts are general 
> key:value stores where the values can be any kind of object at all, not 
> just numbers or even strings. Most objects don't support addition.
> It is totally unreasonable to assume that dict addition will add values 
> by default when by default, objects cannot be added.

I fully agree to that. But someone working with dicts which store floats or 
lists might be tempted to assume that `d1 + d2` means "add the values" 
(especially if they're reading the code). If in that specific context it's 
perfectly fine (and maybe even reasonable) to add dict values it is more 
difficult to neglect that assumption (unless they're already familiar with the 
syntax). Yes, it's the programmers responsibility to be aware of what specific 
syntax does, but the language should assist as much as possible.

> > how obvious is the conclusion that dict performs a 
> > shallow merge and resolves conflicting keys by giving precedence to 
> > the r.h.s. operand?
> > About as obvious that update performs a shallow merge and resolves 
> duplicate keys by giving precedence to the last seen value.

Only if you know that "+" means "update" in that specific context. Otherwise 
one could even think that there are already ways to copy-merge two dicts, so 
why would they introduce new syntax for that, so "+" must be meaning something 
else (possibly the complementary, preserving l.h.s. values).
___
Python-ideas mailing list -- python-ideas@python.org
To unsubscribe send an email to python-ideas-le...@python.org
https://mail.python.org/mailman3/lists/python-ideas.python.org/
Message archived at 
https://mail.python.org/archives/list/python-ideas@python.org/message/Y4YKYHQCSEQKIVURCWZCOOJI7PODRK5G/
Code of Conduct: http://python.org/psf/codeofconduct/


[Python-ideas] Re: PEP 584: Add + and += operators to the built-in dict class.

2019-10-21 Thread Dominik Vilsmeier
Steven D'Aprano wrote:
> On Sun, Oct 20, 2019 at 11:48:10PM -, Dominik Vilsmeier wrote:
> > Regarding "|" operator, I think a drawback is the
> > resemblance with 
> > "or" (after all it's associated with "__or__") so people might assume 
> > behavior similar to x or y where x takes precedence (for truthy
> > 
> > values of x). So when reading d1 | d2 one could falsely assume 
> > that values in d1 take precedence over the ones in d2 for 
> > conflicting keys. And this is also the existing set behavior (though 
> > it's not really relevant in this case):
> > There's a much easier way to demonstrate what you did:
> >>> {1} | {1.0}
> {1}
> 
> In any case, dict.update already has this behaviour:
> >>> d = {1: 'a'}
> >>> d.update({1.0: 'A'})
> >>> d
> {1: 'A'}
> 
> The existing key is kept, only the value is changed. The PEP gives a 
> proposed implementation, which if I remember correctly is:
> # d1 | d2
> d = d1.copy()
> d.update(d2)
> 
> so it will keep the current dict behaviour:
> 
> keys are stable (first key seen wins)
> values are updated (last value seen wins)

Exactly, so the dict "+" behavior would match the set "|" behavior, preserving 
the keys. But how many users will be concerned about whether the keys are going 
to be preserved? I guess almost everybody will want to know what happens with 
the values, and that question remains unanswered by just looking at the "+" or 
"|" syntax. It's reasonable to assume that values are preserved as well, i.e. 
`d1 + d2` adds the missing keys from `d2` to `d1`. Of course, once you know 
that "+" is actually similar to "update" you can infer that the last value 
wins. But "+" simply doesn't read "update". So in order to know you'll have to 
look it up, but following that argument you could basically settle on any 
operator symbol for the update operation. A drawback of "+" is that different 
interpretations are plausible, and this fact cannot be denied as can be seen 
from the ongoing discussion. Of course one can blame the programmer, if they 
didn't check the documentation carefully enough, also since "in the 
 face of ambiguity, refuse the temptation to guess". But in the end the 
language should assist the programmer and it's better not to introduce 
ambiguity in the first place.

> 
> I think that, strictly speaking, this "keys are stable" behaviour is not 
> guaranteed by the language reference. But it's probably so deeply built 
> into the implementation of dicts that it is unlike to ever change. (I 
> think Guido mentioned something about it being a side-effect of the way 
> dict __setitem__ works?)
___
Python-ideas mailing list -- python-ideas@python.org
To unsubscribe send an email to python-ideas-le...@python.org
https://mail.python.org/mailman3/lists/python-ideas.python.org/
Message archived at 
https://mail.python.org/archives/list/python-ideas@python.org/message/EX2B2QKNVKSTEW7GFPJBLZF7S4TG25R7/
Code of Conduct: http://python.org/psf/codeofconduct/


[Python-ideas] Re: PEP 584: Add + and += operators to the built-in dict class.

2019-10-21 Thread brian . skinn
Agreed -- Anyone who uses numpy a lot might make the same assumption, because 
numpy vectorizes. Anybody who doesn't might expect an extension-equivalent:

>>> import numpy as np
>>> a1 = np.arange(2,6)
>>> a2 = np.arange(4,0,-1)
>>> a2
array([4, 3, 2, 1])
>>> a1
array([2, 3, 4, 5])
>>> a1 + a2
array([6, 6, 6, 6])
>>> l1 = list(range(2,6))
>>> l2 = list(range(4,0,-1)
... )
>>> l1 + l2
[2, 3, 4, 5, 4, 3, 2, 1]
___
Python-ideas mailing list -- python-ideas@python.org
To unsubscribe send an email to python-ideas-le...@python.org
https://mail.python.org/mailman3/lists/python-ideas.python.org/
Message archived at 
https://mail.python.org/archives/list/python-ideas@python.org/message/ZR7SQPXW6KMMUZBCZW2GF7GBADTM6PW6/
Code of Conduct: http://python.org/psf/codeofconduct/


[Python-ideas] Re: PEP 584: Add + and += operators to the built-in dict class.

2019-10-21 Thread brian . skinn
**Strongly** disagree. I would anticipate using this feature a LOT, and would 
be excited to see it added. (I would love to replace things like "d2 = 
d1.copy(); d2.update(d3)" with just "d2 = d1 | d3". In-place "d2 |= d3" is nice 
in its terseness, but isn't a huge benefit.)  But, I completely agree with the 
arguments in favor of using "|" from the semantic perspective of the operation 
being much more like a set operation, than a list operation.

Further: One angle I don't think I've read from anyone yet (still catching up 
on the thread tho) is the question of the obscurity of "|" vs the commonality 
of "+", and how they would likely interact with newcomers. A newcomer is likely 
going to use "+" a LOT, in all sorts of different situations. Given how 
non-intuitive dict merging can be, I would rather 'd1 + d2' throw a TypeError 
than return something unexpected. The more-obscure 'd1 | d2' is likely only 
going to be used by people who know how the machinery works and go searching 
for a more concise idiom, and who thus are less likely to be surprised by how 
it works.

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


[Python-ideas] Copying a multiple values of a dict to another with a lot easier syntax

2019-10-21 Thread Gediz GÜRSU
m and n are lists or dicts or enumerates or classes or anything it can be
assigned like following:

instead of :

m.a=n.a;
m.b=n.b;
m.c=n.c;
...

I suggest
a,b,c of m to n ;

I thought of this while writing something in javascript since I love pyhton
above everything I can type (even more than native language sentences) I
wanted to post this idea to here
It is my first idea while coding ...

In javascript, I was assinging a boundingBoxRect values to a div it was
going like this:

adiv=document.createElement("div")
adiv.style.x=comp.x;
adiv.style.y=comp.y;
adiv.style.height=comp.height;
adiv.style.widht=comp.width;

I thought it is super waste of time instead of :
x,y,height,width of comp to adiv;

English is not my native language and as I said its my first idea while
coding.
Thank you.

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


[Python-ideas] Re: PEP 584: Add + and += operators to the built-in dict class.

2019-10-21 Thread Andrew Barnert via Python-ideas
On Oct 21, 2019, at 09:29, Steven D'Aprano  wrote:
> 
> What did you think it was, if it wasn't a 
> specialised "sum these values" function?

For what it’s worth, I initially thought it was a general fold function, using 
the magic of optional parameters and operator polymorphism to default to the 
most common reduction operation for a whole bunch of types. But it only took a 
few seconds to realize I was wrong. (Although I think this was added not long 
after new-style classes and the full dunder protocols, so I probably did have 
fun building a wrapper type that I could pass to sum and use it efficiently as 
a generic fold function against its will, it was pretty obvious that’s not what 
it was for.)

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


[Python-ideas] Re: Copying a multiple values of a dict to another with a lot easier syntax

2019-10-21 Thread Steve Jorgensen
Steve Jorgensen wrote:
> gedizgursu@gmail.com wrote:
> > m and n are lists or dicts or enumerates or classes
> > or anything it can be assigned like
> > following:
> > instead of :
> > m.a=n.a;
> > m.b=n.b;
> > m.c=n.c;
> > ...
> > I suggest:
> > a,b,c of m to n ;
> > I thought of this while writing something in javascript since I love pyhton 
> > above
> > everything I can type (even more than native language sentences) I wanted 
> > to post this
> > idea to here
> > It is my first idea while coding ...
> > In javascript, I was assinging a boundingBoxRect values to a div it was 
> > going like
> > this:
> > adiv=document.createElement("div")
> > adiv.style.x=comp.x;
> > adiv.style.y=comp.y;
> > adiv.style.height=comp.height;
> > adiv.style.widht=comp.width;
> > I thought it is super waste of time instead of :
> > x,y,height,width of comp to adiv;
> > How about something like…
> setattrs(adiv.style, getattrs(comp, 'x y height width')
> where getattrs returns a dict and setattrs accepts a
> mapping?
> That could be done now without adding any new features to the language. These 
> functions
> could be added to the standard library somewhere if they should become 
> official
> things.

Those might not be the best names for those functions, but continuing with 
those for now, here's an example implementation:

from functools import reduce
import re


def getattrs(obj, *names):
names = reduce(_concat_attr_names, names, [])
return {name: getattr(obj, name) for name in names}


def setattrs(obj, mapping):
for name, value in mapping.items():
setattr(obj, name, value)


def _concat_attr_names(x, y):
return x + re.split(r'\s+', y)


class Thing:
def __init__(self, color=None, size=None, shape=None):
self.color = color
self.size = size
self.shape = shape

def __repr__(self):
return (
f'Thing({repr(self.color)}, {repr(self.size)},'
f' {repr(self.shape)})')


thing_a = Thing('red', 'large', 'round')
thing_b = Thing('blue')

setattrs(thing_b, getattrs(thing_a, 'size shape'))

print(repr(thing_b))  # -> 'Thing('blue', 'large', 'round')
___
Python-ideas mailing list -- python-ideas@python.org
To unsubscribe send an email to python-ideas-le...@python.org
https://mail.python.org/mailman3/lists/python-ideas.python.org/
Message archived at 
https://mail.python.org/archives/list/python-ideas@python.org/message/Z4SY7U6RQCVPEGHU3VOABDC6LYKTVZNL/
Code of Conduct: http://python.org/psf/codeofconduct/


[Python-ideas] Re: PEP 584: Add + and += operators to the built-in dict class.

2019-10-21 Thread Steven D'Aprano
On Mon, Oct 21, 2019 at 10:25:57AM -0500, Dan Sommers wrote:

> Iterables are ordered collections of values, and outside of
> specialized subclasses, we can't expect that adding the values
> is meaningful or even possible.

Correct. That's why lists, tuples, strings, bytes and even arrays all 
define addition as concatentation rather than element-by-element 
addition. We leave it to specialised libraries and data types, like 
numpy, to implement element-by-element addition.


> "Adding the values" is too
> specialized and not general enough for iterables.

Correct. That's why join is a specialised string method, rather than a 
method on more general lists.


> And yet the builtin function sum exists and works the way it
> does.

Yes, because sum is a specialised function whose job is to sum the 
values of an iterable. What did you think it was, if it wasn't a 
specialised "sum these values" function?


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


[Python-ideas] Re: Copying a multiple values of a dict to another with a lot easier syntax

2019-10-21 Thread Andrew Barnert via Python-ideas
On Oct 21, 2019, at 07:44, gedizgu...@gmail.com wrote:
> 
> m and n are lists or dicts or enumerates or classes or anything it can be 
> assigned like following:

Assigning attributes is different from assigning items to a collection like a 
list or dict. That’s why there are separate syntaxes, and separate protocols 
for it.

I realize that in JavaScript that’s not true; collections are just objects with 
their items as attributes, so `a.b` means the same thing as `a['b']`. But 
that’s confusing more often than it’s helpful, and I don’t think anyone wants 
to bring it to Python, or any other languages.

> instead of :
> 
> m.a=n.a;
> m.b=n.b;
> m.c=n.c;
> ...
> 
> I suggest:
> 
> a,b,c of m to n ;

You can do this with a two-liner function:

copy_attrs(m, n, 'a', 'b', 'c')

… which you implement like this;

def copy_items(src, dst, keys):
for key in keys:
dst[key] = src[key]

def copy_attrs(src, dst, *attrs):
for attr in attrs:
setattr(dst, attr, getattr(src, attr))

Or, if you want to check that all of the source attributes exist and raise 
before writing anything to dst:

values = [src[key] for key in keys]
for (key, value) in zip(keys, values):
dst[key] = value

Or maybe instead of *attrs you want to take a single string and split() it, 
similar to the way namedtuple does.

The functions are simple to write, and probably wouldn’t be used often, and 
there are variations that you’d probably want sometimes one way and sometimes 
the other. So I don’t think this needs to be in the stdlib, much less needs 
custom syntax. But I could be wrong. If you disagree, you can:

 * Try to argue for good use cases that would come up frequently. 
 * Search the stdlib, popular projects on PyPI, in your own codebase, etc. to 
come up with examples that would be more readable with this new feature.
 * Search places like python-list and StackOverflow to see if people are asking 
for this feature (or, even better, if people are confused but would be asking 
for this feature if they knew what they wanted).
 * Package it up and publish on PyPI and come back later with stats showing 
lots of people downloading and using it.

As a side note: Python statements don’t end in semicolons like JavaScript. It’s 
usually legal to put one there (it means you’re adding an extra null statement 
after each statement, which is wasteful but otherwise has no effect that will 
usually break anything). But you shouldn’t do it.

More generally, don’t try to write Python as if it were JavaScript. They have 
different idioms for a lot of things, and trying to treat them the same means 
you end up writing Python code that isn’t very good Python and JS code that 
isn’t very good JS. 

> I thought of this while writing something in javascript since I love pyhton 
> above everything I can type (even more than native language sentences) I 
> wanted to post this idea to here
> It is my first idea while coding ...
> 
> In javascript, I was assinging a boundingBoxRect values to a div it was going 
> like this:
> 
> adiv=document.createElement("div")
> adiv.style.x=comp.x;
> adiv.style.y=comp.y;
> adiv.style.height=comp.height;
> adiv.style.widht=comp.width;
> 
> I thought it is super waste of time instead of :
> x,y,height,width of comp to adiv;

Another way people have tried to solve this problem is with a BASIC-style 
`with` (which has nothing to do with Python’s `with`):

with adiv.style:
.y = comp.y
.height = comp.height

I don’t think that’s really helpful here, because you have two different 
objects you want to shortcut, not just one. But you might want to look into 
past proposals to add a similar feature to Python, to see if any of them did 
come up with something that would be helpful to you.
___
Python-ideas mailing list -- python-ideas@python.org
To unsubscribe send an email to python-ideas-le...@python.org
https://mail.python.org/mailman3/lists/python-ideas.python.org/
Message archived at 
https://mail.python.org/archives/list/python-ideas@python.org/message/NUGWHXCVN5LZZLDX74R7CVDV2QPRTTQQ/
Code of Conduct: http://python.org/psf/codeofconduct/


[Python-ideas] Re: PEP 584: Add + and += operators to the built-in dict class.

2019-10-21 Thread Steven D'Aprano
On Sun, Oct 20, 2019 at 11:29:54PM -, Dominik Vilsmeier wrote:

> The question is, why would someone who has experience with adding 
> counters but never felt the need to add dicts, assume that this 
> behavior is specialized in `Counter` and not inherited by `dict`. 

I think you might mean inherited *from* dict? dict doesn't inherit 
Counter's behaviour because Counter is the subclass and dict the parent 
class.


> Maybe at some point they'll encounter a scenario where they need to 
> recursive-merge (the `Counter` style) two dicts and then they might 
> assume that they just need to add the dicts 

Okay. So what? If they do this, it will be a mistake. Programmers make 
mistakes thousands of times a day, it is neither our responsibility nor 
within our power to prevent them all.

Programmer error is not a good reason to reject a feature.


> since they're familiar 
> with this behavior from `Counter` and `Counter` subclasses `dict` so 
> it's reasonable to assume this behavior is inherited.

No it isn't reasonable. Counters are designed to *count*. Their values 
are supposed to be ints, usually positive ints. dicts are general 
key:value stores where the values can be any kind of object at all, not 
just numbers or even strings. Most objects don't support addition.

It is totally unreasonable to assume that dict addition will add values 
by default when by default, objects cannot be added.


> how obvious is the conclusion that dict performs a 
> shallow merge and resolves conflicting keys by giving precedence to 
> the r.h.s. operand?

About as obvious that update performs a shallow merge and resolves 
duplicate keys by giving precedence to the last seen value.



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


[Python-ideas] Re: Copying a multiple values of a dict to another with a lot easier syntax

2019-10-21 Thread Steve Jorgensen
gedizgursu@gmail.com wrote:
> m and n are lists or dicts or enumerates or classes or anything it can be 
> assigned like
> following:
> instead of :
> m.a=n.a;
> m.b=n.b;
> m.c=n.c;
> ...
> I suggest:
> a,b,c of m to n ;
> I thought of this while writing something in javascript since I love pyhton 
> above
> everything I can type (even more than native language sentences) I wanted to 
> post this
> idea to here
> It is my first idea while coding ...
> In javascript, I was assinging a boundingBoxRect values to a div it was going 
> like
> this:
> adiv=document.createElement("div")
> adiv.style.x=comp.x;
> adiv.style.y=comp.y;
> adiv.style.height=comp.height;
> adiv.style.widht=comp.width;
> I thought it is super waste of time instead of :
> x,y,height,width of comp to adiv;

How about something like…
setattrs(adiv.style, getattrs(comp, 'x y height width')

where `getattrs` returns a dict and `setattrs` accepts a mapping?

That could be done now without adding any new features to the language. These 
functions could be added to the standard library somewhere if they should 
become official things.
___
Python-ideas mailing list -- python-ideas@python.org
To unsubscribe send an email to python-ideas-le...@python.org
https://mail.python.org/mailman3/lists/python-ideas.python.org/
Message archived at 
https://mail.python.org/archives/list/python-ideas@python.org/message/N6YG43COFMKHT2KYVOJWCCOXAT4UJDGW/
Code of Conduct: http://python.org/psf/codeofconduct/


[Python-ideas] Re: Copying a multiple values of a dict to another with a lot easier syntax

2019-10-21 Thread Jonathan Fine
Hi

You quite rightly noted that
m.a = n.a
m.b = m.b
m.c = m.c
is repetitive. Larger such examples cry out for refactoring.

Such can already be done in Python. How about
for key in 'a', 'b', 'c':
setattr(m, key, getattr(n, key))

If you're doing this a lot, how about a helper function:

   transfer_attrs(tgt, src, keys)

Here's the help messages for the builtin commands setattr and getattr.
They're a bit like item access for a dictionary.

setattr(obj, name, value, /)
Sets the named attribute on the given object to the specified value.

setattr(x, 'y', v) is equivalent to ``x.y = v''

getattr(...)
getattr(object, name[, default]) -> value

Get a named attribute from an object; getattr(x, 'y') is equivalent to
x.y.
When a default argument is given, it is returned when the attribute
doesn't
exist; without it, an exception is raised in that case.

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


[Python-ideas] Re: PEP 584: Add + and += operators to the built-in dict class.

2019-10-21 Thread Dan Sommers

On 10/21/19 9:51 AM, Steven D'Aprano wrote:


Dicts are a key:value store, not a multiset, and outside of specialised
subclasses like Counter, we can't expect that adding the values is
meaningful or even possible. "Adding the values" is too specialised and
not general enough for dicts ...


Iterables are ordered collections of values, and outside of
specialized subclasses, we can't expect that adding the values
is meaningful or even possible.  "Adding the values" is too
specialized and not general enough for iterables.

And yet the builtin function sum exists and works the way it
does.

Lately, I tend to reduce or fold my collections rather than to
use symbolic operators, and to write specialized functions when
it comes to use cases like preferences.

I'd *almost* vote for | operating on the keys (because keys are
like a set) and + for operating on values (because adding one key
to another is more meaningless than adding arbitrary values), but
that doesn't seem quite right, either.
___
Python-ideas mailing list -- python-ideas@python.org
To unsubscribe send an email to python-ideas-le...@python.org
https://mail.python.org/mailman3/lists/python-ideas.python.org/
Message archived at 
https://mail.python.org/archives/list/python-ideas@python.org/message/B2GKUVSKQC7KKDLTYKINSGNI66GHJYTU/
Code of Conduct: http://python.org/psf/codeofconduct/


[Python-ideas] Re: PEP 584: Add + and += operators to the built-in dict class.

2019-10-21 Thread Steven D'Aprano
On Sun, Oct 20, 2019 at 11:48:10PM -, Dominik Vilsmeier wrote:

> Regarding "|" operator, I think a drawback is the resemblance with 
> "or" (after all it's associated with "__or__") so people might assume 
> behavior similar to `x or y` where `x` takes precedence (for truthy 
> values of `x`). So when reading `d1 | d2` one could falsely assume 
> that values in `d1` take precedence over the ones in `d2` for 
> conflicting keys. And this is also the existing `set` behavior (though 
> it's not really relevant in this case):

There's a much easier way to demonstrate what you did:

>>> {1} | {1.0}
{1}

In any case, dict.update already has this behaviour:

>>> d = {1: 'a'}
>>> d.update({1.0: 'A'})
>>> d
{1: 'A'}

The existing key is kept, only the value is changed. The PEP gives a 
proposed implementation, which if I remember correctly is:

# d1 | d2
d = d1.copy()
d.update(d2)

so it will keep the current dict behaviour:

- keys are stable (first key seen wins)
- values are updated (last value seen wins)

I think that, strictly speaking, this "keys are stable" behaviour is not 
guaranteed by the language reference. But it's probably so deeply built 
into the implementation of dicts that it is unlike to ever change. (I 
think Guido mentioned something about it being a side-effect of the way 
dict `__setitem__` works?)



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


[Python-ideas] Re: PEP 584: Add + and += operators to the built-in dict class.

2019-10-21 Thread Neil Girdhar
I would use it, and I prefer | for the reasons given by Stephen, MRAB, and 
the other proponents.

On Monday, October 21, 2019 at 1:08:32 AM UTC-4, Andrew Barnert via 
Python-ideas wrote:
>
> On Oct 20, 2019, at 21:10, Stephen J. Turnbull <
> turnbull...@u.tsukuba.ac.jp > wrote: 
> > 
> > I'm not against having an operator for updating dicts, but "+" is not 
> > it.  "|" is fine, though. 
>
> It seems like people who don’t really like this feature and don’t plan to 
> use it mostly really want it to be spelled | if it has to be added. But 
> people who are dying for it mostly want + (except for the ones who want all 
> the set operators). I’m not sure what that means… 
>
> ___
> Python-ideas mailing list -- python...@python.org 
> To unsubscribe send an email to python-id...@python.org 
> https://mail.python.org/mailman3/lists/python-ideas.python.org/
> Message archived at 
> https://mail.python.org/archives/list/python-ideas@python.org/message/TV73IEFOV77Z64RN2QXOKYIOBCUHD45I/
> Code of Conduct: http://python.org/psf/codeofconduct/
>
___
Python-ideas mailing list -- python-ideas@python.org
To unsubscribe send an email to python-ideas-le...@python.org
https://mail.python.org/mailman3/lists/python-ideas.python.org/
Message archived at 
https://mail.python.org/archives/list/python-ideas@python.org/message/NXQ4YKXCT6SHZ6QDRWCAE4RJB5MULPSQ/
Code of Conduct: http://python.org/psf/codeofconduct/


[Python-ideas] Re: PEP 584: Add + and += operators to the built-in dict class.

2019-10-21 Thread Steven D'Aprano
On Sat, Oct 19, 2019 at 02:02:43PM -0400, David Mertz wrote:

> The plus operation on two dictionaries feels far more natural as a
> vectorised merge, were it to mean anything.  E.g., I'd expect
> 
> >>> {'a': 5, 'b': 4} + {'a': 3, 'b': 1}
> {'a': 8, 'b': 5}

Outside of Counter when would this behaviour be useful?

I expect that this feels natural to you because you're thinking about 
simple (dare I say "toy"?) examples like the above, rather than 
practical use-cases like "merging multiple preferences":

prefs = defaults + system_prefs + user_prefs

# or if you prefer the alternative syntax
prefs = defaults | system_prefs | user_prefs


(Note that in this case, the lack of commutativity is a good thing: we 
want the last seen value to win.)

Dicts are a key:value store, not a multiset, and outside of specialised 
subclasses like Counter, we can't expect that adding the values is 
meaningful or even possible. "Adding the values" is too specialised and 
not general enough for dicts, as a slightly less toy example might show:


d = ({'customerID': 12932063,
  'purchaseHistory': ,
  'name': 'Joe Consumer',
  'rewardsID': 391187} 
  + {'name': 'Jane Consumer', 'rewardsID': 445137}
  )


Having d['name'] to be 'Joe ConsumerJane Consumer' and d['rewardsID'] to 
be 836324 would be the very opposite of useful behaviour.



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


[Python-ideas] Re: PEP 584: Add + and += operators to the built-in dict class.

2019-10-21 Thread Paul Moore
On Mon, 21 Oct 2019 at 14:55, David Mertz  wrote:

> What is proposed in this PEP is to add a meaning for dct1+dct2 that would be 
> well defined, but that would be DIFFERENT from the "one obvious meaning."

For me, what's coming out is that there *is* no "obvious meaning".
People expect different things. All the attempts to persuade people
that they "should" expect something other than what they do is merely
symptomatic of the basic fact, that not everyone expects the same
thing from this operation.

Whether "in time, you'll learn the meaning that Python assigns to
dictionary +", and "the proposed meaning is useful in a number of
contexts" are sufficiently true to counterbalance the fact that people
assume different meanings when faced with the operator for the first
time, is a different question - and one that's much harder to answer.
But arguing over what's "obvious" in the face of people clearly
stating that they have differing initial assumptions, seems like a
waste of time to me. Let's just accept that the meaning of + on
dictionaries, as defined by the PEP, is something that *at least some
people* will not find immediately obvious, and will have to learn.

Personally, I think the utility is marginal, the "obviousness" is
context dependent, the inconsistencies with set union are a concern,
and the fact that there are already (admittedly more convoluted) ways
of doing this makes the proposal a minor win at best. So I'm probably
-0 on the PEP.

Paul

PS Yes, every programming language construct is unfamiliar to someone
completely new to programming. Yes, even keywords and method names are
unfamiliar to people who are not native English speakers. Both of
those points support my argument, so no-one should feel any particular
need to make them here ;-)
___
Python-ideas mailing list -- python-ideas@python.org
To unsubscribe send an email to python-ideas-le...@python.org
https://mail.python.org/mailman3/lists/python-ideas.python.org/
Message archived at 
https://mail.python.org/archives/list/python-ideas@python.org/message/DAN3PM3H4FQWRBQKCNPZFEZS6KYJGFZ3/
Code of Conduct: http://python.org/psf/codeofconduct/


[Python-ideas] Re: PEP 584: Add + and += operators to the built-in dict class.

2019-10-21 Thread Rhodri James

On 21/10/2019 14:54, David Mertz wrote:

On Mon, Oct 21, 2019, 9:14 AM Rhodri James


The plus operation on two dictionaries feels far more natural as

a vectorised merge, were it to mean anything.  E.g., I'd expect

{'a': 5, 'b': 4} + {'a': 3, 'b': 1}

{'a': 8, 'b': 5}

That's only a natural expectation if you also expect the values in your
dict to be addable (in the sense of doing something useful with a "+"
operator).  It never occurs to me to make that assumption because a fair
amount of the time it isn't true in my code.


I'm not arguing that we SHOULD make '+' mean recursive addition. I'm just
saying that if I never read this discussion, then later read `dict1 +
dict2` in code, that's what I'd expect.


And I'm just explaining why that's not what I expect.  My code at the 
moment looks more like


lookup_dict[remote_id] = RemoteObject(stuff)

so the idea of adding dict values simply doesn't come to me.

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


[Python-ideas] Re: PEP 584: Add + and += operators to the built-in dict class.

2019-10-21 Thread Ethan Furman

On 10/20/2019 10:08 PM, Andrew Barnert via Python-ideas wrote:

On Oct 20, 2019, at 21:10, Stephen J. Turnbull wrote:



I'm not against having an operator for updating dicts, but "+" is not
it.  "|" is fine, though.


It seems like people who don’t really like this feature and don’t plan to use 
it mostly really want it to be spelled | if it has to be added. But people who 
are dying for it mostly want + (except for the ones who want all the set 
operators). I’m not sure what that means…


I really don't want it as '+'.  I'm happy to use it as '|'.  :)

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


[Python-ideas] Re: PEP 584: Add + and += operators to the built-in dict class.

2019-10-21 Thread David Mertz
On Mon, Oct 21, 2019, 9:14 AM Rhodri James

> > The plus operation on two dictionaries feels far more natural as
> a vectorised merge, were it to mean anything.  E.g., I'd expect
> >
>  {'a': 5, 'b': 4} + {'a': 3, 'b': 1}
> > {'a': 8, 'b': 5}
>
> That's only a natural expectation if you also expect the values in your
> dict to be addable (in the sense of doing something useful with a "+"
> operator).  It never occurs to me to make that assumption because a fair
> amount of the time it isn't true in my code.
>

I'm not arguing that we SHOULD make '+' mean recursive addition. I'm just
saying that if I never read this discussion, then later read `dict1 +
dict2` in code, that's what I'd expect.

I think a large percentage of the code I work with would operates insert
this hypothetical meaning. Values in my ducts are usually numbers, lists,
tuples, or *other dicts*. If that last had this new behavior, things would
mostly work.

I don't usually write code with:

d1 = {'purchases': [apples, bananas, pears]}
d2 = {'purchases': 17}

I could, of course. But lots of things I can do raise exceptions. Like
`dct[mutable_var] = val` (yes, technically "unhashable"). This one I
actually wind up encountering pretty often (or with sets even more).

What is proposed in this PEP is to add a meaning for dct1+dct2 that would
be well defined, but that would be DIFFERENT from the "one obvious meaning."
___
Python-ideas mailing list -- python-ideas@python.org
To unsubscribe send an email to python-ideas-le...@python.org
https://mail.python.org/mailman3/lists/python-ideas.python.org/
Message archived at 
https://mail.python.org/archives/list/python-ideas@python.org/message/TCLT7CYN3U3PIOG5BWIFXJOEPTNOM2VU/
Code of Conduct: http://python.org/psf/codeofconduct/


[Python-ideas] Re: PEP 584: Add + and += operators to the built-in dict class.

2019-10-21 Thread Ricky Teachey
> >> but i'm -0 because i am very concerned it will not be obvious to new
> >> learners, without constantly looking it up, whether adding two mappings
> >> together would either:
> >
> > When Python first added the dict.update method (I think that was in
> > 1.5?) I could never remember if it kept the old values or the new. But
> > there were a million other things I couldn't remember either, such as
> > whether slicing was open or closed, whether the trig functions in math
> > took degrees or radians, whether exponentiation was ^ or ** and whether
> > I needed parentheses around calls to print or not.
>
> Agreed we already have update; people already have to learn that it
> uses the right value, and that it’s spelled update rather than merge! or
> something else. If we have + or |, people will have to learn that it uses
> the right value there too. The fact that all of the operations are
> consistent will mean that eventually they only have one thing to remember
> instead of a bunch of separate things, but it’s still a thing to remember.
>

Well, the part about looking it up wasn't so much the actual objection as
it being so much less intuitive- for newcomers- what exactly the operation
would do compared to the addition of the other basic structures: strings
and lists. Those are so obvious they just make sense. Having to look it up
a lot is just a potential symptom of a larger problem.

Granted, I'm coming at this from an assumption that there should be a
higher bar for operators as compared to methods: imo, they should be
totally intuitive in the way they behave. In fact this consistency about
operators is one of the things I love about python. I don't think that
standard is ~quite~ met here. So I'm still -0.. I think the most intuitive
situation is the status quo: "no dict addition because what do you do with
the values?" It's certainly possible I'm setting the bar too high, though,
or that I'm so familiar with the way operators for other structures behave
now that they seem intuitive to me when really they are not.

The .update() method, on the other hand, feels much more naturally
intuitive once you are aware it exists. And I would be very much in favor
of a method (a new one, or perhaps adding arguments to .copy()) that copies
and updates a dictionary in a single step.
___
Python-ideas mailing list -- python-ideas@python.org
To unsubscribe send an email to python-ideas-le...@python.org
https://mail.python.org/mailman3/lists/python-ideas.python.org/
Message archived at 
https://mail.python.org/archives/list/python-ideas@python.org/message/BOL525ZPR2BSZ632H54UPO7JYO4CCUEL/
Code of Conduct: http://python.org/psf/codeofconduct/


[Python-ideas] Re: PEP 584: Add + and += operators to the built-in dict class.

2019-10-21 Thread Rhodri James

On 19/10/2019 19:02, David Mertz wrote:

I am strong -1 on the proposal.

The plus operation on two dictionaries feels far more natural as a
vectorised merge, were it to mean anything.  E.g., I'd expect


{'a': 5, 'b': 4} + {'a': 3, 'b': 1}

{'a': 8, 'b': 5}


That's only a natural expectation if you also expect the values in your 
dict to be addable (in the sense of doing something useful with a "+" 
operator).  It never occurs to me to make that assumption because a fair 
amount of the time it isn't true in my code.


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


[Python-ideas] Re: PEP 584: Add + and += operators to the built-in dict class.

2019-10-21 Thread Rhodri James

On 20/10/2019 05:52, Inada Naoki wrote:

I think this PEP doesn't include one big disadvantage of the + operator.

If we use + for dict merging, set doesn't support + looks strange
and inconsistent.


As I've said before, set already looks strange and inconsistent to me. 
I have some hopes that after this discussion I will remember that set 
union is spelt "|", but thus far I've had to look it up every time.


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


[Python-ideas] Re: Expose Py_TabcheckFlag as other PyAPI_DATA flag.

2019-10-21 Thread Victor Stinner
Eloi opened https://bugs.python.org/issue38543

This issue is specific to Python 2.7. Python 3 no longer has Py_TabcheckFlag.

Eloi: hey, you should upgrade to Python 3 and have a look at my PEP
587 "Python Initialization Configuration" ;-)

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


[Python-ideas] Re: Expose Py_TabcheckFlag as other PyAPI_DATA flag.

2019-10-21 Thread GAUDRY Eloi
Hi Victor,
yes, you're right.
I've already upgraded and I mixed up some patches I used to apply on the old 
2.7 branch.
Thanks for your feedback.
Eloi

From: Victor Stinner 
Sent: Monday, October 21, 2019 13:15
To: GAUDRY Eloi 
Cc: gu...@python.org ; python-ideas@python.org 

Subject: Re: [Python-ideas] Re: Expose Py_TabcheckFlag as other PyAPI_DATA flag.

This email is not from Hexagon’s Office 365 instance. Please be careful while 
clicking links, opening attachments, or replying to this email.


Eloi opened 
https://eur02.safelinks.protection.outlook.com/?url=https%3A%2F%2Fbugs.python.org%2Fissue38543data=02%7C01%7C%7C59611e2716ed47c4e6b408d75617f8a5%7C1b16ab3eb8f64fe39f3e2db7fe549f6a%7C0%7C0%7C637072533263290085sdata=82y4CVE3A12A4RH4K5I02fWRDvKt5IJHb4lZzbwX32c%3Dreserved=0

This issue is specific to Python 2.7. Python 3 no longer has Py_TabcheckFlag.

Eloi: hey, you should upgrade to Python 3 and have a look at my PEP
587 "Python Initialization Configuration" ;-)

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


[Python-ideas] Re: Expose Py_TabcheckFlag as other PyAPI_DATA flag.

2019-10-21 Thread GAUDRY Eloi
ok, I will.
thanks



Eloi Gaudry
Senior Product Development Engineer, HPC & IT manager
Free Field Technologies, part of Hexagon's Manufacturing Intelligence division
T: +32 10 495 147
E: eloi.gau...@fft.be

[FFT Logo]

Free Field Technologies
Rue Emile Francqui, 9
Mont-Saint-Guibert, Belgium1435
www.fft.be | 
LinkedIn | 
Facebook | 
Twitter




From: Guido van Rossum 
Sent: Friday, October 18, 2019 20:27
To: GAUDRY Eloi 
Cc: python-ideas@python.org 
Subject: Re: [Python-ideas] Expose Py_TabcheckFlag as other PyAPI_DATA flag.

This email is not from Hexagon’s Office 365 instance. Please be careful while 
clicking links, opening attachments, or replying to this email.

Please submit this to 
bugs.python.org.

On Fri, Oct 18, 2019 at 3:02 AM GAUDRY Eloi 
mailto:eloi.gau...@fft.be>> wrote:
Hi

When looking at the pydebug.h header file, I see that some symbols are not 
declared as exported.
For instance, I would like to be able to change the value of the 
Py_TabcheckFlag when running specific codelines.
Any chance this patch could be added ?

Thanks for your feedback,
Eloi


Index: Include/pydebug.h
===
--- Include/pydebug.h (revision 118072)
+++ Include/pydebug.h (working copy)
@@ -16,6 +16,7 @@
 PyAPI_DATA(int) Py_NoSiteFlag;
 PyAPI_DATA(int) Py_BytesWarningFlag;
 PyAPI_DATA(int) Py_FrozenFlag;
+PyAPI_DATA(int) Py_TabcheckFlag;
 PyAPI_DATA(int) Py_IgnoreEnvironmentFlag;
 PyAPI_DATA(int) Py_DontWriteBytecodeFlag;
 PyAPI_DATA(int) Py_NoUserSiteDirectory;






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


--
--Guido van Rossum 
(python.org/~guido)
Pronouns: he/him (why is my pronoun 
here?)
___
Python-ideas mailing list -- python-ideas@python.org
To unsubscribe send an email to python-ideas-le...@python.org
https://mail.python.org/mailman3/lists/python-ideas.python.org/
Message archived at 
https://mail.python.org/archives/list/python-ideas@python.org/message/DXZAULGZ6B3ZMGXRLG3VAUXDL7MLPAKL/
Code of Conduct: http://python.org/psf/codeofconduct/


[Python-ideas] Re: Expose _PyGC_generation0 for allowing internal use directly from a CPython extension

2019-10-21 Thread GAUDRY Eloi
ok, I will.
thanks

éloi

From: Guido van Rossum 
Sent: Friday, October 18, 2019 20:26
To: GAUDRY Eloi 
Cc: python-ideas@python.org 
Subject: Re: [Python-ideas] Expose _PyGC_generation0 for allowing internal use 
directly from a CPython extension

This email is not from Hexagon’s Office 365 instance. Please be careful while 
clicking links, opening attachments, or replying to this email.

This looks like an issue for 
bugs.python.org.
 After opening a bug there you could also try to fix this yourself and submit a 
Pull Request (see the Python devguide).

On Fri, Oct 18, 2019 at 3:10 AM GAUDRY Eloi 
mailto:eloi.gau...@fft.be>> wrote:
Hi

I would like to be able to get an handle on PyGC_Head*_PyGC_generation0 from a 
CPython extension.
This is possible when building Python on a Posix host, but not on Windows 
because of a missing PyAPI_DATA wrapping of the said object in the objimpl.h 
header.

Having the possibility to inspect the PyGC_Head here can be very useful when 
customizing the way a garbage-collectable object created from CPython extension 
would be cleaned/inspected, etc.

Any chance this patch could be added to get the same capabilities on Windows 
and Posix platforms ?

Thanks for your feedback,
Eloi



Index: Include/objimpl.h
===
--- Include/objimpl.h (revision 118072)
+++ Include/objimpl.h (working copy)
@@ -258,7 +258,7 @@
 double dummy;  /* force worst-case alignment */
 } PyGC_Head;

-extern PyGC_Head *_PyGC_generation0;
+PyAPI_DATA(PyGC_Head*) _PyGC_generation0;

 #define _Py_AS_GC(o) ((PyGC_Head *)(o)-1)

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


--
--Guido van Rossum 
(python.org/~guido)
Pronouns: he/him (why is my pronoun 
here?)
___
Python-ideas mailing list -- python-ideas@python.org
To unsubscribe send an email to python-ideas-le...@python.org
https://mail.python.org/mailman3/lists/python-ideas.python.org/
Message archived at 
https://mail.python.org/archives/list/python-ideas@python.org/message/W34GXNK3CIK443E2R5MPECHGWSYCMWI4/
Code of Conduct: http://python.org/psf/codeofconduct/


[Python-ideas] Re: Ability to set precedence of classdict (returned from __prepare__) for a metaclass type

2019-10-21 Thread Steve Jorgensen
Steve Jorgensen wrote:
> Oops. Obviously, the above is pseudo-code because I left ('~OTHER~', 
> 'Something
> else') the first assert, and I have (Food, Food) instead of
> (Food,) * 4 for the second assert. Possibly some other mistakes as well.

Umm, like the fact that I'm testing for colors instead of foods since I changed 
the kind of example case. :)

Here's an updated example, minus the comments — still pseudocode with possible 
mistakes:

from choices import ChoicesContext


# Get choices context for Food choices.
fcc = ChoicesContext()

class Food(fcc.base):
fcc.APPLE
fcc.GREEK_YOGURT
fcc.EGG_MCMUFFIN %= 'Egg McMuffin'
fcc.append('~OTHER~', 'Something else')

assert (
(Food.Apple, Food.GREEK_YOGURT, fcc.EGG_MCMUFFIN) ==
('APPLE', 'GREEK_YOGURT', 'EGG_MCMUFFIN'))

assert tuple(Food) == (
('APPLE','Apple'),
('GREEK_YOGURT', 'Greek Yogurt'),
('EGG_MCMIFFIN', 'Egg McMuffin'),
('~OTHER~',  'Something else'),
)
assert tuple(type(food) for food in Food) == (Food,) * 4
___
Python-ideas mailing list -- python-ideas@python.org
To unsubscribe send an email to python-ideas-le...@python.org
https://mail.python.org/mailman3/lists/python-ideas.python.org/
Message archived at 
https://mail.python.org/archives/list/python-ideas@python.org/message/6CQNDKSO7LHL5RTUA7M76BYKN3AR7ILV/
Code of Conduct: http://python.org/psf/codeofconduct/


[Python-ideas] Re: Ability to set precedence of classdict (returned from __prepare__) for a metaclass type

2019-10-21 Thread Steve Jorgensen
Oops. Obviously, the above is pseudo-code because I left `('~OTHER~', 
'Something else')` the first assert, and I have `(Food, Food)` instead of 
`(Food,) * 4` for the second assert. Possibly some other mistakes as well.
___
Python-ideas mailing list -- python-ideas@python.org
To unsubscribe send an email to python-ideas-le...@python.org
https://mail.python.org/mailman3/lists/python-ideas.python.org/
Message archived at 
https://mail.python.org/archives/list/python-ideas@python.org/message/TGLYPHWKLJCZC4MXVUFW2BS5EX53TS5A/
Code of Conduct: http://python.org/psf/codeofconduct/


[Python-ideas] Re: Ability to set precedence of classdict (returned from __prepare__) for a metaclass type

2019-10-21 Thread Steve Jorgensen
Anders Hovmöller wrote:
> We try to do the same thing in various libraries. We've settled on using 
> existing
> python and end up with syntax like:
> class MyForm(Form):
> field = Field()
> or in your case
> class Colors(TokenContainer):
> red = Token()
> green = Token()
> blue = Token()
> (this is using tri.token).
> The discussion on creating namespaces seem to match this type of usage more 
> than what
> you've suggested here.

Here's another interesting possible pattern/DSL that I've come up with for my 
value/label case. This pattern doesn't require getting fancy with the classdict 
at all. It does create choices implicitly via name access, but it's the name of 
an attribute of a context object, not the name of a variable in the namespace.

from choices import choices


def test_constructs_with_auto_valued_choices():
# Get choices context for Food choices.
fcc = choices()

# Optionally replace fcc.base with a subclass of fcc.base or
# fcc.mixin here if additional behavior is desirable to have
# within the class body below.

class Food(fcc.base):
# Add a new instance of fcc.base w/ value of 'APPLE' and label
# of None, and create an APPLE class attribute with a value
# of 'APPLE'
fcc.APPLE

# Just as for APPLE above.
fcc.GREEK_YOGURT

# Add an EGG_MCMUFFIN choice and class value-attribute, then
# replace it with a choice that has the same value and a label
# of 'Egg McMuffin' (since instances are immutable).
fcc.EGG_MCMUFFIN %= 'Egg McMuffin'

# Add a choice with value of '~OTHER~' and label of
# not associated with any attribute 'Something else'
fcc.append('~OTHER~', 'Something else')

# After class is defined, unlabeled instances of fcc.base have been
# auto-labeled and upgraded to instances of Food by passing through
# Food.coerce_from(obj).
# The __new__ method behavior of Food has now been locked, and raises
# TypeError for any subsequent attempts to instantiate.

# The default fcc.base class has a value/label namedtuple as a base
# class, so this is valid/successful.
assert tuple(Food) == (
('RED',  'Apple'),
('GREEN','Greek Yogurt'),
('EGG_MCMUFFIN', 'Egg McMuffin'),
)

# Members are instances of Food.
assert tuple(type(food) for food in Food) == (Food, Food)
___
Python-ideas mailing list -- python-ideas@python.org
To unsubscribe send an email to python-ideas-le...@python.org
https://mail.python.org/mailman3/lists/python-ideas.python.org/
Message archived at 
https://mail.python.org/archives/list/python-ideas@python.org/message/4BVORO34Q3CDKBKSMMXIXYWS5FU3LNUA/
Code of Conduct: http://python.org/psf/codeofconduct/


[Python-ideas] Re: PEP 584: Add + and += operators to the built-in dict class.

2019-10-21 Thread Andrew Barnert via Python-ideas
On Oct 20, 2019, at 22:08, Guido van Rossum  wrote:
> 
> Also note that copy() methods are entirely missing from the ABCs. For 
> [Mutable]Sequence and [Mutable]Mapping this is not a coincidence -- there are 
> no methods that create new instances. For [Mutable]Set I'm not sure about the 
> reason -- perhaps it's in analogy of the others, perhaps it's because you can 
> easily create a copy of a set using s | set().

I always thought this went along with the fact that the constructor isn’t part 
of the ABC. For something that duck types as a tuple or list or set all the way 
up to constructing new instances, you can just do type(s)(iter(a)) with the 
same meaning as s.copy(), but you can’t do that for, say, range, where you need 
to understand more about the type than its sequenceness to construct an equal 
one. So there’s no way the mixin can help; if the ABC required any methods that 
returned new instances, every class would have to define all of them.

Another point against Mapping.__add__ (but not MutableMapping.__iadd__): the 
performance cost of copy-merging is acceptable if you know something about them 
beyond the fact that they’re mappings (like when you’re adding a tiny literal 
to a **kw, or you know you’re using persistent sharing HAMTs), but if you 
don’t, it may not be. You could discourage people from writing sum(some 
arbitrary possibly huge mappings) with a check inside sum, but it’s hard to 
discourage people from doing the same thing indirectly.
___
Python-ideas mailing list -- python-ideas@python.org
To unsubscribe send an email to python-ideas-le...@python.org
https://mail.python.org/mailman3/lists/python-ideas.python.org/
Message archived at 
https://mail.python.org/archives/list/python-ideas@python.org/message/B3FNWXBD2C7Q5LCUWDSDIER7HLJDVXGQ/
Code of Conduct: http://python.org/psf/codeofconduct/