[Python-ideas] Re: commonprefix

2024-06-12 Thread Dom Grigonis
This being in `os.path` module suggests that the main intent is to find a 
common prefix of a `path`.

If this is the case, maybe it would be worth instead of:
```
if not isinstance(m[0], (list, tuple)):
m = tuple(map(os.fspath, m))
```
have
```
if not isinstance(m[0], (list, tuple)):
m = [os.fspath(el).split(SEP) for el in m]
…

as now (from tests):
```
commonprefix([b"home:swenson:spam", b"home:swen:spam”]) -> b"home:swen"
```
, which is not a common prefix of a path.

If my suggestion above is valid and it was intended to be used on parts of 
`path`, then it is the right place for it. But it was made too flexible, which 
makes it suitable for general string problems, but error prone for path 
problems.

The way I see it, ideally there should be:
1. string method
2. sequence method
3. path utility

Current `commonprefix` is doing 1 and 2 very well, but 3 is error-prone.

Regards,
dg

> On 13 Jun 2024, at 05:32, Tim Peters  wrote:
> 
> [Rob Cliffe]
> > The os.path.commonprefix function basically returns the common initial
> > characters (if any) shared by a sequence of strings, e.g.
> >  ...
> > It seems to me that this function (or something similar) should not be
> > in os.path, but somewhere else where it would be more visible.
> 
> It's certainly in a strange place ;-)
> 
> >  (1) a str.commonprefix function.  Unfortunately it would have to be
> > used like this
> >  str.commonprefix()
> >  which would make it [I think] the only str function which
> > couldn't be called as a string method.
> 
> Sure it could. like
> 
> astr.commonprefix(*strs)
> 
> to find the longest common prefix among `astr` and the (zero or more) 
> optional arguments.
> 
> > ...
> >One wrinkle: os.patch.commonprefix, if passed an empty
> > sequence, returns an empty STRING.
> >If this function were designed from scratch, it should
> > probably return None.
> 
> Don't think so. An empty string is a valid string too, and is the "obviously 
> correct" common prefix of "abc" and "xyz".
> 
> > I also suspect that this function could be made more efficient.  It
> > sorts the sequence.  While sorting is very fast (thanks, Uncle Tim!) it
> > seems a bit OTT in this case.
> 
> It doesn't sort. It finds the min and the max of all the inputs, as separate 
> operations, and finds the longest common prefix of those teo alone. Apart 
> from the initial min/max calls, the other inputs are never looked at again. 
> It's a matter of logical deduction that if S <= L have K initial characters 
> in common, then every string T with S <= T <= L must have the same K initial 
> characters.
> 
> As a micro-optimization, you might think the min'max could be skipped if 
> there were only two input strings. But then
> 
> for i, c in enumerate(s1):
> if c != s2[i]:
> return s1[:i]
> 
> could blow up with an IndexError if len(s2) < len(s1). As is, that can't 
> happen, because s1 <= s2 is known. At worst, the `for` loop can run to 
> exhaustion (in which case s2.startswith(s1)).
> 
> So. to my eye, there are surprisingly few possibilities for speeding this.
> 
> ___
> 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/6AJN3FXTZMKSBF6KDQYSDSPO2GJOBP6S/
> 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/7K56LVEZLNZMS3DH7S32KY7FWEEZFXOS/
Code of Conduct: http://python.org/psf/codeofconduct/


[Python-ideas] Re: Descriptor __get__ and __set__ argument discrepancy

2023-10-19 Thread Dom Grigonis
Thank you, makes sense. This one has been bugging me every time I worked with 
descriptors.

I even had __set__ method in my Descriptor Base for class attributes, but never 
needed it so didn’t realise.

> On 19 Oct 2023, at 12:09, Antoine Rozo  wrote:
> 
> Hi,
> 
> The __get__ method of descriptors can be called at the class level (that's 
> how methods work) and in that case instance would be None, but owner will 
> always reference the current class.
> 
> __set__ can only be called for instances on that class (`Cls.attr = ...` 
> would redefine the class-attribute and not call the descriptor), so instance 
> can never be None and owner is type(instance).
> 
> Le jeu. 19 oct. 2023 à 09:45, Dom Grigonis  <mailto:dom.grigo...@gmail.com>> a écrit :
> 
> > On 19 Oct 2023, at 10:27, dn via Python-ideas  > <mailto:python-ideas@python.org>> wrote:
> > 
> > On 19/10/2023 19.50, Dom Grigonis wrote:
> >> Thank you,
> >> Good information, thank you. Was not aware of __set_name__.
> > 
> > IIRC that was one of the updates/improvements. Thanks to whomsoever...!
> > 
> > The:
> > 
> >instance.__dict__[self.name <http://self.name/>] = value
> > 
> > may require a bit of thought before it feels comfortable, but it is 
> > significantly easier to understand than what we had to do 'before'.
> I am using `setattr(instance, self.name <http://self.name/>, value)`. But I 
> see that instance.__dict__ is more appropriate in this case.
> 
> 
> > Another surprise, and I've assumed you're asking in the context of [Custom] 
> > Descriptors, is in how many places/functions Python makes use of a 
> > descriptor/descriptor protocol. Yet few of us seem to make use of them in 
> > our application code...
> > (YMMV!)
> I use them more and more.
> 
> 
> However, I was more interested, why doesn't __set__ have an `owner` argument, 
> while `__get__` does. I am aware that this is not an issue at all as one can 
> simply do `inst.__class__`, but I am just curious about the reason for 
> inconsistency.
> 
> Although, answers that I got were very useful.
> 
> DG
> ___
> Python-ideas mailing list -- python-ideas@python.org 
> <mailto:python-ideas@python.org>
> To unsubscribe send an email to python-ideas-le...@python.org 
> <mailto:python-ideas-le...@python.org>
> https://mail.python.org/mailman3/lists/python-ideas.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/64MSMP4FFIT4FHPJQ66RW3OWXSP7RUFC/
>  
> <https://mail.python.org/archives/list/python-ideas@python.org/message/64MSMP4FFIT4FHPJQ66RW3OWXSP7RUFC/>
> Code of Conduct: http://python.org/psf/codeofconduct/ 
> <http://python.org/psf/codeofconduct/>
> 
> 
> -- 
> Antoine Rozo

___
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/JYWMEHUBWSCKS7KAJP3DW46OKJ7BV3IS/
Code of Conduct: http://python.org/psf/codeofconduct/


[Python-ideas] Re: Descriptor __get__ and __set__ argument discrepancy

2023-10-19 Thread Dom Grigonis


> On 19 Oct 2023, at 10:27, dn via Python-ideas  wrote:
> 
> On 19/10/2023 19.50, Dom Grigonis wrote:
>> Thank you,
>> Good information, thank you. Was not aware of __set_name__.
> 
> IIRC that was one of the updates/improvements. Thanks to whomsoever...!
> 
> The:
> 
>instance.__dict__[self.name] = value
> 
> may require a bit of thought before it feels comfortable, but it is 
> significantly easier to understand than what we had to do 'before'.
I am using `setattr(instance, self.name, value)`. But I see that 
instance.__dict__ is more appropriate in this case.


> Another surprise, and I've assumed you're asking in the context of [Custom] 
> Descriptors, is in how many places/functions Python makes use of a 
> descriptor/descriptor protocol. Yet few of us seem to make use of them in our 
> application code...
> (YMMV!)
I use them more and more.


However, I was more interested, why doesn't __set__ have an `owner` argument, 
while `__get__` does. I am aware that this is not an issue at all as one can 
simply do `inst.__class__`, but I am just curious about the reason for 
inconsistency.

Although, answers that I got were very useful.

DG
___
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/64MSMP4FFIT4FHPJQ66RW3OWXSP7RUFC/
Code of Conduct: http://python.org/psf/codeofconduct/


[Python-ideas] Re: Descriptor __get__ and __set__ argument discrepancy

2023-10-19 Thread Dom Grigonis
Thank you,

Good information, thank you. Was not aware of __set_name__.

DG

> On 19 Oct 2023, at 09:28, dn via Python-ideas  wrote:
> 
> On 19/10/2023 18.29, Dom Grigonis wrote:
>> def  __get__(self, instance, owner):
>> def  __set__(self, instance, value):
>> Is there a reason why `__set__` does not have owner in it’s arguments while 
>> `__get__` does?
> 
> Is this a Python Idea?
> 
> You may have only given us a couple of lines, when the scope of the question 
> is much wider...
> 
> Be careful because these mechanisms were updated relatively-recently - and 
> thus there are differences between Python versions!
> 
> 
> From my notes (please see code-example which appears to answer your question):
> 
> The __set_name__() method is a special method in Python that is used in the 
> context of descriptors. It was introduced in Python 3.6 as a part of the 
> Descriptor Protocol.
> 
> The purpose of the __set_name__() method is to allow descriptors to 
> automatically determine and store the name of the attribute they are assigned 
> to within the class. This method is called once during the creation of the 
> descriptor instance, and it receives two arguments: the owner class and the 
> name of the attribute.
> 
> By implementing the __set_name__() method in a descriptor, you can access and 
> store the name of the attribute to which the descriptor is assigned. This can 
> be useful when you want to associate the descriptor with the attribute name 
> or perform any additional setup based on the attribute name.
> 
> Here's an example to illustrate the usage of __set_name__():
> 
> ```python
> class Descriptor:
>def __set_name__(self, owner, name):
>self.name = name
> 
>def __get__(self, instance, owner):
>if instance is None:
>return self
>return instance.__dict__.get(self.name)
> 
>def __set__(self, instance, value):
>instance.__dict__[self.name] = value
> 
> class MyClass:
>attribute = Descriptor()
> 
> obj = MyClass()
> obj.attribute = 42
> print(obj.attribute)  # Output: 42
> ```
> 
> In the above code, the Descriptor class defines the __set_name__() method. 
> When the attribute descriptor is assigned to the attribute attribute of the 
> MyClass class, the __set_name__() method is automatically called with the 
> owner class (MyClass) and the attribute name (attribute). Inside this method, 
> we store the attribute name in the descriptor instance.
> 
> Later, when we set obj.attribute = 42, the descriptor's __set__() method is 
> called, and the value is stored in the instance's __dict__ attribute using 
> the previously stored attribute name.
> 
> By using __set_name__(), descriptors can dynamically associate themselves 
> with the attribute names they are assigned to, providing more flexibility and 
> customization.
> 
> 
> Web.Refs:
> https://docs.python.org/3/howto/descriptor.html
> https://docs.python.org/3/reference/datamodel.html#descriptors
> 
> -- 
> Regards,
> =dn
> ___
> 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/L7WZA7GEW3TPYUA4NF6POHDL2FSF5TIY/
> 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/GXXHZ4KPC5OJDKGMMOWSE6SH44EAHJYK/
Code of Conduct: http://python.org/psf/codeofconduct/


[Python-ideas] Descriptor __get__ and __set__ argument discrepancy

2023-10-18 Thread Dom Grigonis
Hi all,

Quick question.

def __get__(self, instance, owner):
def __set__(self, instance, value):
Is there a reason why `__set__` does not have owner in it’s arguments while 
`__get__` does?

Regards,
DG


___
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/RUJ32TCAEQONJULYXBYEIK53AETRBE3P/
Code of Conduct: http://python.org/psf/codeofconduct/


[Python-ideas] Non-aware operators PEP505

2023-10-16 Thread Dom Grigonis
Hi all,

Just want to follow up on discussions from before by saying that I came to a 
conclusion that from my POV non-aware operators would be an excellent addition 
to python.

The number of times that I need to write:
pal = None if self.pal is None else self.pal.rgb_to_cmy()
or alternatively:
pal = None
if self.pal is None:
pal = self.pal.rgb_to_cmy()
is still fairly high.

The first one is one-line, but its readability is, although not the worst, but 
is not satisfactory in the context of other practices I have employed.

The second one has good readability, but it takes 3 lines for operation, which 
I think shouldn’t take more than 1 line.

——

Now following up on my thoughts on deferred evaluation this case could be 
solved by its side effect, which is allowing user to control evaluation order. 
However, I think it would be more suitable for corner cases and more complex 
tool building due to its verbosity and readability, which I think would be 
better than many corner-case hacks, but nowhere as elegant as say non-aware 
operator syntax.

So I think regardless of whether deferred evaluation is ever implemented, this 
PEP( https://peps.python.org/pep-0505/ ) 
could be a very useful addition given the frequency of such cases.

——

Even a minimal implementation of it for would be very useful, say simple binary 
operator with __has_value__ object protocol.

——

Maybe someone knows a better way to write the example above?

Regards,
DG


___
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/XE4J7RF5CETQZRZKQHMQ3CELHR2OAOQZ/
Code of Conduct: http://python.org/psf/codeofconduct/


[Python-ideas] Re: SyntaxError: cannot use assignment expressions with attribute

2023-10-09 Thread Dom Grigonis
I just want to note that this is just a gentle suggestion/observation, in case 
this wasn’t done yet.

I am not pushing this.

——

All good points, thank you.

——

Why would this not be a good option? 1 extra line compared to walrus, but no 
DRY issue.
with open(“fn") as f:
while True:
line = f.readline()
if line and check(line):
process(line)
else:
break
DG

> On 9 Oct 2023, at 15:52, Stephen J. Turnbull 
>  wrote:
> 
> Dom Grigonis writes:
> 
>> Mistake, late night. I just meant to portray initialisation via
>> walrus inside statement, nothing more. It doesn’t work with while
>> loop.
> 
> It *does* work with a while loop, just not that one.  See below.  The
> problem is that you're writing new code full of trash you don't need
> to explain the concept.  Keep these examples as simple as possible.
> For example, my "pass" example is too simple if you want to show how
> the walrus can save typing because it doesn't save any lines of code;
> you need something a little more complicated to demonstrate that
> saving.
> 
> In the progress of any proposal to acceptance, at some point someone
> is going to say, "I see that it works and solves a theoretical
> problem, but who would ever use it?"  At that point you go into a
> large body of code such as the Python standard library or numpy to
> find realistic examples.  But that's old code, and only needed to
> demonstrate actual utility.
> 
>> Generally, this would be useful for all examples of
>> https://peps.python.org/pep-0572/ <https://peps.python.org/pep-0572/>
>> , where “initial” value is an attribute or dictionary item.
> 
> That's not the question though.  The question is are those examples
> themselves frequently useful.  And that's when you go find them in the
> stdlib.
> 
>> I see. Could you give an example of this? I vaguely remember this
>> sometimes being the case, but can not find anything now on this in
>> relation to walrus operator. Is there no way to bring that
>> execution within the body without walrus operator?
> 
> The problem is code like this:
> 
>with open("a_file") as f:
>while (line := f.readline())
>if check(line):
>process(line)
>else:
>break
> 
> There is no way to do that without an assignment, and without the
> walrus you need an assignment before the while, and the same
> assignment within the loop body.  Is that a big deal?  No.  In fact, I
> have never used the walrus operator in anger, nor wanted to.  I'm just
> as happy to write
> 
>with open("a_file") as f:
>line = f.readline()
>while (line)
>if check(line):
>process(line)
>else:
>break
>line = f.readline()
> 
> But some people find loop-and-a-half extremely ugly, and while I
> differ on "extremely", I can't deny that it's ugly.
> 
> You *could* do this for small files with
> 
>with open("a_file") as f:
>lines = f.readlines()
>for (line in lines):
>if check(line):
>process(line)
>else:
>break
> 
> but that's not possible with an infinite iterable, undesireable for
> most non-file streams, etc.
> 
> Re "simple examples", see why I used the "if check()" stuff?  If I
> wasn't going to talk about infinite iterables and pausing external
> streams, that would just be (potentially wrong!) complexity that
> doesn't help explain anything.
> 
> Steve
> 
> 

___
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/B2TLFMOOYMRRXCRJLLFV6F5URU4OPO3J/
Code of Conduct: http://python.org/psf/codeofconduct/


[Python-ideas] Re: SyntaxError: cannot use assignment expressions with attribute

2023-10-09 Thread Dom Grigonis
On 9 Oct 2023, at 08:58, Stephen J. Turnbull 
 wrote:
> ...
> Not sure what you're getting at here, that's an infloop.  Did you mean
> something like this:
> 
>class A:
>def func(self):
>while (self.a := self.a += 1) < 5:
>pass
>return self.a
Mistake, late night. I just meant to portray initialisation via walrus inside 
statement, nothing more. It doesn’t work with while loop. The intention was 
this, which is also principal use-case from previous reply:
class A:
def func(self, string):
if self.a := re.match('.*', string):
print(self.a)
return self.a.group()
Generally, this would be useful for all examples of
https://peps.python.org/pep-0572/ 
, where “initial” value is an attribute or dictionary item.

>> Same argument as for “walrus” operator itself - convenient
>> feature. Or is there more to it?
> 
> There's more to it.  The loop and a half construct, where you execute
> the body of the loop once outside the loop for some reason is widely
> considered a really big wart (DRY failure).  The walrus allows us to
> eliminate most of those.
> 
> On the other hand, an assignment and a return statement are two
> different things; it's not a DRY viotion to have the same identifier
> in both.
I see. Could you give an example of this? I vaguely remember this sometimes 
being the case, but can not find anything now on this in relation to walrus 
operator. Is there no way to bring that execution within the body without 
walrus operator?

>> I was actually surprised that this didn’t work - I thought that
>> this operator is a literal composite of assignment and “retriever",
>> rather than having it’s own restrictive logic.
> 
> This is a common practice in Python development.  Try a little bit of
> a new idea, avoid engineering, and expand later if that seems useful
> too.
Fair.

>> If it doesn’t break anything, doesn’t have any undesirable side
>> effects and community likes it, then could be a good addition.
> 
> "Community likes it" is a null predicate, very hard to verify in edge
> cases.  When the support in the community is strong enough that
> "community likes it" is common knowledge, it's always the case that
> there are objective reasons why it's a good thing.
> 
> All additions have a 0 * infinity cost: a negligible cost of learning
> (for one user) times *all* the users.
Ok, thanks.

DG



___
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/JXUUX7EDHM73RZQVGEUADS7X6AJSB3CB/
Code of Conduct: http://python.org/psf/codeofconduct/


[Python-ideas] Re: SyntaxError: cannot use assignment expressions with attribute

2023-10-08 Thread Dom Grigonis

> Having:
> 
>self.mode = self.mode_valid(mode)
>return self.mode
> 
> isn't too bad.

No, not bad at all. But to me, being able to use walrus would be convenient.

———

This nuance can also be encountered in “principal use-case”. E.g.:
class A:
def func(self):
while (self.a := 1) < 5:
self.a += 1
return self.a

A().func()
Could be useful in iterator protocol implementations, where/or_where state is 
managed with property setters managing objects that implement  custom 
`__iadd__`, etc or just simply convenience as in my former example.

Same argument as for “walrus” operator itself - convenient feature. Or is there 
more to it?

———

I was actually surprised that this didn’t work - I thought that this operator 
is a literal composite of assignment and “retriever", rather than having it’s 
own restrictive logic.

Could be a reason for it, maybe to avoid some undesirable mis-usage. But I 
can’t see it. Any issues arising from such construct would be the same issues 
as for:
expr = 1
expr
This could be an actual assignment + retrieval of left-hand-side, then it would 
work generically for all constructs, such as:
a()[‘a'] := 1
a().attr := 1
If walrus currently has its own specific logic, this would integrate it nicely 
into assignment operator. Then it would benefit automatically from any language 
extension that makes use of it.

Or is it already it, just with added restrictions?

All in all, I think would be a generalisation of a convenience feature, which 
doesn’t invent anything new, but extends its convenience to more general 
application.

These are my thoughts, whether it’s worthwhile and sensible - I have no idea.

If it doesn’t break anything, doesn’t have any undesirable side effects and 
community likes it, then could be a good addition.

Regards,
DG

P.S. Deferred evaluation will be able to handle this one too___
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/VGMMI4PNTSW4AD22EESF62DWUOMJ3RHK/
Code of Conduct: http://python.org/psf/codeofconduct/


[Python-ideas] SyntaxError: cannot use assignment expressions with attribute

2023-10-08 Thread Dom Grigonis
Is there a reason why this is not allowed?
return (self.mode := self.mode_valid(mode))
___
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/EULXNH2OQOY72LDAMQSRLA3JKU55UBG6/
Code of Conduct: http://python.org/psf/codeofconduct/


[Python-ideas] Re: Extract variable name from itself

2023-09-28 Thread Dom Grigonis
Just want to clear things out that I did not respond to immediately due to 
obvious reasons.

> On 25 Sep 2023, at 07:44, Tiago Illipronti Girardi  
> wrote:
> Can you please stop manufacturing consent?
It is not what you stated it is. It was something different.

An example of manufacturing consent was:
> and I doubt it was only to me

In the context of:
> On 24 Sep 2023, at 22:32, Tiago Illipronti Girardi  
> wrote:
> Appling my specific advice elsewhere is at most cute, in this case it was 
> offensive, and I doubt it was only to me.


And what was being referred to was not offensive, only unless badly 
misinterpreted. An accusation as such on a public group is. It was also 
offensive to people who you implicitly involved in supposedly supporting your 
opinion without their consent.

Regards,
DG


> Em dom., 24 de set. de 2023 às 21:06, Dom Grigonis  <mailto:dom.grigo...@gmail.com>> escreveu:
> What is your position on this?
> 
> Do you think that such thing is worth having?
> 
> If yes, do any of the 3 final options seem sensible to you?
> 
> > On 25 Sep 2023, at 02:39, Chris Angelico  > <mailto:ros...@gmail.com>> wrote:
> > 
> > On Mon, 25 Sept 2023 at 07:05, Dom Grigonis  > <mailto:dom.grigo...@gmail.com>> wrote:
> >> What I meant is that functions in __builtins__ are low level, with 
> >> functionality which is hidden from the user.
> >> 
> > 
> > What does that even mean?
> > 
> > ChrisA
> > ___
> > Python-ideas mailing list -- python-ideas@python.org 
> > <mailto:python-ideas@python.org>
> > To unsubscribe send an email to python-ideas-le...@python.org 
> > <mailto:python-ideas-le...@python.org>
> > https://mail.python.org/mailman3/lists/python-ideas.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/ERAO66OAI73EO4YYCG3ODI3TPFSKYUEG/
> >  
> > <https://mail.python.org/archives/list/python-ideas@python.org/message/ERAO66OAI73EO4YYCG3ODI3TPFSKYUEG/>
> > Code of Conduct: http://python.org/psf/codeofconduct/ 
> > <http://python.org/psf/codeofconduct/>
> 
> ___
> Python-ideas mailing list -- python-ideas@python.org 
> <mailto:python-ideas@python.org>
> To unsubscribe send an email to python-ideas-le...@python.org 
> <mailto:python-ideas-le...@python.org>
> https://mail.python.org/mailman3/lists/python-ideas.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/6ILMQ4PB5W6MAJZZALK47QDFOYYM4M4X/
>  
> <https://mail.python.org/archives/list/python-ideas@python.org/message/6ILMQ4PB5W6MAJZZALK47QDFOYYM4M4X/>
> Code of Conduct: http://python.org/psf/codeofconduct/ 
> <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/DRUFRQ4SSXZ2GPJV3NTMKVRGQKFKDGG3/
Code of Conduct: http://python.org/psf/codeofconduct/


[Python-ideas] Re: Extract variable name from itself

2023-09-25 Thread Dom Grigonis
I think a lot has been said by this time and I have nothing to add.

If this is something that is of value, I am sure it will be picked up when the 
time is right.

One last thing that I think could be of some use is a poll:

https://take.supersurvey.com/QCVZKTDY0 

It will not take more than few seconds. Appreciate your time.

Regards,
DG


___
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/65OSC2LGO44SNQCKH5VP6I2UNZ5I64AD/
Code of Conduct: http://python.org/psf/codeofconduct/


[Python-ideas] Re: Extract variable name from itself

2023-09-24 Thread Dom Grigonis
What is your position on this?

Do you think that such thing is worth having?

If yes, do any of the 3 final options seem sensible to you?

> On 25 Sep 2023, at 02:39, Chris Angelico  wrote:
> 
> On Mon, 25 Sept 2023 at 07:05, Dom Grigonis  wrote:
>> What I meant is that functions in __builtins__ are low level, with 
>> functionality which is hidden from the user.
>> 
> 
> What does that even mean?
> 
> ChrisA
> ___
> 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/ERAO66OAI73EO4YYCG3ODI3TPFSKYUEG/
> 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/6ILMQ4PB5W6MAJZZALK47QDFOYYM4M4X/
Code of Conduct: http://python.org/psf/codeofconduct/


[Python-ideas] Re: Extract variable name from itself

2023-09-24 Thread Dom Grigonis

> 'Esoteric' means something hidden, it is the exact opposite of 'we all know 
> about'
What I meant is that functions in __builtins__ are low level, with 
functionality which is hidden from the user. So my point is that it seems like 
an appropriate place for nameof(). After all, f’{v!}’ applies functions to 
v from builtin namespace: str/repr/ascii.

> Em dom., 24 de set. de 2023 às 16:11, Dom Grigonis  <mailto:dom.grigo...@gmail.com>> escreveu:
> 
> 
>> On 24 Sep 2023, at 19:27, Tiago Illipronti Girardi > <mailto:tiagoigira...@gmail.com>> wrote:
>> 
>> There definitely is a miscommunication:
>> 
>> The 2 first options was me spitballing an alternative against the third.
>> 
>> The not reinventing the wheel remark was me saying that the particular 
>> example that you gave *on that particular message* can already be done.
> I know, I just applied your advice in a different place. :)
> 
>> Also the case 2 f'{name!i}', I suggested as an extension of the current 
>> formatting paradigm, but is also the same as `f{name=}` except that you 
>> don't format the *value*,
>> so I *imagine* (that word pulling more weight than I do at the gym, mind 
>> you) would be trivial to implement. It *needs* editor support regardless.
> So just to double check. You think f’{name!i}’ would be better than simply 
> nameof() builtin?
> 
> I have no problems with either b) or c), but I like c) better. As you said:
> print('In this context, variable', 'name', 'means an esoteric thing that we 
> all know about’)
> 
> Maybe it would be sensible not to couple ‘esoteric` thing with non-esoteric 
> ones and find its place among other unique functionality providing things, 
> such as id, type, exec, etc.
> 
> 
>> While I would be very glad if my opinion is adopted by the community, do not 
>> substitute my opinion for the community's.
>> 
>> Em dom., 24 de set. de 2023 às 12:29, Dom Grigonis > <mailto:dom.grigo...@gmail.com>> escreveu:
>> I think the separation is needed between the 2:
>> 
>> a) identifier name
>> b) expression text
>> 
>> I think there is a mix-up between these 2 which causes some confusion (at 
>> least to me). Wanting both made me cling to f-strings as they currently do 
>> b) in ‘postfix=' and a) can be extracted from it.
>> 
>> —
>> 
>> I think having b) will be convenient to extract given/when/if/please 
>> deferred evaluation is implemented:
>> a = `expr`
>> print(a.__expr_text__)  # ‘expr'
>> —
>> 
>> So I think the focus here is a). I think this is what you are having in 
>> mind, while I think about both - thus slight miscommunication.
>> 
>> And for it I currently see 3 options:
>> 1. typing.ID['name']
>>  I think this one is too verbose for what it is. Also requiring an import
>> 2. ‘{name!i}’
>>  This one is sensible (and I think is better than my prefix=)
>> 3. nameof(name)
>>  But I am leaning towards this one.
>>  Pros:
>>  * it is not coupled with either string formatting or typing. 
>>  * C# guys most likely gave some thought into it so the 
>> resulting output can potentially be modelled after it. That is: to either 
>> return identifier name, or the name of the attribute.
>>  * Also, this would be in line with your suggestion of not 
>> reinventing the wheel.
>>  * Finally, there would be no extra editor work.
>>  Cons:
>>  * Extra name in global namespace
>>  * Any thoughts why this isn’t a good option?
>> 
>> Regards,
>> DG
>> 
>>> On 24 Sep 2023, at 17:44, Tiago Illipronti Girardi >> <mailto:tiagoigira...@gmail.com>> wrote:
>>> 
>>> or
>>> 
>>> print('{a=} and b={a}')
>>> 
>>> This already exists. Kindly stop reinventing the wheel.
>>> 
>>> the thing that does not exist now is:
>>> 
>>> print('In this context, variable', 'name', 'means an esoteric thing that we 
>>> all know about')
>>> 
>>> where `'name'` can be substituted easily (the 'nameof' case) but it could 
>>> be, as an example:
>>> 
>>> print('In this context, variable {name!i} means an esoteric thing that we 
>>> all know about')
>>> 
>>> (my favorite, but interpreter maintenance costs trumps my preferences)
>>> or could be done as:
>>> 
>>> print('In this context, variable', typing.ID['name'], 'means an esoteric 
>>> thing that we all know about')
>>> 
>&g

[Python-ideas] Re: Extract variable name from itself

2023-09-24 Thread Dom Grigonis


> On 24 Sep 2023, at 19:27, Tiago Illipronti Girardi  
> wrote:
> 
> There definitely is a miscommunication:
> 
> The 2 first options was me spitballing an alternative against the third.
> 
> The not reinventing the wheel remark was me saying that the particular 
> example that you gave *on that particular message* can already be done.
I know, I just applied your advice in a different place. :)

> Also the case 2 f'{name!i}', I suggested as an extension of the current 
> formatting paradigm, but is also the same as `f{name=}` except that you don't 
> format the *value*,
> so I *imagine* (that word pulling more weight than I do at the gym, mind you) 
> would be trivial to implement. It *needs* editor support regardless.
So just to double check. You think f’{name!i}’ would be better than simply 
nameof() builtin?

I have no problems with either b) or c), but I like c) better. As you said:
print('In this context, variable', 'name', 'means an esoteric thing that we all 
know about’)

Maybe it would be sensible not to couple ‘esoteric` thing with non-esoteric 
ones and find its place among other unique functionality providing things, such 
as id, type, exec, etc.


> While I would be very glad if my opinion is adopted by the community, do not 
> substitute my opinion for the community's.
> 
> Em dom., 24 de set. de 2023 às 12:29, Dom Grigonis  <mailto:dom.grigo...@gmail.com>> escreveu:
> I think the separation is needed between the 2:
> 
> a) identifier name
> b) expression text
> 
> I think there is a mix-up between these 2 which causes some confusion (at 
> least to me). Wanting both made me cling to f-strings as they currently do b) 
> in ‘postfix=' and a) can be extracted from it.
> 
> —
> 
> I think having b) will be convenient to extract given/when/if/please deferred 
> evaluation is implemented:
> a = `expr`
> print(a.__expr_text__)  # ‘expr'
> —
> 
> So I think the focus here is a). I think this is what you are having in mind, 
> while I think about both - thus slight miscommunication.
> 
> And for it I currently see 3 options:
> 1. typing.ID['name']
>   I think this one is too verbose for what it is. Also requiring an import
> 2. ‘{name!i}’
>   This one is sensible (and I think is better than my prefix=)
> 3. nameof(name)
>   But I am leaning towards this one.
>   Pros:
>   * it is not coupled with either string formatting or typing. 
>   * C# guys most likely gave some thought into it so the 
> resulting output can potentially be modelled after it. That is: to either 
> return identifier name, or the name of the attribute.
>   * Also, this would be in line with your suggestion of not 
> reinventing the wheel.
>   * Finally, there would be no extra editor work.
>   Cons:
>   * Extra name in global namespace
>   * Any thoughts why this isn’t a good option?
> 
> Regards,
> DG
> 
>> On 24 Sep 2023, at 17:44, Tiago Illipronti Girardi > <mailto:tiagoigira...@gmail.com>> wrote:
>> 
>> or
>> 
>> print('{a=} and b={a}')
>> 
>> This already exists. Kindly stop reinventing the wheel.
>> 
>> the thing that does not exist now is:
>> 
>> print('In this context, variable', 'name', 'means an esoteric thing that we 
>> all know about')
>> 
>> where `'name'` can be substituted easily (the 'nameof' case) but it could 
>> be, as an example:
>> 
>> print('In this context, variable {name!i} means an esoteric thing that we 
>> all know about')
>> 
>> (my favorite, but interpreter maintenance costs trumps my preferences)
>> or could be done as:
>> 
>> print('In this context, variable', typing.ID['name'], 'means an esoteric 
>> thing that we all know about')
>> 
>> which wouldn't change the interpreter at all, (but would change the stdlib).
>> 
>> Either way, the 'nameof'-support needs editor support, because it is an 
>> *editing* use case, the interpreter just doesn't care.
>> (It could, but it *can't* do anything without the *editor* responding to it)
>> 
>> Em dom., 24 de set. de 2023 às 11:13, Dom Grigonis > <mailto:dom.grigo...@gmail.com>> escreveu:
>> 
>> 
>>> On 24 Sep 2023, at 16:42, Stephen J. Turnbull 
>>> >> <mailto:turnbull.stephen...@u.tsukuba.ac.jp>> wrote:
>>> 
>>> Dom Grigonis writes:
>>> 
>>>>> But it's far from concise
>>>> What could be more concise?
>>> 
>>> A notation where you don't have to repeat a possibly long expression.
>>> For example, numerical positions like 

[Python-ideas] Re: Extract variable name from itself

2023-09-24 Thread Dom Grigonis
I think the separation is needed between the 2:

a) identifier name
b) expression text

I think there is a mix-up between these 2 which causes some confusion (at least 
to me). Wanting both made me cling to f-strings as they currently do b) in 
‘postfix=' and a) can be extracted from it.

—

I think having b) will be convenient to extract given/when/if/please deferred 
evaluation is implemented:
a = `expr`
print(a.__expr_text__)  # ‘expr'
—

So I think the focus here is a). I think this is what you are having in mind, 
while I think about both - thus slight miscommunication.

And for it I currently see 3 options:
1. typing.ID['name']
I think this one is too verbose for what it is. Also requiring an import
2. ‘{name!i}’
This one is sensible (and I think is better than my prefix=)
3. nameof(name)
But I am leaning towards this one.
Pros:
* it is not coupled with either string formatting or typing. 
* C# guys most likely gave some thought into it so the 
resulting output can potentially be modelled after it. That is: to either 
return identifier name, or the name of the attribute.
* Also, this would be in line with your suggestion of not 
reinventing the wheel.
* Finally, there would be no extra editor work.
Cons:
* Extra name in global namespace
* Any thoughts why this isn’t a good option?

Regards,
DG

> On 24 Sep 2023, at 17:44, Tiago Illipronti Girardi  
> wrote:
> 
> or
> 
> print('{a=} and b={a}')
> 
> This already exists. Kindly stop reinventing the wheel.
> 
> the thing that does not exist now is:
> 
> print('In this context, variable', 'name', 'means an esoteric thing that we 
> all know about')
> 
> where `'name'` can be substituted easily (the 'nameof' case) but it could be, 
> as an example:
> 
> print('In this context, variable {name!i} means an esoteric thing that we all 
> know about')
> 
> (my favorite, but interpreter maintenance costs trumps my preferences)
> or could be done as:
> 
> print('In this context, variable', typing.ID['name'], 'means an esoteric 
> thing that we all know about')
> 
> which wouldn't change the interpreter at all, (but would change the stdlib).
> 
> Either way, the 'nameof'-support needs editor support, because it is an 
> *editing* use case, the interpreter just doesn't care.
> (It could, but it *can't* do anything without the *editor* responding to it)
> 
> Em dom., 24 de set. de 2023 às 11:13, Dom Grigonis  <mailto:dom.grigo...@gmail.com>> escreveu:
> 
> 
>> On 24 Sep 2023, at 16:42, Stephen J. Turnbull 
>> > <mailto:turnbull.stephen...@u.tsukuba.ac.jp>> wrote:
>> 
>> Dom Grigonis writes:
>> 
>>>> But it's far from concise
>>> What could be more concise?
>> 
>> A notation where you don't have to repeat a possibly long expression.
>> For example, numerical positions like regular expressions.  Consider
>> this possible notation:
>> 
>>f'There are {count} expression{pluralize(count)} denoted by {=0}.'
>> 
>> Otherwise it isn't great, but it's definitely concise.  In the
>> simplest case you could omit the position:
>> 
>>f'{=} is {count} at this point in the program.'
> Hmmm...
> 
>>>> and violates DRY -- it doesn't solve the problem of the first
>>>> draft typo.
>> 
>>> And how is “postfix =“ different?
>> 
>> You *can't* use different identifiers for the name and value in
>> "postfix =": the same text is used twice, once as a string and one as
>> an identifier.
> I see what you mean, but this property is arguably intrinsic to what it is. 
> And is part of f-strings vs explicit formatting property too:
> variable = 1
> print(f'{variable=} and b={variable}')
> # VS
> msg = 'variable={v} and b={v}'
> print(msg.format(v=variable))
> Especially, where msg can be pre-stored and reused. Then maybe not making it 
> f-string only is a better idea. So that one can do:
> msg = '{a!i}={a} and b={a}'
> print(msg.format(a=variable))
> 
> 
> 
> 

___
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/SWJ5YHQWHLRW2YKGUDIRYIIXTA43QPMI/
Code of Conduct: http://python.org/psf/codeofconduct/


[Python-ideas] Re: Extract variable name from itself

2023-09-24 Thread Dom Grigonis


> On 24 Sep 2023, at 17:23, Chris Angelico  wrote:
> 
> On Mon, 25 Sept 2023 at 00:15, Dom Grigonis  wrote:
>> I see what you mean, but this property is arguably intrinsic to what it is. 
>> And is part of f-strings vs explicit formatting property too:
>> 
>> variable = 1
>> print(f'{variable=} and b={variable}')
>> # VS
>> msg = 'variable={v} and b={v}'
>> print(msg.format(v=variable))
>> 
>> Especially, where msg can be pre-stored and reused.
> 
> What do you mean by that? Are you suggesting that there's a massive
> cost in constructing a string literal and thus reusing it with
> .format() is more efficient than an f-string? Because that's, uhh,
> kinda not the point of str.format().
That was in response to it violating DRY. Just pointed out that it is intrinsic 
to the wider scope of how things work in different ways of formatting and for 
it to be completely satisfied, str.format can be used as opposed to f-strings. 
It was about DRY, not efficiency.

> And if that isn't what you mean, what is it? Your posts are often
> distinctly unclear. I get the impression that you think everyone else
> understands your idea.

Apologies. Noted.___
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/23DNNUYD2EYKSZPCHRSF3CTGZYR3XEEK/
Code of Conduct: http://python.org/psf/codeofconduct/


[Python-ideas] Re: Extract variable name from itself

2023-09-24 Thread Dom Grigonis


> On 24 Sep 2023, at 16:42, Stephen J. Turnbull 
>  wrote:
> 
> Dom Grigonis writes:
> 
>>> But it's far from concise
>> What could be more concise?
> 
> A notation where you don't have to repeat a possibly long expression.
> For example, numerical positions like regular expressions.  Consider
> this possible notation:
> 
>f'There are {count} expression{pluralize(count)} denoted by {=0}.'
> 
> Otherwise it isn't great, but it's definitely concise.  In the
> simplest case you could omit the position:
> 
>f'{=} is {count} at this point in the program.'
Hmmm...

>>> and violates DRY -- it doesn't solve the problem of the first
>>> draft typo.
> 
>> And how is “postfix =“ different?
> 
> You *can't* use different identifiers for the name and value in
> "postfix =": the same text is used twice, once as a string and one as
> an identifier.
I see what you mean, but this property is arguably intrinsic to what it is. And 
is part of f-strings vs explicit formatting property too:
variable = 1
print(f'{variable=} and b={variable}')
# VS
msg = 'variable={v} and b={v}'
print(msg.format(v=variable))
Especially, where msg can be pre-stored and reused. Then maybe not making it 
f-string only is a better idea. So that one can do:
msg = '{a!i}={a} and b={a}'
print(msg.format(a=variable))




___
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/VV7FFVBVTXCAOI6OQVHN3DZIIM5RVPLT/
Code of Conduct: http://python.org/psf/codeofconduct/


[Python-ideas] Re: Extract variable name from itself

2023-09-24 Thread Dom Grigonis

> But it's far from concise
What could be more concise?

> and
> violates DRY -- it doesn't solve the problem of the first draft typo.
And how is “postfix =“ different?

> I don't see it as elegant the way "postfix =" is.
Agreed.

DG
___
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/MJ6FVYOKOLGGHSHAEOGCVNCGSRY42M44/
Code of Conduct: http://python.org/psf/codeofconduct/


[Python-ideas] Re: Extract variable name from itself

2023-09-23 Thread Dom Grigonis
I haven’t given much thought regarding the syntax. The prefix “=“ just popped 
into my mind and I went along with it to use in my examples. The point was that 
f-strings are potentially a good place to implement such thing.

By “elegant", I wasn’t talking about the syntax. It was more about the benefits 
of it being well integrated python construct, which is subject to a parser and 
is a python code by all standards and it fitting in that place sensibly given 
what it is.

Regards,
DG

> On 24 Sep 2023, at 05:15, Stephen J. Turnbull 
>  wrote:
> 
> Dom Grigonis writes:
> 
>>>>>> Eric Smith wrote:
>>> Since I wrote that commit: no one is saying it’s impossible or
>>> overly difficult,
> 
>> To be honest it is exactly what was being said.
> 
> Sure ... about an unclearly expressed early version of the proposal,
> that seemed to ask "given an object x, tell me the name of x".  In the
> end, I don't think there was any disagreement that doing that reliably
> is indeed impossible.  But if someone has written that the #nameof
> version of the proposal is impossible to implement, that is not
> representative of what most of us think or have said.
> 
>> What I think is that it would be an elegant feature if it was
>> implemented at python level.
> 
> The postfix '=' flag is elegant by anyone's standard, I think: it
> provides immediately useful, though limited, functionality, with no
> waste, and is automatically fit for purpose because it satisfies DRY.
> And it is mnemonic in the sense that you may have to look it up to
> write it, but once you've learned it, you will recognize it when you
> see it in unfamiliar code because it "looks like" what it produces.
> 
> The proposed prefix '=' flag is much less attractive to me on all
> counts above, except that it's quite mnemonic.
> 
> Steve

___
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/IQKEAWZQYHZECH74BTXBO2T4VF44ZKAB/
Code of Conduct: http://python.org/psf/codeofconduct/


[Python-ideas] Re: Extract variable name from itself

2023-09-23 Thread Dom Grigonis
> Since I wrote that commit: no one is saying it’s impossible or overly 
> difficult,

To be honest it is exactly what was being said.

>  just that the benefit of having it doesn’t justify the cost of adding it.
I can understand that.

> I understand that you think it’s worth the cost.
No, I don’t think that. I wrote here to find that out.

What I think is that it would be an elegant feature if it was implemented at 
python level.

Thanks for reply,
DG

> On 24 Sep 2023, at 02:24, Eric V. Smith  wrote:
> 
> 
> 
>> On Sep 23, 2023, at 5:37 PM, Dom Grigonis  wrote:
>> 
>> It seems that my guess was correct. There was a commit, when only the first 
>> part was working:
>> 
>> https://github.com/python/cpython/pull/13123/commits/67977672360659f203664d23cfc52b5e07e4381a
>>  
>> <https://github.com/python/cpython/pull/13123/commits/67977672360659f203664d23cfc52b5e07e4381a>
> Since I wrote that commit: no one is saying it’s impossible or overly 
> difficult, just that the benefit of having it doesn’t justify the cost of 
> adding it. Costs include implementation, testing, teaching, cognitive load on 
> all readers, etc.
> 
> I understand that you think it’s worth the cost. Others, including me, do not.
> 
> Eric 
> 
>> 
>> So it does seem that it can be done manageably, while all editors with 
>> f-string support would benefit instantaneously without extra effort or 
>> unnecessary complications such as `typing` library.
>> 
>> Regards,
>> DG
>> 
>>> On 23 Sep 2023, at 23:55, Dom Grigonis >> <mailto:dom.grigo...@gmail.com>> wrote:
>>> 
>>>> the output will have the expression text
>>> This is exactly what I want. If there was an extra check for validity at 
>>> parser level, it is a plus.
>>> 
>>>> You want to produce a name, that is an identifier 
>>>> <https://docs.python.org/3/reference/lexical_analysis.html#identifiers>. 
>>> Not necessarily, I want the first part of f’{expr=}’.
>>> There are outputs:
>>> a) `expr=repr(expr)`
>>> b) `repr(expr)`
>>> 
>>> why is it a bad idea to have:
>>> c) `expr` without `repr(expr)`?
>>> 
>>> This does cover `identifier only` case as well, but is not limited to it.
>>> 
>>> Is it difficult to achieve? Apologies if I am missing something, but if you 
>>> know the workings of python, could you point me to where f’{expr=}' is 
>>> parsed and compiled?
>>> 
>>> Obviously I might be wrong, but it is difficult to believe that it is done 
>>> in such way, that I can have B, A, but not A without B. Would appreciate 
>>> if you convinced me with some support for your rather strong statements.
>>> 
>>> Regards,
>>> DG
>>> 
>>>> On 23 Sep 2023, at 23:18, Tiago Illipronti Girardi 
>>>> mailto:tiagoigira...@gmail.com>> wrote:
>>>> 
>>>> I think I did something wrong and we are responding to one another instead 
>>>> of the list, please correct this if you can.
>>>> 
>>>> Let's start with `f'{name=}'`. This is from the docs 
>>>> <https://docs.python.org/3/reference/lexical_analysis.html#f-strings> (the 
>>>> link has the docs for f-strings, so read it):
>>>> 
>>>> When the equal sign '=' is provided, the output will have the expression 
>>>> text, the '=' and the evaluated value. Spaces after the opening brace '{', 
>>>> within the expression and after the '=' are all retained in the output. By 
>>>> default, the '=' causes the repr() 
>>>> <https://docs.python.org/3/library/functions.html#repr> of the expression 
>>>> to be provided, unless there is a format specified. When a format is 
>>>> specified it defaults to the str() 
>>>> <https://docs.python.org/3/library/stdtypes.html#str> of the expression 
>>>> unless a conversion '!r' is declared.
>>>> 
>>>> That's not what you want. You want to produce a name, that is an 
>>>> identifier 
>>>> <https://docs.python.org/3/reference/lexical_analysis.html#identifiers>. 
>>>> The semantics of name binding are described here 
>>>> <https://docs.python.org/3/reference/executionmodel.html#naming-and-binding>.
>>>>  Which means that you cannot infer the name from the value.
>>>> Python only deals with values, not names. The names are how you refer to 
>>>> the values. That is the semantics. There's no inverse transformation 
>>>

[Python-ideas] Re: Extract variable name from itself

2023-09-23 Thread Dom Grigonis
It seems that my guess was correct. There was a commit, when only the first 
part was working:

https://github.com/python/cpython/pull/13123/commits/67977672360659f203664d23cfc52b5e07e4381a
 
<https://github.com/python/cpython/pull/13123/commits/67977672360659f203664d23cfc52b5e07e4381a>

So it does seem that it can be done manageably, while all editors with f-string 
support would benefit instantaneously without extra effort or unnecessary 
complications such as `typing` library.

Regards,
DG

> On 23 Sep 2023, at 23:55, Dom Grigonis  wrote:
> 
>> the output will have the expression text
> This is exactly what I want. If there was an extra check for validity at 
> parser level, it is a plus.
> 
>> You want to produce a name, that is an identifier 
>> <https://docs.python.org/3/reference/lexical_analysis.html#identifiers>. 
> Not necessarily, I want the first part of f’{expr=}’.
> There are outputs:
> a) `expr=repr(expr)`
> b) `repr(expr)`
> 
> why is it a bad idea to have:
> c) `expr` without `repr(expr)`?
> 
> This does cover `identifier only` case as well, but is not limited to it.
> 
> Is it difficult to achieve? Apologies if I am missing something, but if you 
> know the workings of python, could you point me to where f’{expr=}' is parsed 
> and compiled?
> 
> Obviously I might be wrong, but it is difficult to believe that it is done in 
> such way, that I can have B, A, but not A without B. Would appreciate if 
> you convinced me with some support for your rather strong statements.
> 
> Regards,
> DG
> 
>> On 23 Sep 2023, at 23:18, Tiago Illipronti Girardi > <mailto:tiagoigira...@gmail.com>> wrote:
>> 
>> I think I did something wrong and we are responding to one another instead 
>> of the list, please correct this if you can.
>> 
>> Let's start with `f'{name=}'`. This is from the docs 
>> <https://docs.python.org/3/reference/lexical_analysis.html#f-strings> (the 
>> link has the docs for f-strings, so read it):
>> 
>> When the equal sign '=' is provided, the output will have the expression 
>> text, the '=' and the evaluated value. Spaces after the opening brace '{', 
>> within the expression and after the '=' are all retained in the output. By 
>> default, the '=' causes the repr() 
>> <https://docs.python.org/3/library/functions.html#repr> of the expression to 
>> be provided, unless there is a format specified. When a format is specified 
>> it defaults to the str() 
>> <https://docs.python.org/3/library/stdtypes.html#str> of the expression 
>> unless a conversion '!r' is declared.
>> 
>> That's not what you want. You want to produce a name, that is an identifier 
>> <https://docs.python.org/3/reference/lexical_analysis.html#identifiers>. The 
>> semantics of name binding are described here 
>> <https://docs.python.org/3/reference/executionmodel.html#naming-and-binding>.
>>  Which means that you cannot infer the name from the value.
>> Python only deals with values, not names. The names are how you refer to the 
>> values. That is the semantics. There's no inverse transformation embedded in 
>> the language. That's what everyone is trying to communicate to you.
>> If you pay close attention to the execution model 
>> <https://docs.python.org/3/reference/executionmodel.html#naming-and-binding> 
>> there is a link from the name to the object but not the other way around, so 
>> you can't get it from the object. That's it. You need to change the whole 
>> execution model (that is the interpreter) to get what you  want
>> 
>> Em sáb., 23 de set. de 2023 às 13:16, Dom Grigonis > <mailto:dom.grigo...@gmail.com>> escreveu:
>> 
>> 
>>> On 23 Sep 2023, at 18:00, Tiago Illipronti Girardi >> <mailto:tiagoigira...@gmail.com>> wrote:
>>> 
>>> The `f'{obj!fmt}'` syntax formats the `obj` with `repr` if `fmt` is `r`, 
>>> with `str` if it is `s`, or with `ascii` if its `a`.
>>> With a new format `id` or `i` it would do nothing, but it could signal to 
>>> an editor that it is an identifier (editors, I believe, already parse the 
>>> contents of the curly brackets on f-strings).
>> I know the formatting syntax, I wasn’t clear what your point was. I see now 
>> that you are referring to new syntax which does nothing apart from 
>> signalling the editor.
>> 
>> Your suggestion is leaning towards python adapting to the editor, while I 
>> would argue that things are simpler and more robust if editors treat code 
>> expression as code expression and strings as strings. Making a mess here 
>> does seem like too big of

[Python-ideas] Re: Extract variable name from itself

2023-09-23 Thread Dom Grigonis
> the output will have the expression text
This is exactly what I want. If there was an extra check for validity at parser 
level, it is a plus.

> You want to produce a name, that is an identifier 
> <https://docs.python.org/3/reference/lexical_analysis.html#identifiers>. 
Not necessarily, I want the first part of f’{expr=}’.
There are outputs:
a) `expr=repr(expr)`
b) `repr(expr)`

why is it a bad idea to have:
c) `expr` without `repr(expr)`?

This does cover `identifier only` case as well, but is not limited to it.

Is it difficult to achieve? Apologies if I am missing something, but if you 
know the workings of python, could you point me to where f’{expr=}' is parsed 
and compiled?

Obviously I might be wrong, but it is difficult to believe that it is done in 
such way, that I can have B, A, but not A without B. Would appreciate if you 
convinced me with some support for your rather strong statements.

Regards,
DG

> On 23 Sep 2023, at 23:18, Tiago Illipronti Girardi  
> wrote:
> 
> I think I did something wrong and we are responding to one another instead of 
> the list, please correct this if you can.
> 
> Let's start with `f'{name=}'`. This is from the docs 
> <https://docs.python.org/3/reference/lexical_analysis.html#f-strings> (the 
> link has the docs for f-strings, so read it):
> 
> When the equal sign '=' is provided, the output will have the expression 
> text, the '=' and the evaluated value. Spaces after the opening brace '{', 
> within the expression and after the '=' are all retained in the output. By 
> default, the '=' causes the repr() 
> <https://docs.python.org/3/library/functions.html#repr> of the expression to 
> be provided, unless there is a format specified. When a format is specified 
> it defaults to the str() 
> <https://docs.python.org/3/library/stdtypes.html#str> of the expression 
> unless a conversion '!r' is declared.
> 
> That's not what you want. You want to produce a name, that is an identifier 
> <https://docs.python.org/3/reference/lexical_analysis.html#identifiers>. The 
> semantics of name binding are described here 
> <https://docs.python.org/3/reference/executionmodel.html#naming-and-binding>. 
> Which means that you cannot infer the name from the value.
> Python only deals with values, not names. The names are how you refer to the 
> values. That is the semantics. There's no inverse transformation embedded in 
> the language. That's what everyone is trying to communicate to you.
> If you pay close attention to the execution model 
> <https://docs.python.org/3/reference/executionmodel.html#naming-and-binding> 
> there is a link from the name to the object but not the other way around, so 
> you can't get it from the object. That's it. You need to change the whole 
> execution model (that is the interpreter) to get what you  want
> 
> Em sáb., 23 de set. de 2023 às 13:16, Dom Grigonis  <mailto:dom.grigo...@gmail.com>> escreveu:
> 
> 
>> On 23 Sep 2023, at 18:00, Tiago Illipronti Girardi > <mailto:tiagoigira...@gmail.com>> wrote:
>> 
>> The `f'{obj!fmt}'` syntax formats the `obj` with `repr` if `fmt` is `r`, 
>> with `str` if it is `s`, or with `ascii` if its `a`.
>> With a new format `id` or `i` it would do nothing, but it could signal to an 
>> editor that it is an identifier (editors, I believe, already parse the 
>> contents of the curly brackets on f-strings).
> I know the formatting syntax, I wasn’t clear what your point was. I see now 
> that you are referring to new syntax which does nothing apart from signalling 
> the editor.
> 
> Your suggestion is leaning towards python adapting to the editor, while I 
> would argue that things are simpler and more robust if editors treat code 
> expression as code expression and strings as strings. Making a mess here does 
> seem like too big of a cost for not so profound benefits of what I am 
> proposing.
> 
>> Identifiers are syntactical constructs in python, they only have semantics 
>> given a context, and more than one identifier can have the same semantic 
>> meaning in a given context, which makes your proposal a no-go from start.
> Can you elaborate on this?
> 
> Given f’{expr=}’ syntax already exists, how is this an issue for my proposal?
> 
>> Except if we were to change the whole execution model of the language.
> Although I am open to be proven wrong. Could you give an explanation why 
> stripping `repr(expr)` part from f’{expr=}’ and leaving expr literal is 
> problematic, given substituting expr literal is already being done?
> 
> 
>> However, for the "change this identifier from this to that" case (which is 
>> an editor problem), subclassing `typing.LiteralString` would basicall

[Python-ideas] Re: Extract variable name from itself

2023-09-23 Thread Dom Grigonis

> On 23 Sep 2023, at 16:24, Tiago Illipronti Girardi  
> wrote:
> 
> but:
> 1. There are costs doing it in python. And easy implementation doing it in 
> editor (with the typing support it's almost already done).
What are those costs?

> 2. The f-string functionality is not there right now, but f'{name!id}' would 
> leverage what is there and, with editor support, give the exact `nameof`` 
> support even without further interpret support.
What do you mean by f’{name!id}’ ? I don’t understand your point here.

Are you proposing f’{name!id}’ syntax for it? My whole point is to do this in 
f-strings.

Namely my proposal is f’{=expr}’.

`nameof` function is out of the question - it has no benefits over f-string 
implementation.

> The other use cases you mention are easily dealt with, assuming editor and 
> typing.LiteralString (subclassed) support.
Can you elaborate? I have only basic user knowledge about typing library and 
use it sparsely.

But from what I know, tying this to typing does not seem like a good idea. It 
is very basic functionality and from my POV stands at lower level, while typing 
is optional feature and not everyone uses it or even needs to know it.

DG
—Evaluation of deferred evaluation can be deferred, but not indefinitely —


> Em sáb., 23 de set. de 2023 às 09:51, Dom Grigonis  <mailto:dom.grigo...@gmail.com>> escreveu:
>> This is the only use case I can think of.
> Yes, probably most common one, but I have mentioned couple more.
> 
> 1. Keeping dictionary keys in sync with variable name.
> 2. eval / exec statements. Although eval / exec are not recommended in high 
> standard production code, python is widely used in plugins for various apps. 
> E.g. Alfred / Sublime text, where exec/eval can be very useful. Why not have 
> a method to do it a bit more robustly?
> 
> Given python being flexible multipurpose interpreted language, I am sure more 
> use cases would surface.
> 
>> Couldn’t we just subclass typing.LiteralString to typing.Id or something for 
>> this “functionality” and let editing tools deal with it.
> 
> “Could”, but:
> 1. There are benefits doing it in python. And undesired costs of implementing 
> this in editor (see my later e-mails)
> 2. The f-string functionality for it is already there:
> f'{a=}'.rstrip(f'{a}')
> # or a bit better
> f'{a=}'.split('=')[0]
> # = exactly what I am proposing (Except the unneeded evaluation part)
> So if it is already there, why not have it done well given there is little to 
> none overall cost to it? I think cost implementing such things in Editor is 
> much greater.
> 
> Regards,
> DG

___
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/TKB3EVGGSXRBZQ5EXKRX5GCW5NPRVB4B/
Code of Conduct: http://python.org/psf/codeofconduct/


[Python-ideas] Re: Extract variable name from itself

2023-09-23 Thread Dom Grigonis
> This is the only use case I can think of.
Yes, probably most common one, but I have mentioned couple more.

1. Keeping dictionary keys in sync with variable name.
2. eval / exec statements. Although eval / exec are not recommended in high 
standard production code, python is widely used in plugins for various apps. 
E.g. Alfred / Sublime text, where exec/eval can be very useful. Why not have a 
method to do it a bit more robustly?

Given python being flexible multipurpose interpreted language, I am sure more 
use cases would surface.

> Couldn’t we just subclass typing.LiteralString to typing.Id or something for 
> this “functionality” and let editing tools deal with it.

“Could”, but:
1. There are benefits doing it in python. And undesired costs of implementing 
this in editor (see my later e-mails)
2. The f-string functionality for it is already there:
f'{a=}'.rstrip(f'{a}')
# or a bit better
f'{a=}'.split('=')[0]
# = exactly what I am proposing (Except the unneeded evaluation part)
So if it is already there, why not have it done well given there is little to 
none overall cost to it? I think cost implementing such things in Editor is 
much greater.

Regards,
DG___
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/7G5EXX7QBGJB7H3PDNOWXKW2JMPDIJ4J/
Code of Conduct: http://python.org/psf/codeofconduct/


[Python-ideas] Re: Extract variable name from itself

2023-09-23 Thread Dom Grigonis


> On 23 Sep 2023, at 08:54, Stephen J. Turnbull 
>  wrote:
> 
> Dom Grigonis writes:
> 
>> Simply eval/exec string inputs. I sometimes use of these for ad-hoc
>> callbacks. Would be great if `v` was recognised as a code.
> 
> Looking at the example, do you mean '=' here?  That is, you want to
> add semantics for prefixed '=', meaning "just insert the expression
> string here"?
Correct, it’s the one that I though could make sense, so just keep using it in 
examples now.


>> Code is similar to this: class A:
>>def __init__(self):
>>self.d = {'a': 1, 'b': 2}
>> 
>>def apply(self, smtp):
>>for k, v in self.d.items():
>>if callable(smtp):
>>self.d[k] = smtp(v)
>>elif isinstance(smtp, str):
>>self.d[k] = eval(f'{=v}{smtp}')
> 
> Since f'{=v}' just results in 'v', why isn't
> 
>self.d[k] = eval(f'v{smtp}')
> 
> fine?  Sure, you get the compiler check/refactoring benefit, but as
> you admit, this is a very "ad hack" use case.  I don't think we should
> encourage it in production code.

Agree, this use case is not for production code.

Correct me if I am wrong, but I think `eval` in general should not be 
encouraged in production code.


___
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/N74S6AEKQEXG467DA5CWOW2DAO7KAWN6/
Code of Conduct: http://python.org/psf/codeofconduct/


[Python-ideas] Re: Extract variable name from itself

2023-09-22 Thread Dom Grigonis
Just want to add to this as I encountered a case, where I think f-string would 
be sensible to use. Third potential use case after logging & dictionary key 
synchronisation with variables names.

Simply eval/exec string inputs. I sometimes use of these for ad-hoc callbacks. 
Would be great if `v` was recognised as a code. Code is similar to this:
class A:
def __init__(self):
self.d = {'a': 1, 'b': 2}

def apply(self, smtp):
for k, v in self.d.items():
if callable(smtp):
self.d[k] = smtp(v)
elif isinstance(smtp, str):
self.d[k] = eval(f'{=v}{smtp}')

a = A()
print(a.d)# {'a': 1, 'b': 2}
a.apply(lambda x: x * 2)
print(a.d)# {'a': 2, 'b': 4}
a.apply('* 2')
print(a.d)# {'a': 4, 'b': 8}
Regards,
DG


> On 16 Sep 2023, at 20:43, Dom Grigonis  wrote:
> 
> Agree, all good points.
> f'{=expr}'.split('.')[-1]
> Does take care of all cases and `nameof` has no additional use over it.
> 
> It seems that `nameof` is out of question.
> 
> DG
> 
>> On 16 Sep 2023, at 19:50, Stephen J. Turnbull 
>> > <mailto:turnbull.stephen...@u.tsukuba.ac.jp>> wrote:
>> 
>> Dom Grigonis writes:
>> 
>>> print(f'{=A.a}')# 'A.a'
>>> print(nameof(A.a))  # 'a'
>> 
>> I see that's the C# semantics, but it's not obvious to me why the
>> ambiguity introduced is worth emulating.  The important aspect of the
>> proposed 'nameof' operator is that its argument can be validated by
>> the compiler and unambiguously recognized by refactoring tools.  But
>> once it's a string, it loses those advantages.  Why not be unambiguous?
>> 
>> I don't think that the tricks recommended (ie, typeof) to retrieve a
>> fully-qualified name in C# would be unambiguous in Python.
>> 
>> Also, Python's f-string '=' operator handles a broad variety of
>> expressions, not just attribute references.  This has been useful to
>> me more often than bare names and attribute references.
>> 
>>> Both [member name and full reference] seem useful to me.
>> 
>> What am I missing?  When would you want the member name only but
>> "nameof().split('.')[-1]" would not do?
>> 
>> Also, are there use cases for the proposed nameof other than a more
>> flexible f-string '='?  Ie, where only the str is wanted, not the
>> str-ified object?  That clearly doesn't apply to the refactoring
>> application, though, unless you're communicating local names to
>> nonlocal computations or using eval, both of which seem like really
>> dubious practices to me.
>> 
>>> So the functionality is bound to an editor and anyone using another
>>> editor would just see a weird string?
>> 
>> No, they'd see an ordinary string.  Editors would use heuristics to
>> recognize strings like f"the value of expression is {expression}".  I
>> do stuff like this in Emacs all the time ad hoc, Chris is just
>> suggesting that some editors/IDEs would provide a more powerful and
>> accurate facility.  I see while I was composing this Bruce Leban came
>> up with a very plausible convention, too.
>> 
>>> Use cases are mostly bug-free refactoring,
>> 
>> But the refactoring is very "meta" in the sense that you're creating a
>> string that refers to the name of an object.  You either need an
>> external agent or computation which would be confused if the name were
>> incorrect, or to be using eval() for this to be an actual refactoring.
>> All of this seems very "code smelly" to me.  If you're refactoring
>> this automatically, you're doing it wrong. ;-)
>> 
>> I don't see any use case that f-string '=' doesn't satisfy well enough
>> to make a new builtin pseudo-function[1] justifiable.
>> 
>>> E.g. would it be faster than `Class.__name__`?
>> 
>> You're working with strings expressing code.  If it's about speed,
>> there's got to be a better way.
>> 
>> 
>> 
>> Footnotes: 
>> [1]  In C#, 'nameof' is first looked up as a function reference, and
>> if found that is called.  Otherwise the compiler macro is used.
>> 
> 

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


[Python-ideas] Re: Revise using the colon ( : )

2023-09-20 Thread Dom Grigonis
My bad, you have pointed to ambiguity accurately.

Thanks for taking time to correct me.

Regards,
DG

> On 20 Sep 2023, at 16:09, Celelibi  wrote:
> 
> 2023-09-12 7:10 UTC+02:00, Dom Grigonis :
>> I don’t think your example depicts the ambiguity well.
>> 
>> 1. is the correct parsing of the Original1, 2. is the correct parsing of
>> Original2 and 3. is not correct for either of those.
>> 
>> Original1
>>> while a < b (x := c) - 42
>> Original2
>>> while a < b(x := c) - 42
> 
> They're the same. AFAIK `foo(...)` and `foo (...)` are parsed exactly
> the same way. A space in this place is irrelevant. And it's unlikely
> to change in the next few decades.
> 
>> 
>> 1. In this case, it’s obviously this one
>>> while a < b:
>>>   (x := c) - 42
> 
> Why tho? Why would this one be more obvious than the other
> alternatives? What would be the rules to decide? If I may quote the
> PEP 20:
>> In the face of ambiguity, refuse the temptation to guess.
> 
>> 2. In here your removed the space, which is not ambiguity, but rather
>> mistype
> Again, the space in this place doesn't matter. I removed it to show
> more explicitely how it could be parsed.
> 
>> 3. Same as in 2. But also, this is not an option, because if there was no
>> indent on the next line, then body exists. So this is incorrect.
>>> Or:
>>> while a < b(x := c) - 42:
>>>   # ???
> 
> I actually think this is the better parsing of the three: a SyntaxError.
> 
> 
> Celelibi
> ___
> 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/WSOJIXRMEYCNQGVNABPCJJ4S23PB6X4L/
> 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/RQBYA3FMKBL6OXZWJ55XAT26CKOPH7EU/
Code of Conduct: http://python.org/psf/codeofconduct/


[Python-ideas] Re: Extract variable name from itself

2023-09-18 Thread Dom Grigonis
Thank you Jonathan,

This is indeed helpful, I have completely forgotten about these.

However, in my case, defaults are not callable defaults, but rather default 
values preset at a higher level object and it has little to do with function 
defaults.

Although, I think it is possible to reshape the problem to use the mechanism 
you have provided. For example:

class Node:
def __init__(self, a=1):
self.a = a

class Container:
def __init__(self, a):
self.node_defaults = dict()
self.node_cls = Node
self.node_cls.__init__.__defaults__ = (a,)
# The issue, however is that it modifies the constructor from outside
# And it changes the Node class for the whole Runtime
# copy, deepcopy do not work here either
# Construct the node class programatically by inheritance leads to the 
same issue:
# self.node_cls = type('Node2', (Node,), {})
# self.node_cls.__init__.__defaults__ = (a,)
self.nodes = list()

def new_node(self, *args, **kwds):
node = self.node_cls(*args, **kwds)
self.nodes.append(node)
return node

c = Container(a=2)
print(c.new_node().a)   # 2
print(c.new_node(3).a)  # 3
print(Node().a) # 2
If you could provide an example, which solves the same issue that I have 
presented in a more elegant manner than simple dictionary storage, I would 
appreciate it.

Kind regards,
DG


> On 18 Sep 2023, at 17:24, Jonathan Fine  wrote:
> 
> Hi Dom
> 
> In your original post you used your proposed addition to write code that 
> provides a way of handling defaults different from the standard mechanism, 
> and perhaps in your opinion better.
> 
> The following example tells us something about defaults mechanism already 
> provided by Python:
> 
> >>> def f(a, b=1, c=2): return a, b, c
> ... 
> >>> f(0)
> (0, 1, 2)
> >>> f.__defaults__
> (1, 2)
> >>> f.__defaults__ = (0, 1, 2)
> >>> f()
> (0, 1, 2)
> >>> f.__defaults__ = (2, 1, 0)
> >>> f()
> (2, 1, 0)
> 
> I am suspicious of your example in your original post because it does not 
> explicitly consider the possibilities already provided by Python for changing 
> default values on the fly.
> 
> I hope this helps.
> 
> 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/MUGEZV47DCD7BO43JZ7AFFAGGKETWM5D/
Code of Conduct: http://python.org/psf/codeofconduct/


[Python-ideas] Re: Extract variable name from itself

2023-09-17 Thread Dom Grigonis
Thank you Jonathan,

Could you please elaborate on your suspicion, that my proposed addition will 
make bad code easier to write?

It would be nice if you provided example, where there is a pattern using my 
proposed addition, where similar badness of code cant be achieved using already 
existing python constructs.

Also, some explanation why would you deem it as bad code would be helpful.

Regards,
Dominykas

Now is better than never.
Although never is often better than *right* now.
While deferred evaluation is the happy midst of this temporal confusion.


> On 17 Sep 2023, at 11:47, Jonathan Fine  wrote:
> 
> Hi Dom
> 
> To support your proposal you provided an example. Well done for providing 
> evidence to support your idea. Doing that makes the discussion more 
> productive.
> 
> I'm going to use the words 'good' and 'bad', but with two provisos. The first 
> is that they are judgemental, and often judgement is little more than 
> personal opinion presented in an objective language. The second is that 
> 'good' and 'bad' depend on context. The usual C-Python is not good at writing 
> code where high performance is critical (but is fairly good at linking to 
> external libraries that do provide high performance). However, often 
> high-performance is of no importance when writing a prototype. For prototypes 
> the forces are quite different than for production.
> 
> With these provisos, a major purpose of a programming language is to make 
> good code easier to write, and bad code harder to write. Hence the importance 
> of you providing a coding example to support your idea. And also my request 
> that you provide more information about the example code you kindly provided.
> 
> Based on your example, I suspect that your proposed addition will make bad 
> code easier to write. However, we don't need to discuss that now. I suggest 
> that for your proposal to gain support an example of how it makes good code 
> easier to write would be helpful. And also if you wish an example of how it 
> makes bad code harder to write.
> 
> Please note that my use of 'good' and 'bad' are subject to the provisos 
> mentioned earlier.
> 
> I hope this helps.
> 
> 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/A4EG7HT2SNUJ5UF2LZ3T2P2L6AUH6IV7/
Code of Conduct: http://python.org/psf/codeofconduct/


[Python-ideas] Re: Extract variable name from itself

2023-09-16 Thread Dom Grigonis
Hi Jonathan,

I wasn’t writing anything specialised on handling of defaults. My initial 
example pretty much covers it.

What defaults handler of python are you talking about?

This proposal is more about convenient refactoring and keeping things nicely 
synchronised where variable name and string value are preferred to be kept in 
sync. The default handling is just one such case. It can also be useful in 
logging.

I can make my initial example a bit more clear and closer to what actually 
happened:

class Container:
def __init__(self, a):
self.node_defaults = dict()
self.node_defaults[f'{=a}'] = a
self.nodes = list()

def new_node(self, a=None):
if a is None:
a = self.node_defaults.get(f'{=a}')
node = Node(a)
self.nodes.append(a)
return node


class Node:
def __init__(self, a):
self.a = a
Currently, I just store keys as close to the object that finally uses the value 
as possible. So to achieve similar overall effect. And I am not saying that the 
above is better than below. IMO, it all depends on individual case. My point is 
that it might be nice to have. And I think the reasoning for such thing goes 
more along the lines of convenience, rather than if similar result can be 
achieved in different ways.
class Container:
def __init__(self, a):
self.node_defaults = dict()
self.node_defaults[Node.K_A] = a
self.nodes = list()

def new_node(self, a=None):
if a is None:
a = self.node_defaults.get(Node.K_A)
node = Node(a)
self.nodes.append(a)
return node


class Node:
K_A = 'a'

def __init__(self, a):
self.a = a

Regards,
DG

—What can not be solved by force, can be solved by deferred evaluation —


> On 16 Sep 2023, at 21:27, Jonathan Fine  wrote:
> 
> Hi Dom
> 
> In your original post you said you're writing some code to improve handling 
> of defaults (perhaps only in some situations). You also said that the feature 
> you're suggesting would make your improved default handler easier to write.
> 
> Python already handles default values at least fairly well in many 
> situations. Please would you provide at least one example of how your 
> proposed default handler would be better than that already provided by Python.
> 
> Please don't worry about the implementation. Please focus on the syntax and 
> semantics and comparison with what Python does.
> 
> I will value your response to my request more highly if it shows that you 
> have a clear understanding of Python's present behaviour. I'd also welcome 
> any example you provide of weaknesses in Python's present behaviour.
> 
> I hope this helps.
> 
> 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/JNDAOK6EPYAUJZA5DDG6R2S3AAKOY62J/
Code of Conduct: http://python.org/psf/codeofconduct/


[Python-ideas] Re: Extract variable name from itself

2023-09-16 Thread Dom Grigonis
Agree, all good points.
f'{=expr}'.split('.')[-1]
Does take care of all cases and `nameof` has no additional use over it.

It seems that `nameof` is out of question.

DG

> On 16 Sep 2023, at 19:50, Stephen J. Turnbull 
>  wrote:
> 
> Dom Grigonis writes:
> 
>> print(f'{=A.a}')# 'A.a'
>> print(nameof(A.a))  # 'a'
> 
> I see that's the C# semantics, but it's not obvious to me why the
> ambiguity introduced is worth emulating.  The important aspect of the
> proposed 'nameof' operator is that its argument can be validated by
> the compiler and unambiguously recognized by refactoring tools.  But
> once it's a string, it loses those advantages.  Why not be unambiguous?
> 
> I don't think that the tricks recommended (ie, typeof) to retrieve a
> fully-qualified name in C# would be unambiguous in Python.
> 
> Also, Python's f-string '=' operator handles a broad variety of
> expressions, not just attribute references.  This has been useful to
> me more often than bare names and attribute references.
> 
>> Both [member name and full reference] seem useful to me.
> 
> What am I missing?  When would you want the member name only but
> "nameof().split('.')[-1]" would not do?
> 
> Also, are there use cases for the proposed nameof other than a more
> flexible f-string '='?  Ie, where only the str is wanted, not the
> str-ified object?  That clearly doesn't apply to the refactoring
> application, though, unless you're communicating local names to
> nonlocal computations or using eval, both of which seem like really
> dubious practices to me.
> 
>> So the functionality is bound to an editor and anyone using another
>> editor would just see a weird string?
> 
> No, they'd see an ordinary string.  Editors would use heuristics to
> recognize strings like f"the value of expression is {expression}".  I
> do stuff like this in Emacs all the time ad hoc, Chris is just
> suggesting that some editors/IDEs would provide a more powerful and
> accurate facility.  I see while I was composing this Bruce Leban came
> up with a very plausible convention, too.
> 
>> Use cases are mostly bug-free refactoring,
> 
> But the refactoring is very "meta" in the sense that you're creating a
> string that refers to the name of an object.  You either need an
> external agent or computation which would be confused if the name were
> incorrect, or to be using eval() for this to be an actual refactoring.
> All of this seems very "code smelly" to me.  If you're refactoring
> this automatically, you're doing it wrong. ;-)
> 
> I don't see any use case that f-string '=' doesn't satisfy well enough
> to make a new builtin pseudo-function[1] justifiable.
> 
>> E.g. would it be faster than `Class.__name__`?
> 
> You're working with strings expressing code.  If it's about speed,
> there's got to be a better way.
> 
> 
> 
> Footnotes: 
> [1]  In C#, 'nameof' is first looked up as a function reference, and
> if found that is called.  Otherwise the compiler macro is used.
> 

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


[Python-ideas] Re: Extract variable name from itself

2023-09-16 Thread Dom Grigonis
If it is done at a tool level, it is not a robust solution. The fact that it 
can be done in a tool doesn’t mean that it is the optimal solution. Having it 
done at python level could be a simpler solution and provide benefits to all of 
the tools, without needing for editor logic to deviate from python logic. Also, 
it eliminates inconsistencies and coding styles which would arise if each 
editor was to implement its own method.

Besides, editor tool implementation doesn’t offer all of the benefits, which on 
top of the refactoring benefits offer:
a) validity check in both f-strings and nameof().
b) nameof(‘a.b’) = ‘b’, which is not a straight forward equality.

Regarding f-strings.
I think the fact that it is already being done in python justifies its validity:
a = 1
print(f'{a=}')
and everybody is happy using it instead of:
print(f'a={a}')
If the argument that this sort of thing should be done in editor is deemed to 
be a valid one, then the `f’{expr=}’` expression was a mistake. However, the 
way I see it, it is very useful addition and I do use it a fair bit.

What I am proposing is nothing new, but rather a small part of what is already 
there, arguably bringing it closer to modular completeness:
print(f'{a}')
print(f'{a=}')
print(f'{=a}')
It’s the same as “I can draw square, square and circle, but I cant draw a 
circle without a square”.

It seems like a non-invasive addition, not causing any problems, not cluttering 
namespaces and how I see it, has just the right place for it and its syntax 
space is very unlikely to be used for anything else.

I do not see a big cost in either implementation or maintenance. The question 
is whether benefits justify that cost.

DG

> On 16 Sep 2023, at 18:37, Bruce Leban  wrote:
> 
> If the goal is to create a syntax that allows tools to recognize names in 
> strings, there is a simple solution which requires tool changes only, for 
> example:
> 
> raise Exception('The field ' + ((('size'))) + ' must be a positive integer in 
> ' + ((('Sample.widget'
> 
> Python already treats triple parenthesized strings properly and all you need 
> to do is modify tools to recognize that syntax. It's even backwards 
> compatible, visually striking, and doesn't prevent compile-time string 
> folding.
> 
> --- Bruce
> 
> ___
> 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/OXEOPXY7BCFB4P7XKEAM3UN5XU6RIHJP/
> 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/TRRMMUCYRJVAORM4RFDJFXGKP53ZVQ47/
Code of Conduct: http://python.org/psf/codeofconduct/


[Python-ideas] Re: Extract variable name from itself

2023-09-16 Thread Dom Grigonis


Yes, it seems it does have scope beyond editor in both cases.
class A: a = 1

print(f'{=A.a}')# 'A.a'
print(nameof(A.a))  # 'a'
In f-string case, if to be consistent with current f-string functionality, 
expression would be checked for a validity and that reference is in scope and 
available. Essentially, everything that `f{A.a=}` does now, except actual 
evaluation.

In `nameof` case, it only prints the name of the last attribute and drops the 
tail. It is also naturally checked for validity.

Both seem useful to me.

> It works already with existing tools that will treat "nameof(a+b)" as a 
> function call, which it is syntactically but not semantically, so renaming b 
> to c will now produce the string "a+c". I think my IDE does offer to do this 
> with variable names in strings and comments, but it produces so many false 
> hits I don't enjoy using the feature.

So the functionality is bound to an editor and anyone using another editor 
would just see a weird string?
After several similar editor features things could get very confusing.

> I'm not convinced this feature is widely useful.
> 

So what is the general procedure for determining it?


On a side note,
I have stumbled on this stack thread:
https://stackoverflow.com/questions/31695900/what-is-the-purpose-of-nameof 

Use cases are mostly bug-free refactoring, but some are using it for resource 
check at compie time. Also, certain cases C# offer speed benefits. E.g. would 
it be faster than `Class.__name__`?

DG

> On 16 Sep 2023, at 12:44, Jeff Allen  wrote:
> 
> On 16/09/2023 01:14, Chris Angelico wrote:
>> But if that tool can be taught that nameof indicates a variable name,
>> then it can rename inside it just like it would rename anything else.
>> Your problem here is a limitation of the variable renaming tool. I'm
>> suggesting a solution to that problem. This is not a language problem,
>> it's an editor problem, so it needs an editor solution.
> It needs language (parser) support because it does what you identified early 
> on: "take whatever is given and put it in quotes", where "whatever is given" 
> is the text of the expression only available at run-time. (Actually, I can 
> think of something complicated one might possibly do with the text produced 
> in exceptions, but please don't.)
> Taking an example from my REPL just now (it happens that r2 is the AST of an 
> Expression), you could simulate nameof with f-strings:
> 
> >>> f"{r2.body.op.test=}"
> 'r2.body.op.test=42'
> >>> f"{r2.body.op.test=}".split('=')[0]
> 'r2.body.op.test'
> 
> This also evaluates the expression, encodes the result as text then discards 
> it, which is undesirable. The point is that renaming r2, or the fields of a 
> BinOp (if it were project-local, not a stdlib object) would cause the string 
> to change in most existing IDEs.
> Attempts to guess the name from the expression at runtime are futile and a 
> red herring. Trying to describe the desired semantics that way leads to 
> nonsensical ideas, I agree.
> 


> -- 
> 
> Jeff Allen
> ___
> 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/RQISFW5UV2EW6ZB3ZKUDNV2R45MWIH3O/
> 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/SWM5ZL6X3TQV24OAPQOH3GI4UNPV2AJL/
Code of Conduct: http://python.org/psf/codeofconduct/


[Python-ideas] Re: Extract variable name from itself

2023-09-15 Thread Dom Grigonis
So following this thread, from your perspective and from what has been said you 
can’t see or noticed any parts of it needing interpreter?
DG

> On 16 Sep 2023, at 03:14, Chris Angelico  wrote:
> 
> On Sat, 16 Sept 2023 at 10:07, Dom Grigonis  wrote:
>> 
>> 
>>> def nameof(x): return x
>>> 
>>> print("This " + nameof("thing") + " is:", thing)
>> Can you explain what you meant by this code? How would this work in editor?
>> 
> 
> Frankly, I have no idea, because your **entire proposal** is
> predicated on some sort of automated tool for renaming variables.
> Without knowing the details of that tool, how can I tell you how this
> would work?
> 
> But if that tool can be taught that nameof indicates a variable name,
> then it can rename inside it just like it would rename anything else.
> 
> Your problem here is a limitation of the variable renaming tool. I'm
> suggesting a solution to that problem. This is not a language problem,
> it's an editor problem, so it needs an editor solution.
> 
> ChrisA
> ___
> 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/I6KUD7LCGYV4JES77A7PZDVBHWVIKXF3/
> 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/IDOWZCWN6CPEVFOUZGDPRKD7QV36ZCHL/
Code of Conduct: http://python.org/psf/codeofconduct/


[Python-ideas] Re: Extract variable name from itself

2023-09-15 Thread Dom Grigonis


> def nameof(x): return x
> 
> print("This " + nameof("thing") + " is:", thing)
Can you explain what you meant by this code? How would this work in editor?

> 
> ChrisA
> ___
> 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/MRHSRDWF3IR6ZEC7HFE5VBPS2YW4CITX/
> 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/7Y2AOC6ATEOCMIZNNJERSDUKF2L5DCVD/
Code of Conduct: http://python.org/psf/codeofconduct/


[Python-ideas] Re: Extract variable name from itself

2023-09-15 Thread Dom Grigonis
Yes, I agree. This was exactly what I had in mind. Was good to find out that 
there is such implementation in other language.

DG.

> On 15 Sep 2023, at 17:00, Jeff Allen  wrote:
> 
> On 13/09/2023 17:21, MRAB wrote:
>> I think the point is to have an equivalent to C#'s 'nameof'. 
>> 
>> It would be evaluated at compile time to a string, but with the advantage 
>> that it's clear that it's a name and not some random string that just 
>> happens to look like a name. 
>> 
> I'd like to draw attention to this as the first contribution to the thread 
> that has given a precise meaning to the initial idea. It tells us both what 
> it means and why you might want it (at least if the OP agrees). It seems to 
> be being overlooked.
> 
> As others have amply demonstrated (short of proof, I know) what is being 
> asked is not possible with the information available at run-time. You can't 
> reliable get from the "reference", which is actually an expression, to the 
> text of the expression.
> 
> The parallel with f-string = is helpful, for which compile-time support is 
> essential, of course.
> 
> -- 
> 
> Jeff Allen
> ___
> 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/45P4HD5LBNDCPUGRRWWDV6XGR6H3GCDB/
> 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/X6GLLYE3VAGCLCCWGQNGXJTISI2WMTXY/
Code of Conduct: http://python.org/psf/codeofconduct/


[Python-ideas] Re: Extract variable name from itself

2023-09-14 Thread Dom Grigonis
Good ideas, however not robust:
a = 1
b = 1
print(id(a))# 4536318072
print(id(b))# 4536318072

> On 14 Sep 2023, at 16:35, Jonathan Fine  wrote:
> 
> POSTSCRIPT
> 
> We can also use locals() to 'inverse search' to get the name, much as in the 
> original post.
> 
> >>> locals()['x']
> (0, 1, 2, 3)
> >>> id(x)
> 139910226553296
> >>> id(locals()['x'])
> 139910226553296
> -- 
> 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/MPPLJ6MXZDNA7J75T7H76LNYZGHCEG37/
> 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/7BXP63XG4PSQ2YFLCRXUEXJNNIQYEB4H/
Code of Conduct: http://python.org/psf/codeofconduct/


[Python-ideas] Re: Extract variable name from itself

2023-09-12 Thread Dom Grigonis
I agree.

What I meant is that it is unreliable with `v is 710` and even more unreliable 
with `v == 710` as “==“ is less strict than “is”.

DG

> On 12 Sep 2023, at 21:03, Rob Cliffe  wrote:
> 
> 
>>> As for the example in your first post:
>>> var = 710
>>> variable_name = [k for k, v in locals().items() if v == 710][0] 
>>> print("Your variable name is " + variable_name)
>>> 
>>> it does "work", but it doesn't make much sense with Python's semantics.  
>>> You could have two identifiers bound to the same object; which one you got 
>>> hold of would be essentially random.
>> Yes, if `==` was replaced by `is`. Currently it is even more random as it 
>> would return the first one which evaluates __eq__() positively.
>> 
> I'm not sure what you're saying.  In:
> var1 = 710
> var2 = 710
> variable_names = [k for k, v in locals().items() if v is 710]
> Depending on the Python implementation, variable_names may be ['var1', 
> 'var2'] or it may be empty (depending on whether 710 is interned).  It could 
> also in theory contain one of 'var1', 'var2' but not the other, though I 
> would be surprised if that happened in practice.  The behaviour is not 
> guaranteed and should not be relied on.
> Rob Cliffe

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


[Python-ideas] Re: Extract variable name from itself

2023-09-12 Thread Dom Grigonis
Good points, thanks for reply.

> Or do you want to check that the expression can be evaluated at run time?
> You could achieve that by simply writing
> a.method
Yes, the point is that it would be checked for legality of expression itself. 
Whether to check if it actually evaluates without an error or not would both 
work. I see pros and cons in both cases. Maybe not evaluating is better as 
evaluation can always be checked separately if needed and eventually will be 
checked on actual usage anyway.

> As for the example in your first post:
> var = 710
> variable_name = [k for k, v in locals().items() if v == 710][0] 
> print("Your variable name is " + variable_name)
> 
> it does "work", but it doesn't make much sense with Python's semantics.  You 
> could have two identifiers bound to the same object; which one you got hold 
> of would be essentially random.
Yes, if `==` was replaced by `is`. Currently it is even more random as it would 
return the first one which evaluates __eq__() positively.

That's exactly why I started this. This was to illustrate that I could not find 
any robust way to do it.

DG.

___
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/O4UIFJQ7IYR2UZWYLNAQOOXQFJJNRXVT/
Code of Conduct: http://python.org/psf/codeofconduct/


[Python-ideas] Re: Extract variable name from itself

2023-09-12 Thread Dom Grigonis
Yes, Thank you!

So 2 solutions now. They both solve what I have encountered. Beyond that, they 
differ by:

a) f-string print(f’{=a.method}’)   # ‘a.method’
No new builtin needed.
Simply reprints expression representation.

b) print(nameof(a.method))   # ‘method’
New builtin.
Has its own logic.
Its extra functionality on top of what I have suggested can already 
achieved in python via a.method.__name__

I think f-string approach if optimal. It adds new feature, without 
functionality overlap and doesn’t crowd the namespace. Also, implementation is 
simpler as all what is required seems to be in the place already.

I have little preference regarding syntax, but
f’{=expression}’ does seem to make sense.

Regards,
DG

> On 12 Sep 2023, at 13:14, Valentin Berlier  wrote:
> 
> Do you mean something like C# nameof()? 
> https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/operators/nameof
> ___
> 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/USPQDMEA7ACWH2T56ZYTWBGG7SMT3RIF/
> 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/P7KERJ2O5QWON5CZGM5LTMNVP4AZXHSK/
Code of Conduct: http://python.org/psf/codeofconduct/


[Python-ideas] Re: Extract variable name from itself

2023-09-12 Thread Dom Grigonis
An addition to f-strings:
a = 1
b = 1
print(f'{a+b}') # '2'
print(f'{a+b=}') # 'a+b=2'
# I suggest adding this too
print(f'{=a+b}')# 'a+b'
It is different from putting it in quotes in a way how editors interpret it. 
E.g. changing the variable name in PyCharm would unambiguously change f-string 
as well, while it would not change the string literal.

Also, one could argue that it can just be extracted by 
`f’{a+b=}’.split(‘=‘)[0]`, but it is of course sub-optimal given the 
possibility that evaluation is expensive and not required.

DG.


> On 12 Sep 2023, at 13:06, Chris Angelico  wrote:
> 
> On Tue, 12 Sept 2023 at 20:05, Dom Grigonis  wrote:
>> 
>> Please read the next part of my e-mail too. It actually answer your question.
>> 
> 
> I did read it, and it didn't answer the question. Your desired
> semantics are not clear.
> 
> ChrisA
> ___
> 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/P5RHZPHTVREEYOG2VSBZYLA6UU33T2X3/
> 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/6VVOWCY253PZPMTYNCEXGLH46YDAXN6S/
Code of Conduct: http://python.org/psf/codeofconduct/


[Python-ideas] Re: Extract variable name from itself

2023-09-12 Thread Dom Grigonis
Please read the next part of my e-mail too. It actually answer your question.

> On 12 Sep 2023, at 13:00, Chris Angelico  wrote:
> 
> On Tue, 12 Sept 2023 at 19:51, Dom Grigonis  wrote:
>> 
>> It wouldn’t. I know this is weird and not in line of how things work. This 
>> is more about simply getting reference variable name in locals() from the 
>> reference itself. But how would one access the variable name, when once 
>> called it returns the object it points to, not itself. So this would 
>> obviously require an exception in parser itself.
>> 
>> a = object()
>> b = a
>> print(a.__varname__)  # ‘a'
>> print(b.__varname__)  # 'b'
>> print((a + b).__varname__)  # Undefined??? ‘a + b’?
>> 
> 
> I don't understand your desired semantics. Do you just want to take
> whatever is given and put it in quotes?
> 
> ChrisA
> ___
> 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/ZWO3FPC2G2AWA5TNINBX4ZHDMKFBWQZN/
> 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/U3R6MHLYKC6R7RX2LG7EACVLOPB6TH5N/
Code of Conduct: http://python.org/psf/codeofconduct/


[Python-ideas] Re: Extract variable name from itself

2023-09-12 Thread Dom Grigonis
It wouldn’t. I know this is weird and not in line of how things work. This is 
more about simply getting reference variable name in locals() from the 
reference itself. But how would one access the variable name, when once called 
it returns the object it points to, not itself. So this would obviously require 
an exception in parser itself.
a = object()
b = a
print(a.__varname__)  # ‘a'
print(b.__varname__)  # 'b'
print((a + b).__varname__)  # Undefined??? ‘a + b’?

Actually, it could be easily achieved by what is happening in f-strings:
a = 1
b = 2
print(f'{a+b=}')# 'a+b=2'
# So I would like to be able to have something like
print(f'{=a+b}')# 'a+b'
So now it really looks just an addition to f-strings. They can print
1. value
2. `expression literal`=value
3. What I am asking is: `expression literal` (without value)

One can of course argue that this is the same as just typing it, but the 
difference is that things within curly braces are interpreted as code by the 
editor, which is the whole point.

DG.

> On 12 Sep 2023, at 12:24, Antoine Rozo  wrote:
> 
> Why would an object always be linked to a variable name, and why only one 
> name?
> 
> Le mar. 12 sept. 2023 à 10:23, Dom Grigonis  <mailto:dom.grigo...@gmail.com>> a écrit :
> As far as I understand, it is not possible. Is it?
> 
> Something similar to:
> 
> var = 710
> variable_name = [k for k, v in locals().items() if v == 710][0] 
> print("Your variable name is " + variable_name)
> 
> ,except robust.
> 
> Possible ways to expose it:
> * builtin function `varname(obj: object) —> str`
> * object.__varname__ dunder (this one wouldn’t clutter general namespace)
> 
> I am working on some code and just got to the point where it seems I could 
> make use of it. The case is as follows:
> 
> # What I do now:
> class A:
> defaults = dict()
> 
> def set_default(self, a):
> self.defaults['a'] = a
> 
> def make_something(self, a=None):
> a = a if a is not None else self.defaults.get('a')
> return Something(a)
> 
> # What I would like to be able to do:
> class A:
> defaults = dict()
> 
> def set_default(self, a):
> self.defaults[a.__varname__] = a
> 
> def make_something(self, a=None):
> a = a if a is not None else self.defaults.get(a.__varname__)
> return Something(a)
> 
> In this case I like second one, because it allows a tight coupling of 
> variable names, which has the following benefits:
> 1. General simplification, where one doesn’t have to think variable name and 
> its key value in dictionary. Code looks cleaner.
> 2. If one was to change a variable name of `set_default` it would immediately 
> surface as an error.
> 3. For someone working with IDEs or making use of clever multiple selection 
> tools, it would be easy to change all in one go.
> 
> Any reasons why the above would not be a good practice?
> Any reasons why exposing it is not a good idea?
> Would this be difficult to achieve from python dev’s perspective?
> 
> 
> — This one can’t be solved with deferred eval :/ —
> Regards,
> DG
> ___
> Python-ideas mailing list -- python-ideas@python.org 
> <mailto:python-ideas@python.org>
> To unsubscribe send an email to python-ideas-le...@python.org 
> <mailto:python-ideas-le...@python.org>
> https://mail.python.org/mailman3/lists/python-ideas.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/H3O6N2W62EDU75JEQQGN63HETAZNANLP/
>  
> <https://mail.python.org/archives/list/python-ideas@python.org/message/H3O6N2W62EDU75JEQQGN63HETAZNANLP/>
> Code of Conduct: http://python.org/psf/codeofconduct/ 
> <http://python.org/psf/codeofconduct/>
> 
> 
> -- 
> Antoine Rozo
> ___
> 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/RINOBZMXRJIHY2U7AYKKA5YAXZ5WJNAP/
> 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/7XLHNXNO4CVRRKUI36W5XU6QGDQWQTKQ/
Code of Conduct: http://python.org/psf/codeofconduct/


[Python-ideas] Extract variable name from itself

2023-09-12 Thread Dom Grigonis
As far as I understand, it is not possible. Is it?

Something similar to:

var = 710
variable_name = [k for k, v in locals().items() if v == 710][0] 
print("Your variable name is " + variable_name)

,except robust.

Possible ways to expose it:
* builtin function `varname(obj: object) —> str`
* object.__varname__ dunder (this one wouldn’t clutter general namespace)

I am working on some code and just got to the point where it seems I could make 
use of it. The case is as follows:

# What I do now:
class A:
defaults = dict()

def set_default(self, a):
self.defaults['a'] = a

def make_something(self, a=None):
a = a if a is not None else self.defaults.get('a')
return Something(a)

# What I would like to be able to do:
class A:
defaults = dict()

def set_default(self, a):
self.defaults[a.__varname__] = a

def make_something(self, a=None):
a = a if a is not None else self.defaults.get(a.__varname__)
return Something(a)

In this case I like second one, because it allows a tight coupling of variable 
names, which has the following benefits:
1. General simplification, where one doesn’t have to think variable name and 
its key value in dictionary. Code looks cleaner.
2. If one was to change a variable name of `set_default` it would immediately 
surface as an error.
3. For someone working with IDEs or making use of clever multiple selection 
tools, it would be easy to change all in one go.

Any reasons why the above would not be a good practice?
Any reasons why exposing it is not a good idea?
Would this be difficult to achieve from python dev’s perspective?


— This one can’t be solved with deferred eval :/ —
Regards,
DG___
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/H3O6N2W62EDU75JEQQGN63HETAZNANLP/
Code of Conduct: http://python.org/psf/codeofconduct/


[Python-ideas] Re: Revise using the colon ( : )

2023-09-11 Thread Dom Grigonis
I don’t think your example depicts the ambiguity well.

1. is the correct parsing of the Original1, 2. is the correct parsing of 
Original2 and 3. is not correct for either of those.

Original1
> while a < b (x := c) - 42
Original2
> while a < b(x := c) - 42

1. In this case, it’s obviously this one
> while a < b:
>(x := c) - 42
2. In here your removed the space, which is not ambiguity, but rather mistype
> Or:
> while a < b(x := c):
>-42
3. Same as in 2. But also, this is not an option, because if there was no 
indent on the next line, then body exists. So this is incorrect.
> Or:
> while a < b(x := c) - 42:
># ???

Having that said, I think readability suffers a lot from not having a colon and 
as you indicated potentially makes parser’s job harder.

Dg.

> On 11 Sep 2023, at 20:11, Celelibi  wrote:
> 
> 2023-09-05 18:26 UTC+02:00, Dom Grigonis  <mailto:dom.grigo...@gmail.com>>:
>> I like the idea of eliminating it if it was possible. This is one of my most
>> common syntax errors (although mostly after function signature) and I am not
>> C/C++ programmer. I am not sure about the core technical issues, but
>> readability of code, such as:
>> a = 1
>> while a < 5: a += 1
>> , would suffer:
>> a = 1
>> while a < 5 a += 1
>> So IMO, it does improve readability in certain cases.
>> 
>> Although, removing colon does sound like an idea worth thinking about. I
>> might even dare to suggest disallowing body statement on the same line, but
>> can’t do that for backwards compatibility ofc...
>> 
>> So my point is, if anyone is going to give a thought about this, please add
>> function signature to the list.
>> 
> 
> I just want to mention that without colons, one-liners could become ambiguous:
> while a < b (x := c) - 42
> 
> Is it:
> while a < b:
>(x := c) - 42
> 
> Or:
> while a < b(x := c):
>-42
> 
> Or:
> while a < b(x := c) - 42:
># ???
> 
> If anything, the colon would become optional but would definitely
> remain in the grammar. Kinda like the semi-colon, only used in
> one-liners.
> 
> When teaching python I noticed the usual uselessness of the colon
> regarding the correct parsing of correctly indented code.
> But I've never seen it as a burden and rarely if ever forgot one. It
> also allows code editors to be very simple: you see a line ending with
> a colon, you indent the next line. The keyword at the begining of the
> line doesn't matter.
> 
> Best regards,
> Celelibi
> ___
> Python-ideas mailing list -- python-ideas@python.org 
> <mailto:python-ideas@python.org>
> To unsubscribe send an email to python-ideas-le...@python.org 
> <mailto:python-ideas-le...@python.org>
> https://mail.python.org/mailman3/lists/python-ideas.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/UL3FSZWUKOVUASIPM46IPQIQPJ7GEV7Q/
>  
> <https://mail.python.org/archives/list/python-ideas@python.org/message/UL3FSZWUKOVUASIPM46IPQIQPJ7GEV7Q/>
> Code of Conduct: http://python.org/psf/codeofconduct/ 
> <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/JQGUO6WQ4Y6H4CYNRG7W6AORWKA2TCAE/
Code of Conduct: http://python.org/psf/codeofconduct/


[Python-ideas] Re: Have del return a value

2023-09-09 Thread Dom Grigonis
Also, check out https://docs.python.org/3/library/weakref.html 


Maybe it will not provide exactly what you indicated, but might get some ideas 
how to do things differently.

—
Now is better than never. Although never is often better than *right* now. == 
Deferred Evaluation
—
Dg


> On 9 Sep 2023, at 09:02, Jeff Allen  wrote:
> 
> On 06/09/2023 03:47, Daniel Walker wrote:
>> Perhaps this is a solution in search of a problem but I recently encountered 
>> this situation in one of my projects.
>> 
>> I have an object, foo, which, due to the references it contains, I'd rather 
>> not keep around longer than necessary.
>> 
>> I use foo to instantiate another object:
>> 
>> bar = Bar(foo)
>> 
>> bar is free to manipulate foo however it wants and even del it if necessary. 
>>  However, since the foo name is still around, those resources won't get 
>> cleaned up even if bar is done with them.  The simple solution is
>> 
> It's a neat idea but there are other ways that may be better.
> 
> I assume foo is a "specification", that is, an object you configure through a 
> number of optional calls or attribute assignments, then pass to Bar() as a 
> design alternative to Bar() having a complicated set of arguments. A pattern 
> often used is the fluent API:
> 
> bar = Bar(Foo().a().b(42).c('penguin'))
> 
> Now only Bar has a reference to the Foo you made.
> 
> But foo is not necessarily destroyed immediately the last reference to it is 
> dropped, even with del or when nameless in the fluent API. If you wanted to 
> be certain, you could make Foo a context manager to use like this:
> 
> with Foo() as foo:
> foo.a()
> foo.b(42)
> foo.c('penguin')
> bar = Bar(foo)
> bar.do_stuff()
> (Think I got that right. Not tried it.) Now Foo.__exit__ can be made to 
> properly tear down the resources in a foo.
> 
> -- 
> 
> Jeff Allen
> ___
> 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/75EXWHY3SFZSZTZUQJPIBMXFRF3J327I/
> 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/ICXLYHODLH3RVUQCJAHFZA56RBQTG7YI/
Code of Conduct: http://python.org/psf/codeofconduct/


[Python-ideas] Re: Revise using the colon ( : )

2023-09-05 Thread Dom Grigonis
I like the idea of eliminating it if it was possible. This is one of my most 
common syntax errors (although mostly after function signature) and I am not 
C/C++ programmer. I am not sure about the core technical issues, but 
readability of code, such as:
a = 1
while a < 5: a += 1
, would suffer:
a = 1
while a < 5 a += 1
So IMO, it does improve readability in certain cases.

Although, removing colon does sound like an idea worth thinking about. I might 
even dare to suggest disallowing body statement on the same line, but can’t do 
that for backwards compatibility ofc...

So my point is, if anyone is going to give a thought about this, please add 
function signature to the list.


— One small step towards deferred evaluation, one huge leap for… —
Dg

> On 1 Sep 2023, at 13:26, Morteza Mirzakhan  
> wrote:
> 
> Dear Python Developers,
> 
> I would like to share my thoughts on the use of the colon mark “:” in Python 
> code.
> 
> In my opinion, using a colon after keywords such as `if`, `elif`, `else`, 
> `for`, `while`, `try`, `except`, and `finally` is quite unnecessary.
> 
> Using mandatory indentation in Python to group commands into a block is 
> similar to how curly braces `{}` are used in ‘curly-bracket languages’ like 
> C-family, Perl, Java, PHP, etc. to group multiple commands into a single 
> statement.
> 
> While those compilers don't differentiate between one or more ‘space’ or 
> ‘return’ characters, so they don't recognize new lines and indents, the 
> indentation is also used, not forced but traditionally, to increase 
> readability. However, when it comes to writing just one instruction after the 
> head command, you can omit the curly braces `{}` and simply write it in a new 
> line, traditionally indented in C-family languages.
> 
> So Python is one step forward by not requiring curly braces `{}` whether the 
> block includes one or more lines.
> 
> In contrast, the requirement to use a colon after those keywords in Python is 
> a drawback!
> 
> The colon “:” doesn't improve readability but adds unnecessary complexity, 
> increases the potential for errors, and requires more effort to code. This is 
> because the requirement does not have a logical meaning while the block is 
> made obvious by indentation, so coders may forget to include the colon and 
> face errors.
> 
> This can be particularly frustrating for those who are used to coding in 
> languages such as C and C++, where blocks of code are traditionally indented 
> and no curly braces `{}` are used when the following tail is a singe-command 
> instruction.
> 
> The suggestion is removing the need by interpreter for the use of colon after 
> keyword syntaxes (and making it optional due to Backward Compatibility) in 
> the new revision of Python.
> 
> I believe this change would make Python code easier to read, less prone to 
> errors, and require less effort to code.
> 
> Thank you for your time and attention.
> 
> Best regards,
> Morteza Mirzakhan 
> ___
> 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/E7LCNY6LBWQ5HHI6BHWRDXFE2MMIBZCC/
> 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/TH2SHGK6FIVBPUSWCUW42VMWNDEOLLTR/
Code of Conduct: http://python.org/psf/codeofconduct/


[Python-ideas] Re: Conditional 1-line expression in python

2023-08-05 Thread Dom Grigonis
Ok.

> On 5 Aug 2023, at 16:02, Chris Angelico  wrote:
> 
> On Sat, 5 Aug 2023 at 22:49, Dom Grigonis  wrote:
>> 9. Python has a syntax for conditional expressions. Learn it, if you want to 
>> use Python. No need to create multiple syntaxes for the same thing.
>>  * Hello Chris A? :)
> 
> Nope.
> 
> ChrisA
> ___
> 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/6GDLIOAM6BBF4SNO4MVVYU64UBCPZCCQ/
> 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/JLZBOLJFDD5IVX7WY54RLRHXF4LVMK7Y/
Code of Conduct: http://python.org/psf/codeofconduct/


[Python-ideas] Re: Conditional 1-line expression in python

2023-08-05 Thread Dom Grigonis
Thank you for reminding Rob.

Results are not surprising. Although 10 years ago people preferred C-style, by 
this time everyone is used to python’s expression.

By this time, after having discussions, I myself, am not a proponent of such 
change. It was more about possibility of having 2 conditional expressions, not 
changing it. It was just a part of my more general investigation. My current 
position is that “deferred evaluation” (if implemented with brief syntax) will 
cover many (sometimes seemingly unrelated) cases as a side effect of its main 
intent.

Ok, results.
Not many respondents. 48 in total. Average 24 per question. (Not sure how that 
happened.)

1. Which conditional expression is more readable?
83%: var = foo if condition else bar
17%: var = condition ? foo : bar

2. Which conditional expression is more readable?
84%: var = (foo if foo is not None else default2) if condition else (bar if bar 
is not None else default2)
16%: var = condition ? (foo is not None ? foo : default1) : (bar is not None ? 
bar: default2)

3. Would you use more conditional expression statements if it was more like in 
C?
12%: yes
88%: no

Comments:
1. They are fine the way they are.
2. They're fine for occasional use, as your second example abundantly shows, 
nested conditionals are an abomination in the sight of beasts and men.
3. The C syntax is undecipherable gobbledegook to beginners or people coming 
from other languages without that same syntax. It is the opposite of Python's 
ideal of "executable pseudocode". The Python syntax is easily understandable to 
anyone who knows English as it follows English syntax: "What are you doing 
tonight?" "I'm going to the movies, if I manage to leave work on time, 
otherwise I'll just stay home.”
  * Is the english sentence “If I manage to leave work on time, I’m going to 
the movies, otherwise, I’ll just stay home” incorrect?
4. lol, I would never use that nested conditional expression. I'd definitely 
break it out into an if-else statement that had the conditional expressions. (I 
also break out nested list comprehension a into a for loop for readability in 
the rare cases I have them.)
5. Don't change them now! (this was hashed out 20 years ago!)
  * It was more about adding an alternative, not changing it.
6. Python conditional expressions are English, or very nearly. C ones, using a 
question mark which could mean anything, are obscure (unless perhaps you are 
very very familiar with them).
7. I do not
8. they won't change
9. Python has a syntax for conditional expressions. Learn it, if you want to 
use Python. No need to create multiple syntaxes for the same thing.
  * Hello Chris A? :)
10. Conditional expressions are always confusing
11. Syntax highlighting matters and adds to the inherent readability of 
Python's ansatz.

Thank you all for taking your time in these discussions and filling in this 
quick survey. This has helped me getting answers I was looking for. Hopefully, 
this wasn’t a waste of time from your perspectives either.


—Nothing ever dies, just enters the state of deferred evaluation—
Dg

> On 5 Aug 2023, at 09:22, Rob Cliffe  wrote:
> 
> When can we expect the results of your survey?  (I responded to it.)
> Best wishes
> Rob Cliffe
> 
> On 17/07/2023 21:41, Dom Grigonis wrote:
>> Hi everyone,
>> 
>> I am not very keen on long discussions on such matter as I do not think 
>> there is much to discuss: there is no technical complexity in it and it 
>> doesn’t really change or introduce anything new. It is only a matter of 
>> opinion & style/design preferences with respect to logical order and brevity 
>> of a statement.
>> 
>> So I thought, if anyone can be bothered on such question and instead of 
>> writing 3-minute e-mail, would take few seconds to answer 3-question poll.
>> 
>> https://q5yitzu62.supersurvey.com <https://q5yitzu62.supersurvey.com/>
>> 
>> Would be interesting to see if my preference is an outlier or not really.
>> 
>> 
>> Kind regards,
>> D. Grigonis
>> 
>> 
>> 
>> 
>> ___
>> Python-ideas mailing list -- python-ideas@python.org 
>> <mailto:python-ideas@python.org>
>> To unsubscribe send an email to python-ideas-le...@python.org 
>> <mailto:python-ideas-le...@python.org>
>> https://mail.python.org/mailman3/lists/python-ideas.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/NZVLR56BFMBJXE6GN2GWRXIG6ZVAAWZZ/
>>  
>> <https://mail.python.org/archives/list/python-ideas@python.org/message/NZVLR56BFMBJXE6GN2GWRXIG6ZVAAWZZ/>
>> Code of Conduct: http://python.org/psf/codeofconduct/ 
>&

[Python-ideas] Re: Proposal for get_or function in Python dictionaries

2023-07-24 Thread Dom Grigonis
2 of them are forms of brevity.

To me the whole picture is important. And the context as well.

Individual aspect becomes more important when it feels to be an outlier.

I.e.

In 1 line one can create a dictionary, initialise it with reasonable keys and 
2-values tuples and find the key of the maximum of tuple sums… Elegantly.

But one needs 3 lines of code to resolve default value.

This is an exaggeration, but serves to convey my point.

But again, this is not about this individual case. This thread has started from 
new dict.get method, and not by me. I am just trying to see what is the common 
factor as similar problems have been bothering me too.

To me by now, it is about custom user expressions.

—Nothing ever dies, just enters the state of deferred evaluation—
Dg

> On 24 Jul 2023, at 18:17, Chris Angelico  wrote:
> 
> On Tue, 25 Jul 2023 at 01:03, Dom Grigonis  wrote:
>> I think what would be nice to have is a set of dimensions that are deemed to 
>> be of importance when deciding on a language constructs.
>> plot(dim1, dim2, dim3)
>> dim1 - number of lines
>> dim2 - number of terms
>> dim3 - number of operations
>> dim4 - frequency of usage
>> dim5 - ...
>> 
> 
> Don't think I fully understand, but aren't three out of those four
> just different forms of brevity? Is that really so important to you?
> 
> ChrisA
> ___
> 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/6RF4PMZAZQM74OKWCX5HP7ZN5B4Z5C5U/
> 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/YQVMMSOCDWS5IFVZKY7Z42OD74WGV2NH/
Code of Conduct: http://python.org/psf/codeofconduct/


[Python-ideas] Re: Proposal for get_or function in Python dictionaries

2023-07-24 Thread Dom Grigonis
> 
> Seriously, what is the obsession with putting things on one line here?
> 
There is no obsession. It is more of a consideration of balance between 
operation complexity vs its verbosity.

> If it's because "it works better when there is a long list of such 
> assignments" then unless you actually show a real-world example, it's hard to 
> discuss the *actual* trade-offs.

First library that comes to mind, which has a high level constructor: 
https://github.com/pydata/xarray/blob/main/xarray/core/dataarray.py#L437 


> It's often an anti-pattern to have a function with that many arguments in the 
> first place, so refactoring the code may be a better option).
It often is, but at the same time unavoidable in some cases, i.e. high level 
APIs. Few examples, CLIs (e.g. poetry), constructors of high level objects.

I think what would be nice to have is a set of dimensions that are deemed to be 
of importance when deciding on a language constructs.
plot(dim1, dim2, dim3)
dim1 - number of lines
dim2 - number of terms
dim3 - number of operations
dim4 - frequency of usage
dim5 - ...

Of course, not all dimensions can be quantified. And to quantify some of them 
certain definitions would have to be decided on, e.g. what is an operation. 
Also, I do not know what those dimensions should be, they would ideally be 
decided by those who have a very good sense of python’s long-term vision.

Such information could be helpful in having productive discussions regarding 
such considerations and proposals.

In this case I am concerned with a balance of brevity vs complexity of python 
constructs, which is a core building block in a space of constantly increasing 
number of abstraction layers.


—Nothing ever dies, just enters the state of deferred evaluation—
DG___
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/RKMCQSJB36V2WGKABKKEB5SRB6YLIIXA/
Code of Conduct: http://python.org/psf/codeofconduct/


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

2023-07-23 Thread Dom Grigonis
It’s 2 options:

a) It is a special constant - the only one with such property. Then it would be 
used solely for this purpose. I don’t think you can prevent someone from using 
it for something else. But I don’t think this case of misusage is a big 
exception to the way things are. As this would be only such constant, it then 
should be used only for this purpose. Standard sentinels would be used for 
everything else and None could be left for cross-language cases, such as json 
null value and similar.

But as of now, it is not possible to do what I am referring to with either 
sentinels or None. The standard is to override default such as None with 
itself, witch means ‘NotProvided', but it actually is. Then that value is 
checked within the function’s body and if it is ’NotProvided’, then default is 
set. I appreciate that None value is singleton and technically it is the same 
one, but special value is useful if one was to have a more complex default 
argument and wanted to enforce it from outside, while retaining ability to 
specify it as well. It is simply cleaner than what is being done now. And 
without this PEP, I don’t think there would be a big case for it, but with this 
PEP, it seems more compelling as it seems to encourage more complex defaults.

So no, I don’t think it is likely that another special value would be needed. 
All the other “special values” can be handled with sentinels. If this case is 
not special enough, then (b) could work.

b) Property of a callable to specify an object which is treated in such manner 
as special constant in (a) or a decorator which emulates such behaviour. This 
might be even better approach as long as it is performant and reliable.

Decorator could be a good option, but that depends on how performant it is. If 
it’s the same as e.g. `getcallargs` then, at least to me, not a very attractive 
option.

But I think there might be case for special value as well.

But again, only my opinion, I don’t really have an issue with the way things 
currently are with function arguments. Just answered questionnaire regarding 
this PEP and this is my opinion.

——
I am more excited about deferred-eval, which if was implemented with neat 
syntax, would improve things for me in many different places in one go and from 
what I have seen would benefit many different areas and provide more neat 
solutions for several cases that came to this group & fairly elegant (although 
maybe not as pythonic) ones for several PEPs that were deferred or rejected.

DG

> On 23 Jul 2023, at 14:40, Richard Damon  wrote:
> 
> I think the question is, how is that fundamentally different than the value 
> "None". Once you create this "special value", some function will decide to 
> make it have a meaning as a passed in value, and then need a DIFFERENT 
> "special value" as a default.
> 
> On 7/23/23 1:13 AM, Dom Grigonis wrote:
>> Or maybe you are not listening to what I am saying.
>> 
>> It would only take effect for arguments, which have default value.
>> 
>> So.
>> dict().__setitem__(key, NotGiven)
>> type(NotGiven)
>> Exception(NotGiven)
>> getattr(NotGiven, name)
>> 
>> Ok, maybe there are some crucial functions, which have argument defaults. 
>> But again, there is another solution then, implement efficient decorator in 
>> standard library, maybe as part of sentinels, maybe as part of your PEP, 
>> maybe separately.
>> 
>> I never said that it isn’t hard to write low-level python code. I will do 
>> that when the time is right for me. And I am not claiming that it is 
>> possible. If you read my language, all of my doubts are clearly expressed. 
>> You just seem to read everything as black and white even when it is not so.
>> 
>> However, such statements are in no way valid arguments in such discussion. 
>> If my idea is not optimal, not necessary, no-one needs it or any other valid 
>> responses, why it is not a good one - I can accept it.
>> But commenting that “it makes no sense” without properly explaining to me 
>> why after giving it some thought - it’s not fair.
>> 
>> Also, if you looked at things from a bit more positive perspective, maybe 
>> you could come up with some nice new ways how it could be done. Maybe not 
>> exactly what I am proposing, but some alternative, which would make it work. 
>> Most likely something much better than I am proposing.
>> 
>> After all, I am trying to see how your PEP can be improved, because if it 
>> could be used in all cases, where None can be, then at least to me, it would 
>> be a no-brainer to use it instead and to adapt it as best practice.
>> 
>> DG
>> 
>>> On 23 Jul 2023, at 07:35, Chris Angelico  wrote:
>>> 
>>> On Sun, 23 Ju

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

2023-07-22 Thread Dom Grigonis
Or maybe you are not listening to what I am saying.

It would only take effect for arguments, which have default value.

So.
dict().__setitem__(key, NotGiven)
type(NotGiven)
Exception(NotGiven)
getattr(NotGiven, name)

Ok, maybe there are some crucial functions, which have argument defaults. But 
again, there is another solution then, implement efficient decorator in 
standard library, maybe as part of sentinels, maybe as part of your PEP, maybe 
separately.

I never said that it isn’t hard to write low-level python code. I will do that 
when the time is right for me. And I am not claiming that it is possible. If 
you read my language, all of my doubts are clearly expressed. You just seem to 
read everything as black and white even when it is not so.

However, such statements are in no way valid arguments in such discussion. If 
my idea is not optimal, not necessary, no-one needs it or any other valid 
responses, why it is not a good one - I can accept it.
But commenting that “it makes no sense” without properly explaining to me why 
after giving it some thought - it’s not fair.

Also, if you looked at things from a bit more positive perspective, maybe you 
could come up with some nice new ways how it could be done. Maybe not exactly 
what I am proposing, but some alternative, which would make it work. Most 
likely something much better than I am proposing.

After all, I am trying to see how your PEP can be improved, because if it could 
be used in all cases, where None can be, then at least to me, it would be a 
no-brainer to use it instead and to adapt it as best practice.

DG

> On 23 Jul 2023, at 07:35, Chris Angelico  wrote:
> 
> On Sun, 23 Jul 2023 at 14:08, Dom Grigonis  wrote:
>> 
>> IT IS AN OBJECT. Never said otherwise.
> 
> One that you can't do any of the operations I described. There is no
> way to use it as an object.
> 
>> `inspect.getcallargs` can seemingly be modified for such behaviour. I just 
>> wrote a decorator, which does what I proposed using `inspect` module for a 
>> chosen sentinel value. The issue is that it would be a bottleneck if used on 
>> any callable, which is continuously used. `inspect.getcallargs`, 
>> `signature`, `getfullargspec` are very expensive.
>> 
>> If that can be done, theoretically it should be able to be done at lower 
>> level as well. After all, behaviour of it should be modelled after what is 
>> happening at the function call.
>> 
> 
> Since you clearly are not listening to the discussion, I will leave
> you with one final recommendation: Write some code. Don't just claim
> that it's possible; write actual code that makes it happen. You will
> discover exactly how hard it is. If I am wrong, you will be able to
> PROVE that I am wrong, instead of merely claiming it.
> 
> ChrisA
> ___
> 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/TPY2JHOBXUQIRNRYUUBUX46Y3HS4GQVK/
> 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/RTXRKZWWTRPGYHQTIRNGB57RMRFGWDQR/
Code of Conduct: http://python.org/psf/codeofconduct/


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

2023-07-22 Thread Dom Grigonis
IT IS AN OBJECT. Never said otherwise.

`inspect.getcallargs` can seemingly be modified for such behaviour. I just 
wrote a decorator, which does what I proposed using `inspect` module for a 
chosen sentinel value. The issue is that it would be a bottleneck if used on 
any callable, which is continuously used. `inspect.getcallargs`, `signature`, 
`getfullargspec` are very expensive.

If that can be done, theoretically it should be able to be done at lower level 
as well. After all, behaviour of it should be modelled after what is happening 
at the function call.

> On 23 Jul 2023, at 06:58, Chris Angelico  wrote:
> 
> On Sun, 23 Jul 2023 at 12:20, Dom Grigonis  wrote:
>> 
>> 
>>> There is no way to have a value that isn't a value, in Python. The
>>> concept doesn't make sense and would break all kinds of things.
>>> (That's why, when a special function like __getitem__ has to be able
>>> to return literally anything, it signals "nothing to return" by
>>> raising an exception.)
>> 
>> I accept that it might be difficult to implement.
>> I see that it would break things at cpython.
>> Will definitely break some of the stdlib. E.g. inspect stuff.
>> It wouldn’t break any of the existing python code.
>> So yes, might not be a minor change.
>> 
>> Could it be done nicely and easily by someone with relevant experience? I 
>> don’t know.
>> 
>> 
>> But I fail to see why it doesn’t make sense - that’s a strong statement.
>> 
>> It would be a value, just a value that is treated with exception in this 
>> particular case.
>> There is definitely code at that level - resolving args, kwargs, dealing 
>> with “/" and “*” in relation to arguments provided, etc.
>> 
>> It would take effect only on keyword arguments with defaults, if so then 
>> fairly contained matter.
>> It could be a default of a keyword argument itself, would have a type and 
>> everything as any other object.
>> 
> 
> Okay. You now have an object that you can't do anything with, because
> it can't be a function argument. So...
> 
> Show me how you would put this value into a dictionary.
> 
> Show me how you would find out the type of this value.
> 
> Show me how you would refer to this in an exception.
> 
> Show me how you would access an attribute of this object.
> 
> Show me how you would do ANYTHING WHATSOEVER with this object.
> 
> It does not make sense to have an object that isn't an object. And in
> Python, every value *is* an object.
> 
> ChrisA

___
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/CFFEGHQNQRDA7EDS4ZJBWAWDPU64OYHH/
Code of Conduct: http://python.org/psf/codeofconduct/


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

2023-07-22 Thread Dom Grigonis

> There is no way to have a value that isn't a value, in Python. The
> concept doesn't make sense and would break all kinds of things.
> (That's why, when a special function like __getitem__ has to be able
> to return literally anything, it signals "nothing to return" by
> raising an exception.)

I accept that it might be difficult to implement.
I see that it would break things at cpython.
Will definitely break some of the stdlib. E.g. inspect stuff.
It wouldn’t break any of the existing python code.
So yes, might not be a minor change.

Could it be done nicely and easily by someone with relevant experience? I don’t 
know.


But I fail to see why it doesn’t make sense - that’s a strong statement.

It would be a value, just a value that is treated with exception in this 
particular case.
There is definitely code at that level - resolving args, kwargs, dealing with 
“/" and “*” in relation to arguments provided, etc.

It would take effect only on keyword arguments with defaults, if so then fairly 
contained matter.
It could be a default of a keyword argument itself, would have a type and 
everything as any other object.

___
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/YN3QPKPCN2HSTARQNXXHXZWJTH3AA5RI/
Code of Conduct: http://python.org/psf/codeofconduct/


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

2023-07-22 Thread Dom Grigonis
1. Not if it is exactly as described in PEP.
2. No.
3. -
4. Couple of points here. One check and one orthogonal idea, which would make 
this PEP very attractive to me.

I would definitely like use this functionality if both of below points were 
satisfied/achievable. If any of those weren't satisfied I might just default to 
current syntax as I like to have a default pattern, which I know is flexible 
enough to cover most if not all the cases that I encounter. Currently, I manage 
this particular area (which your PEP is concerned with) with `None` and 
`unittest.Sentinel` defaults and deal with them in function's body.

A.
Currently, if I write:
```
def foo(bar=A()):
pass

class A:
pass
```
I get an error. That is why having `bar=None` is advantageous. This works ok:

```
def foo(bar=None):
if bar is None:
bar = A()

class A:
pass
```

If PEP is aiming to replace the latter example, then it would be great if it 
kept all of its advantages. I.e. not having to change the definition order in 
the module, which could be preferred as it is for other reasons.

My best guess is that it works the same as the latter example, (given the 
expression can contain other arguments, which are not there yet) but just 
wanted to double check.

B.

And also to come back to my previous notice that there is no way to enforce the 
default in case of function chain with cascading arguments. You said it is a 
known limitation. Is there no easy & sensible approach to not have it? E.g.:

a) Any object which has certain dunder attribute, which evaluates to True?
b) NotGiven sentinel value which does exactly that.
c) A special constant, which, if present, at lower level makes things behave 
the same way as the argument wasn’t provided at all. Such constant could be 
very useful outside the scope of this PEP as well. Could be a great place to 
introduce such constant? And to me it seems it could be a well justified one, 
given it actually is special and does not fall under umbrella of generic 
sentinel values.

It would be great if it was to retain all the benefits of the latter example. 
Then (at least from my POV) this PEP would be an excellent addition, and I am 
most likely be using it now if it existed.

Regards,
DG
___
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/7DCPF624EEATZ5IRCSCHDIXDTCT2WYB3/
Code of Conduct: http://python.org/psf/codeofconduct/


[Python-ideas] Re: Conditional 1-line expression in python

2023-07-21 Thread Dom Grigonis
Did not mean that it is easy, but it seems achievable and although a deep dig 
might be needed, my gut feeling is that it is possible to achieve this fairly 
elegantly. I might be wrong ofc.

However, this seems orthogonal to everything else I wrote. Just added it for 
the sake of completeness, this could be a nice one to have further along the 
lines, given def-eval was implemented. Then complete statements would be 
possible via expressions with full functionality.

> On 21 Jul 2023, at 12:19, Chris Angelico  wrote:
> 
> On Fri, 21 Jul 2023 at 19:15, Dom Grigonis  wrote:
>> However, it could be done differently as well. If `Break()` takes effect in 
>> the scope where it is evaluated. Then:
>> 
> 
> You say that as if it's easy. How would this work? How do you have a
> function that, when called, causes the current loop to be broken out
> of?
> 
> ChrisA

___
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/62WEK5BVRSXJ7TPOK4M7BDPDVDTQNZKL/
Code of Conduct: http://python.org/psf/codeofconduct/


[Python-ideas] Re: Conditional 1-line expression in python

2023-07-21 Thread Dom Grigonis
Having said that,

What about a mid-ground approach?

Simply have a `deferred` type, which only gets evaluated if it is explicitly 
asked for. It builds a graph in the same way as dask, but it does not act as a 
proxy, but rather evaluates if explicitly asked.

From technical perspective, it would be the same as dask - non-invasive so 
would have minimal to none impact on existing code. One difference would be 
that the object would not manage operations, but rather leave it as expression 
at lower level of python.

From user’s perspective it would be similar to lambdas or dask, except with 
convenient syntax and seamless integration to existing code.

E.g.
a = `1`
print(type(a))  # 
print(type(a.graph()))  #  
print(a.eval()) # 1
a
print(type(a))  # 
print(!a)   # 1
print(type(a))  # 
b = !a
print(type(b))  # int
print(!1)   # 1
c = `a + 1`
d = `c + 2`
e = `c + d` # simply builds graph
print(eval(e))  # 7 (this is only used if one is sure that it is 
)
print(!e)   # 7 (this untangles if  or just pass through 
for anything else)

So no magic really, pretty straight forward.

Benefits for dask-like applications is to have a lower level & more performant 
deferred object with API to customise evaluation. For such applications 
evaluation would be done via `eval(obj)` or `obj.eval()` as it strictly has to 
be  object and should fail if it’s not.

While convenient builtins would be useful for expression building, Infix 
operators and similar applications. In this case it does act very similarly as 
lambda, but solves a few of lambda’s inconveniences:
1) if using lambda/callables for this purpose, then can not use them as values. 
Same argument as for async/await vs using yield. Simply another layer of depth 
is needed to remove ambiguity.
2) Syntax is too cumbersome - something properly concise IMO should be 
available for it to be convenient.
3) More performant operations than e.g. `isinstance(value, Callable)`.

Function without arguments could be converted to  via decorator or 
multiline expression could be defined via

```
a = 1
b = a + 1
b
```
———
Expressions would naturally be evaluated at the scope of their definition. 
Nothing new.

———
Regarding Break & Continue:

Can still be achieved:

from statements import Break


def ifelse(cond, if_true, if_false):
if cond:
return !if_true
else:
return !if_false

a = 0
while True:
# This would require to be mindful about conditional values
a += ifelse(a < 5, `expr()`, False) or Break(return_value=0)
# or for it to be “perfect", PEP505 is needed
a += ifelse(a < 5, `expr()`, None) ?? Break(return_value=0)
However, it could be done differently as well. If `Break()` takes effect in the 
scope where it is evaluated. Then:

from statements import Break


def add_or_break(cond, if_true, break_return):
if cond:
return if_true
else:
return `Break(return_value=break_return)`

a = 0
while True:
a += !(add_or_break(a < 5, `expr()`, break_return=0))
———

So these would potentially provide a fairly flexible toolkit for expression 
building and seemingly covers all the cases that I was looking at including 
reasonable route to achieve https://peps.python.org/pep-0463/ 
<https://peps.python.org/pep-0463/>.

And it might be a feasible approach for deferred evaluation. Just not sure if 
this covers the needs that it is aiming to fulfil.


DG
> On 21 Jul 2023, at 10:31, Dom Grigonis  wrote:
> 
> This is very much implementation dependent. And I do not have a big opinion 
> here as I certainly haven’t spent enough time to have one. I am just 
> considering functionality from user’s perspective for the time being.
> 
>> Let's tackle just this one part for a moment. What does "ensure_eval"
>> do? Evaluate a proxy object but not evaluate anything else?
> 
> In case of the library I used, it would look something like:
> 
> def ensure_eval(x):
> if isisnstance(x, Proxy) and x.unevaulated:
> x.evaluate()
> return x
> 
>> This should always succeed, right? Well, what if x is itself a Proxy
>> object? How does it know not to reevaluate it?
> 
> Not necessarily. I mean, yes, but only if deferred evaluation is done by 
> actually replacing value in the namespace dictionary. In case of this 
> example, where this specific package is used, it is not so and is not 
> intended to be so.
> 
> When operation is performed, the value is evaluated and returned, but it 
> remains proxy object. So if lazy is nested, the whole nesting is evaluated on 
> first operation which needs its value.
> 
> I see this one as “decision to be made” as opposed to “reason why it’s not 
> working”.
> 
> I am not sure about the “right” approach h

[Python-ideas] Re: Conditional 1-line expression in python

2023-07-21 Thread Dom Grigonis
This is very much implementation dependent. And I do not have a big opinion 
here as I certainly haven’t spent enough time to have one. I am just 
considering functionality from user’s perspective for the time being.

> Let's tackle just this one part for a moment. What does "ensure_eval"
> do? Evaluate a proxy object but not evaluate anything else?

In case of the library I used, it would look something like:

def ensure_eval(x):
if isisnstance(x, Proxy) and x.unevaulated:
x.evaluate()
return x

> This should always succeed, right? Well, what if x is itself a Proxy
> object? How does it know not to reevaluate it?

Not necessarily. I mean, yes, but only if deferred evaluation is done by 
actually replacing value in the namespace dictionary. In case of this example, 
where this specific package is used, it is not so and is not intended to be so.

When operation is performed, the value is evaluated and returned, but it 
remains proxy object. So if lazy is nested, the whole nesting is evaluated on 
first operation which needs its value.

I see this one as “decision to be made” as opposed to “reason why it’s not 
working”.

I am not sure about the “right” approach here. Actually replacing deferred 
object with a value does sound invasive, although given there was a way to do 
it elegantly and without loss in performance, it seems to be more robust and 
eliminates maintenance of proxy object.

So the big question is, which of the 2 approaches to take:
1) Implementing a robust proxy object.
Less depth more breadth - ensuring proxy works with all objects / coming up 
with protocols, which have to be implemented for non-standard types to be 
compatible.
In this case both of assertions will and should fail, although `assert y is 
y_` will always pass.

Example from library:
obj = Proxy(lambda: 1)
obj2 = Proxy(lambda: obj)
obj is obj2 # False
print(obj == obj2)  # True

2) Replacing deferred evaluation with it’s value.
in this case, a fair bit of low level decisions such as the one you 
indicated would have to be made, a lot of deep strings to pull
In this case, it very much depends how “is”, “type” and other `things` 
behave with deferred objects. So if `x` is a proxy, and ‘is’ treats proxy 
object and not it’s value (which is reasonable), then assertions will and 
should fail. However, unraveling the whole stack on first evaluation does 
simplify things a bit.Then ` y_ = ensure_eval(y)` in your example is a 
redundant line. In practice, if deferred evaluation is used, one would need to: 
`assert  ensure_eval(x) is ensure_eval(y)`. Also, looking at deferred eval RST 
doc, the suggested mechanics are that expression is evaluated if “later” is not 
re-called. So in theory, it might be reasonable to have `x = later expr() 
 x = later later later expr()`. Instead of evaluating the whole stack, 
just not allowing it to grow in the first place. Then builtin `ensure_eval` is 
then straight forward single operation at C level, which would mostly be used 
on low level checks, such as asserts in your examples. It could even have its 
syntax instead of builtin function, given there are only 2 entry points 
(definition of deferred & ensuring it’s evaluation). E.g.
def expr():
print('Evaluating')
return 1

a = `expr()`
b = `a` # carry over lazy, but it's a new object at C level
assert a is b   # False
assert !a is !b # True
assert a is b   # True



> On 21 Jul 2023, at 08:46, Chris Angelico  wrote:
> 
> On Fri, 21 Jul 2023 at 11:08, Dom Grigonis  wrote:
>> Also, can't find a way to ONLY force evaluation without any additional 
>> operations in this specific library. A simple callable which evaluates if 
>> unevaluated & returns would do. Then:
>> 
>> def IF(condition, when_true, when_false):
>>if condition:
>>return ensure_eval(when_true)
>>else:
>>return ensure_eval(when_false)
>> 
>> Controls evaluation if deferred objects are provided, but can also be used 
>> with `normal` values.
>> 
> 
> Let's tackle just this one part for a moment. What does "ensure_eval"
> do? Evaluate a proxy object but not evaluate anything else? That seems
> simple, but might very well be straight-up wrong. Consider:
> 
> def test_proxy(x):
>x_ = Proxy(x)
>y = ensure_eval(x_)
>y_ = ensure_eval(y)
>assert x is y
>assert x is y_
> 
> This should always succeed, right? Well, what if x is itself a Proxy
> object? How does it know not to reevaluate it?
> 
> ChrisA
> ___
> 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/arch

[Python-ideas] Re: Conditional 1-line expression in python

2023-07-20 Thread Dom Grigonis
That is where I got to really. Ability to construct one’s own expressions, 
where evaluation can be controlled. And found out that deferred evaluation is 
what would potentially provide exactly what is needed for this.

Making use of ‘function’ protocol seems appropriate as I don’t think inventing 
any extensive syntax is justified.
from lazy_object_proxy import Proxy

value = Proxy(lambda: expr())
# If this could be written in a more concise form. e.g.:
value = `expr()`
# then it would be worthwhile constructing and making use of VB-like expressions
def IF(condition, when_true, when_false):
if condition:
return when_true
else:
return when_false

def expr1():
print('__expr1__')
return 1

def expr2():
print('__expr2__')
return 2

result = IF(True, `expr1()`, `expr2()`)
# Expressions would only be evaluated when certain usage takes place

# This works fairly nicely, but inconvenience of it is a dealbreaker (to be 
used for such cases)
result = IF(True, Proxy(lambda: expr1()), Proxy(lambda: expr2()))
# Not yet evaluated
print(result + 1)
# Now it is
Also, can't find a way to ONLY force evaluation without any additional 
operations in this specific library. A simple callable which evaluates if 
unevaluated & returns would do. Then:
def IF(condition, when_true, when_false):
if condition:
return ensure_eval(when_true)
else:
return ensure_eval(when_false)
Controls evaluation if deferred objects are provided, but can also be used with 
`normal` values.

> On 20 Jul 2023, at 22:51, Random832  wrote:
> 
> On Mon, Jul 17, 2023, at 16:41, Dom Grigonis wrote:
>> Would be interesting to see if my preference is an outlier or not really.
> 
> I think this is a false dichotomy. We should consider VB-like conditional 
> expressions if(condition, when_true, when_false) 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/FZBHN6DVTH2IW4OZH4R36EYZWRRMEYJL/
> 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/QISXXUFM6NJJHR3O6MPOWRTS5BQSZM3J/
Code of Conduct: http://python.org/psf/codeofconduct/


[Python-ideas] Re: Proposal for get_or function in Python dictionaries

2023-07-20 Thread Dom Grigonis
Ok, this is tricky.
So pretty much impossible, given that `Break`, if it was to work has to be 
evaluated in reference scope, while other delayed objects in their definition 
scope.

--
Back to deferred evaluation.

--
Giving it a rest for a while. Thank you for your patience.


> On 20 Jul 2023, at 12:38, Chris Angelico  wrote:
> 
> On Thu, 20 Jul 2023 at 19:34, Dom Grigonis  wrote:
>> And ideally, adding 2 builtin(or imported from stdlib) functions: `Break` 
>> and `Continue`, which if called act as `break` and `continue` statements.
>> 
> 
> How would they work? Would every function call have to provide the
> possibility to return to a location that wasn't where you would
> otherwise go?
> 
> if random.randrange(2):
>func = Break
> else:
>def func(): pass
> 
> def wut():
>for i in range(1, 10):
>if i % 3: func()
>print(i)
> 
> wut()
> 
> Please, tell me how this would behave.
> 
> ChrisA

___
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/RTKFGBNVJ2UQSMFTFNAHFB7HS674GI4B/
Code of Conduct: http://python.org/psf/codeofconduct/


[Python-ideas] Re: Proposal for get_or function in Python dictionaries

2023-07-20 Thread Dom Grigonis
I have looked more properly at deferred evaluation and late-bound defaults. 
Deferred-eval is overkill for what I need and isn’t likely to come about soon, 
while deferred only solves a very small part of what I am looking at. Also, it 
lacks ability to enforce default from outside, which is a bit of a dealbreaker 
to me.

Sooo…

I have come up to a conclusion that what would shut me up is a shorthand syntax 
for lambda. Either:
1) Ability to assign it to a different name
or MUCH MORE preferably
2) lambda: expr() == `expr()` == ?(expr()) == ???. Anything concise and 
sensible would do.

lambda pretty much does the trick, but syntax is too awkward to use for such 
applications.

And ideally, adding 2 builtin(or imported from stdlib) functions: `Break` and 
`Continue`, which if called act as `break` and `continue` statements.

> On 20 Jul 2023, at 11:11, Greg Ewing  wrote:
> 
> On 20/07/23 6:30 pm, James Addison via Python-ideas wrote:
>>result = default if bar is None else bar
>>or if you prefer
>>result = bar if bar is not None else default
> 
> Would it shut anyone up if we had another logical operator:
> 
>x otherwise y
> 
> equivalent to
> 
>x if x is not None else y
> 
> ?
> 
> -- 
> Greg
> 
> ___
> 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/R55FL6U5RFMPLP6NWE4IMMLNR4OLVGTF/
> 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/EX7B7LYIAL6XBPWCCCAC2IYUPVCY7HRJ/
Code of Conduct: http://python.org/psf/codeofconduct/


[Python-ideas] Re: Proposal for get_or function in Python dictionaries

2023-07-20 Thread Dom Grigonis
Thanks, thats truly useful to keep in mind.

> On 20 Jul 2023, at 09:48, anthony.flury  wrote:
> 
> 
> The challenge with anything like 
> 
> result = default if bar is None else bar
> 
> or 
> result = bar if bar else default
> 
> or even 
> 
> result = bar is None ? default : bar
> 
> 
> is that sure default is only evaluated once - but in all cases 'bar' is 
> evaluated twice, and if bar is a function call then no parser is clever 
> enough to diagnose all possible side effects of calling bar() twice, or even 
> detect that bar can be cached, so it will always be called twice.
> 
> In Python then a better way might be 
> 
> result = temp := bar() if temp else default 
> 
> This way only bar() and default are evaluated and invoked once.
> 
> 
> 
> -- Original Message ------
> From: "Rob Cliffe via Python-ideas"  <mailto:python-ideas@python.org>>
> To: "Dom Grigonis" mailto:dom.grigo...@gmail.com>>; 
> "Jothir Adithyan" mailto:adithyanjot...@gmail.com>>
> Cc: python-ideas@python.org <mailto:python-ideas@python.org>
> Sent: Monday, 17 Jul, 23 At 16:09
> Subject: [Python-ideas] Re: Proposal for get_or function in Python 
> dictionaries
> 
>  
>  
>  
> On 15/07/2023 21:08, Dom Grigonis   wrote:
>  
>  
>   Just to add. I haven’t thought about evaluation. Thus, to 
> prevent   evaluation of unnecessary code, introduction of C-style 
> expression   is needed anyways:   
>  
>
>  
>
> 1. result = bar   is None ? default : bar
>  
>
>  
>  
> 
>  
>  
> The below would have to evaluate all arguments,   thus not achieving 
> benefits of PEP505.
>  
>
>  
>
> 2. result = ifelse(bar is None, default, bar)
>  
>
>  
>  
> 
>  
>  
> 
>  
>  
> So I would vote for something similar to:
>  
>
>  
>
>  
> result = bar is None ? default : bar
>
>  
>
>  
>  
> 
>  
>  
> Where default and bar is only evaluated if needed. Although   not to 
> the extent as initially intended, it would offer   satisfiable 
> solutions to several proposals.
>  
>
>  
>  Well, default is only evaluated if needed; bar is always evaluated.
>  What is wrong with the Python equivalent
>  
>  result = default if bar is None else bar
>  or if you prefer
>  result = bar if bar is not None else default
>  
>  Perhaps you didn't know about this construction?
>  It does exactly the same as the C version and is more readable.  Or 
> am I missing something?
>  Best wishes
>  Rob Cliffe
>  
> ___
> 
> Python-ideas mailing list -- python-ideas@python.org 
> <mailto:python-ideas@python.org>
> 
> To unsubscribe send an email to python-ideas-le...@python.org 
> <mailto:python-ideas-le...@python.org>
> 
> https://mail.python.org/mailman3/lists/python-ideas.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/4QBAYBAT6EZFILNS2MCK3D6XW4LNRDZ5/
>  
> <https://mail.python.org/archives/list/python-ideas@python.org/message/4QBAYBAT6EZFILNS2MCK3D6XW4LNRDZ5/>
> 
> Code of Conduct: http://python.org/psf/codeofconduct/ 
> <http://python.org/psf/codeofconduct/>
> 
> 
> 
> -- Anthony Fluryanthony.fl...@btinternet.com 
> <mailto:anthony.fl...@btinternet.com>
___
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/PUKJNAGRRUGW3V4DUWNSQ3BZRLUJH5YT/
Code of Conduct: http://python.org/psf/codeofconduct/


[Python-ideas] Re: Proposal for get_or function in Python dictionaries

2023-07-20 Thread Dom Grigonis

>   result = bar or default

I used to do this, but dropped this habit. Just to be on the safe side if in 
the future I extend bar to take value for which truth test evaluates to False. 
And for consistency across the codebase.

___
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/JBNJWEDWCACDOL54BZSTPDZ6TI64KY7T/
Code of Conduct: http://python.org/psf/codeofconduct/


[Python-ideas] Re: Proposal for get_or function in Python dictionaries

2023-07-20 Thread Dom Grigonis

> I think that's reasonable.  But I don't think Python is the language
> for that.  There are too much existing contrasts, such as loop vs.
> comprehension and conditional statement vs. ternary expression.  Guido
> deliberately chose to vary those expression syntaxes from their
> statement equivalents.  I don't think there's any ambiguity if you say
> that wrapping a compound statement in parentheses creates an
> expression with restricted syntax (namely, the statements the syntax
> controls become expressions):
> 
>(if condition_1: expression_1
> elif condition_2: expression_2
> else: expression_else)
> 
>[for element in iterable: if condition: expression(element)]
> 
> But Guido (and I think everybody else) thought "N! not *that*!”


Yes, I realise that there is no way back as different direction has already 
been taken. So I am not (and have not been) proposing any changes there, just 
trying to find ways to get to where I would like to with python.

>> ??
>> `Deferred evaluation`, if was to gain traction in a similar manner
>> as e.g. `annotations` are now experiencing, would cover all of the
>> cases I was looking at & more.
> 
> As Chris was saying earlier, it's at minimum going to take some genius
> creativity to "cover all and more", because a closer look at what
> people mean by "deferred" shows that in different cases it is
> semantically different.  In particular, there are a number of choices
> that Chris made in PEP 671 that aren't compatible with several of the
> proposals for Deferred objectss, while Deferreds can't give some of
> the benefits of the PEP.

I have read both PEP671 and 
https://github.com/DavidMertz/peps/blob/master/pep-.rst 
, but can’t see 
what benefits does PEP provide, that def-eval can not. I see that they are not 
the same in implementation even orthogonal, but it seems that PEP671, maybe not 
as elegantly, but can achieve the same result.

> I didn't like that PEP then; I was in the camp of "let's get genuine
> Deferreds, and use them to cover some of the use cases for PEP 671."
> I don't actively want the PEP now.  def-time evaluation of defaults
> doesn't catch me and I haven't had trouble teaching it.  The
> "if arg is None: arg = Mutable()" idiom is rare enough that I prefer
> it to adding syntax to the already complex function prototype.

That idiom is only 1 example. See my e-mail with examples of how def-eval 
relates to several PEPs and requests that came up recently in this group. It 
would improve things in many areas. E.g. infix operators might become an 
actually useful thing instead of being just a cool thing to take a look at. 
IMO, infix pattern is too cumbersome to be used as actual operator, but would 
be perfect for defining binary and maybe ternary expressions.

If it’s usage would be as in “def-eval rst", it would potentially bring about a 
new paradigm to the way I do things. Especially if it was well optimised and 
had a concise syntax.
# something similar to
`expr`
# or
?(expr)
> But if you think it might be a good idea, I encourage you to take a
> close look.  For some use cases it's definitely an improvement, and at
> least I won't vocally oppose the PEP now -- haven't seen any progress
> on "true Deferreds".  Perhaps others' opposition has softened, too.
> Adding another proponent is another way to help get it going again.

I am not sure if I would be the right person for this, but if you know any good 
places (discussions or attempts) to look at apart from that “def-eval rst”, I 
would take a look. So far I am only excited about it from user’s perspective…

DG

___
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/MPZZ4ZYAIEQBNV6FK3WAH2JTTUVFDTCN/
Code of Conduct: http://python.org/psf/codeofconduct/


[Python-ideas] Re: Proposal for get_or function in Python dictionaries

2023-07-19 Thread Dom Grigonis
I understand.

As I have already said, I am not exactly proposing more terse if-else 
expression. It’s just where I got to going down the path of several PEPs, 
proposals and my own 'struggles’.

My point was more along the lines, that these are the examples, where several 
users and PEP writers think python can be improved. It looked like, having more 
terse ternary expression would get all of these half the way in certain 
dimensions that they improve on. I see that dimensions that I picked up upon 
were not exactly the same ones that were aimed at (at least in PEPs).

What I was aiming at is getting more information and ideas and tried to pin 
point common root between all of them, which seemed to be the same which I, 
myself is battling with, but can't pin-point.

Although, I do no deny, I got a bit sidetracked with ternary expression. :)

Verbosity, although important to me, but is of secondary importance. Well, at 
least in ternary expression itself and number of characters. But, when a simple 
thing such as dealing with default of 1 argument takes 4 lines of code, it does 
bother me.

——
In reality, I do not think changing ternary expression would be worth the buck 
anyway. The thing I am not content with (to make it common practice in my 
coding style) is inconsistencies between a) order of terms and b) 
functionality, of statements and their analogous expressions. If they were 
consistent, in a similar way that I wrote in a previous e-mail, it might do the 
trick.

But even then it wouldn’t cover all the cases that I am looking at. It seems to 
be a bit wider.

——
 `Deferred evaluation`, if was to gain traction in a similar manner as e.g. 
`annotations` are now experiencing, would cover all of the cases I was looking 
at & more.

Maybe it would be a win-win. At the core, python would retain its 
expressiveness (which to me personally is more than sufficient compared to 
other dimensions that are important in the context of how I use python and 
where I aim to get with it), but there would exist "a way" for those who 
want/need to write very logically consistent, optimised and concise code.


Thank you for reply,
DG

> On 19 Jul 2023, at 09:25, Stephen J. Turnbull 
>  wrote:
> 
> Dom Grigonis writes:
> 
>>> But "encourages one-liners" is generally considered an
>>> anti-pattern in Python.  Let's see why,
> 
>> Here I am a bit confused, how is this the case in the language
>> containing list comprehensions?
> 
> I don't think of list comprehensions in terms of line count.  I often
> write multiple-line list comprehensions and genexps.  Especially when
> nested or with an 'if' clause,, I often use multiple lines even though
> the whole thing would fit on a single line because I feel it expresses
> the structure better.  Comprehensions and genexps are an especially
> nice context for that, because they are always equipped with
> parentheses, so you are not constrained by the usual rules of
> indentation, and don't need line continuing backslashes.
> 
> Also consider
> 
>for x in list1: list2.append(foo(x))
> 
>list2.extend([foo(x) for x in list1])
> 
> The second form is one character less concise than the former, yet far
> more expressive.  Once genexps were introduced, we could make it one
> character more concise than the for loop with
> 
>list2.extend(foo(x) for x in list1)
> 
> but it's unclear that this is an improvement over the list
> comprehension.  (That's probably due to the facts that I don't use
> genexps that often, and that I think of list.extend as a concatenation
> of lists even though it's documented as taking an iterable.  If most
> people have more facility with genexps than I do, it's a small but
> clear improvement.)
> 
>> I would understand if it was swapped with “bad quality & unreadable
>> 1-liners”.
> 
> That dodges the question of when does a one-liner cross over to "bad
> quality and unreadable", though.
> 
>> Also, I would rephrase “encourage 1-liners” to “promote readable
>> and expressive structures that are balanced in their brevity versus
>> complexity”.
>> I am not encouraging 1-liners,
> 
> Well, the word "one-liner" has a history.  "One-liner" is a category
> by that name in the Obfuscated C Contest, and Perl programmers often
> take pride in how much they can accomplish on the command line,
> without starting an editor or interactive interpreter.  Some of us
> old-timers are going to take it the wrong way.  I'm not sure if less
> indoctrinated people would take it to mean "readable and expressive
> structures that are balanced in their brevity versus complexity". :-)
> 
> In any case, whether you intend it or not, making the ternary
> expression more terse w

[Python-ideas] Re: Conditional 1-line expression in python (Dom Grigonis)

2023-07-18 Thread Dom Grigonis
Coming back to deferred evaluation,

https://peps.python.org/pep-0671/ <https://peps.python.org/pep-0671/>
These 2 aren’t really orthogonal in functionality. Maybe in implementation.
But PEP671 is a certain subset of deferred evaluation as it can achieve the 
same with 1 extra line at the start of the function’s body.

--
Most importantly:
If deferred evaluation had a CONCISE keyword/operator, it would actually solve 
my (and several other) requests/proposals.
def ifelse(cond, if_true, if_false):
return if_true if cond else if_false

IF = ifelse


def __init__(self, a=None, b=None):
self.a = ifelse(a is not None, a, ?Foo())
self.b = IF(b is not None, b, `Bar()`)
hopefully it would not be `later`...

This way users could define their own constructs via callables & control order, 
evaluation and brevity to their liking.

--
https://peps.python.org/pep-0463/ <https://peps.python.org/pep-0463/> could 
also be achieved with a function.
def trye(expr, err, default):
try:
return expr
except err:
return default

value = trye(`dct[key]`, KeyError, 'No Value')

--
https://peps.python.org/pep-0505/ <https://peps.python.org/pep-0505/>
def naw(a, b):
if a is not None:
return a
else:
return b

a = None
naw(a, `expr()`)

# OR Infix operator:
a |naw| `expr()`
It starts to seem that it would solve all of the things I was looking at to a 
satisfactory degree (given a concise keyword obviously...).

--
With certain additions, could even break & continue...
from statements import Break, Continue

def ifelsebc(cond, val, else_break=True):
if cond:
return val
elif else_break:
return `Break(0)`
else:
return `Continue(0)`

a = 0
while True:
a += ifelsebc(a < 5, 1, else_break=True)

print(a)# 5
The issue with lambda is that it has to be handled differently, or code has to 
check for its possibility, while deferred evaluation integrates seamlessly into 
already existing code.

IMO, it would be an excellent addition. And all this would come as a side 
effect, rather than main intent (which is dask.delay functionality if I 
understood correctly).

How likely you think is it going to happen? Given PEP number it doesn’t sound 
very promising...

> On 18 Jul 2023, at 09:45, Chris Angelico  wrote:
> 
> On Tue, 18 Jul 2023 at 16:25, Dom Grigonis  wrote:
>> 
>> Yes, thank you, this would definitely be nice to have.
>> 
>> Although, "A generic system for deferred evaluation has been proposed at 
>> times“ sound better if it was a superset of PEP505. Could you refer me to 
>> any resources about such considered system?
>> 
> 
> Hrm, you'd probably have to scour the archives. It's one of those
> things that comes up periodically and spawns a discussion thread, but
> never really gets to a concrete proposal. The best I can find is this,
> which never even got submitted to the official PEP repository, but
> it's someone's attempt to make something that could potentially become
> one, so it's a start.
> 
> https://github.com/DavidMertz/peps/blob/master/pep-.rst
> 
> The trouble is, it's really REALLY hard to pin down useful semantics
> for deferred evaluation. We already have lambda functions, which cover
> a lot of situations, leaving a lot of uncertainty as to what's being
> handled by this new proposal - and since no proposal ever truly comes
> from a single person, that results in a certain amount of chaos.
> 
> ChrisA

___
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/YRGQV3U2GJFHYN2LXLW7PCP7MH22LFWI/
Code of Conduct: http://python.org/psf/codeofconduct/


[Python-ideas] Re: Proposal for get_or function in Python dictionaries

2023-07-18 Thread Dom Grigonis
Ok, fair I am confusing definitions.

Expressiveness, defined by modern dictionary: “the quality of effectively 
conveying a thought or feeling”.

Let me correct myself.

Although I see that expressiveness is important, I think variable:

Functionality / verbosity - can be as important.

> On 18 Jul 2023, at 23:59, Chris Angelico  wrote:
> 
> On Wed, 19 Jul 2023 at 06:41, Dom Grigonis  wrote:
>> 
>> When you put it from this perspective, it seems to make sense, however, I do 
>> not agree.
>> 
>> To me, from first principles it seems it’s all about condensing more 
>> complexity in smaller modular packages.
>> 
>> That is why I am a bit confused, when someone argues that it is not about 
>> conciseness, but about expressiveness.
> 
> You're confused, yet you refuse to accept that you might be wrong. I
> don't think there's any point me continuing to discuss this with you.
> 
> ChrisA
> ___
> 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/M76SNAINFPIVM6NLVZAAKCTJTM2NRCVG/
> 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/H53ZTUOCS7VS4OAFGOMXURL46EB22BWV/
Code of Conduct: http://python.org/psf/codeofconduct/


[Python-ideas] Re: Proposal for get_or function in Python dictionaries

2023-07-18 Thread Dom Grigonis
When you put it from this perspective, it seems to make sense, however, I do 
not agree.

To me, from first principles it seems it’s all about condensing more complexity 
in smaller modular packages.

Leaving modularity aside, condensing more complexity in smaller packages in 
programming area is most often expressed via abstractions. Starting from binary 
we build more expressive components and applications, where each layer uses 
less and less code to do more and more complex things.

Yes, when you increase complexity without increasing the size - you say 
expressiveness.
But when you make package smaller without increasing complexity - you say 
conciseness.

So "expressiveness ~ 1/conciseness" if both aspects of phenomena are taken into 
account.

And decreasing number of characters is not conciseness, but rather 1 dimension 
of it, nevertheless important.

That is why I am a bit confused, when someone argues that it is not about 
conciseness, but about expressiveness.

I see the POV, that say ok x-size, y-expressiveness, however I think in this 
case, it is not expressiveness, but rather functionality.

So x-size(however one defines it), y-functionality.
Expressiveness = y/x
Conciseness = x/y
Thus, expressiveness = 1 / conciseness.

Maybe I am not using the terminology correctly (seems right to me, given 
etymology of these words), but this is just to explain what I meant.


> On 18 Jul 2023, at 18:34, Paul Moore  wrote:
> 
> On Tue, 18 Jul 2023 at 16:13, Dom Grigonis  <mailto:dom.grigo...@gmail.com>> wrote:
> To me, they are in the inverse relationship.
> 
> Terseness ~ 1 / expressiveness.
> 
> No, they are unrelated (in general).
> 
> Terseness is nothing more than "can I use fewer characters?" and is almost 
> always the wrong thing to do in isolation (yes, if things get *yoo* verbose 
> they can be hard to comprehend, but that's about going to extremes, not about 
> terseness as such).
> 
> Expressiveness is about matching the *concepts* involved to the problem. So 
> list comprehensions are expressive because they declaratively say what the 
> content of the list should be, and avoid the unnecessary concepts around how 
> you build the list. It's irrelevant how many characters are involved, what 
> matters is that you can omit saying "first create an empty list, now add 
> elements like  one by one..."
> 
> Paul

___
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/6YRQLO74MSD3F3IJEWXIOJ7BOOHNELSE/
Code of Conduct: http://python.org/psf/codeofconduct/


[Python-ideas] Re: Proposal for get_or function in Python dictionaries

2023-07-18 Thread Dom Grigonis
To me, saying it’s about expressiveness but not brevity sounds similar to e.g. 
“we are in compliance with green policies of EU, but we are not making effort 
to save nature.”

Well, you might not consciously intend to save nature, but those who gave you 
presentation about green legislation had that intent, but used fancy words so 
it sounds cooler. Well, saving nature is at least one of major factors, other’s 
being someone profiting from it, other political implications etc...

I might be completely wrong here, some simple and clear emphasis of how they 
are unrelated is welcome.

> On 18 Jul 2023, at 18:11, Dom Grigonis  wrote:
> 
> To me, they are in the inverse relationship.
> 
> Terseness ~ 1 / expressiveness.
> 
> Maybe I am not getting something.
> 
> But surely if list comprehension took 5 lines to write, it wouldn’t be 
> justifiable? So, even if implicit, brevity and its relation to complexity is 
> always a factor.
> 
>> On 18 Jul 2023, at 17:57, Chris Angelico  wrote:
>> 
>> On Wed, 19 Jul 2023 at 00:55, Dom Grigonis  wrote:
>>> Here I am a bit confused, how is this the case in the language containing 
>>> list comprehensions?
>>> 
>> 
>> Do you understand the difference between expressiveness and terseness?
>> You still seem to be focused on the completely wrong thing here. List
>> comprehensions are not about saving lines, they are about expressing
>> the concept of "build a list from a list".
>> 
>> ChrisA
>> ___
>> 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/HES5J5CLNNBHXAKIMIQA5WV43GBI6Q4W/
>> 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/2L7DMWBTWD3KO7DLZDKOKLJI3NZILC3Q/
Code of Conduct: http://python.org/psf/codeofconduct/


[Python-ideas] Re: Proposal for get_or function in Python dictionaries

2023-07-18 Thread Dom Grigonis
To me, they are in the inverse relationship.

Terseness ~ 1 / expressiveness.

Maybe I am not getting something.

But surely if list comprehension took 5 lines to write, it wouldn’t be 
justifiable? So, even if implicit, brevity and its relation to complexity is 
always a factor.

> On 18 Jul 2023, at 17:57, Chris Angelico  wrote:
> 
> On Wed, 19 Jul 2023 at 00:55, Dom Grigonis  wrote:
>> Here I am a bit confused, how is this the case in the language containing 
>> list comprehensions?
>> 
> 
> Do you understand the difference between expressiveness and terseness?
> You still seem to be focused on the completely wrong thing here. List
> comprehensions are not about saving lines, they are about expressing
> the concept of "build a list from a list".
> 
> ChrisA
> ___
> 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/HES5J5CLNNBHXAKIMIQA5WV43GBI6Q4W/
> 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/SVT7HQ4BHLUTBC4EMY52OIDL5PXYO7ZH/
Code of Conduct: http://python.org/psf/codeofconduct/


[Python-ideas] Re: Proposal for get_or function in Python dictionaries

2023-07-18 Thread Dom Grigonis
> A plain async function pretty much IS a generator, but without the
> risk of removing the last await point and having the function stop
> being a generator.
I am still lost in async space. From my initial benchmarking it seems that the 
complexity that async is introducing hardly justifies itself in performance. In 
other words, if it is done using `async` it’s performance is very similar to 
`gevent`, meaning, that all that hassle doesn’t justify itself in performance 
space, which is one of the major selling points.

If async is done with `yield`, then it could potentially be justified in 
performance-critical applications.

I am not 100% certain about this as I haven't compared everything thoroughly, 
but these were the findings from my initial fairly crude testing.

Am I missing something here?

> But async generators are also a thing, and there's
> no easy way to make a generator-generator with two different types of
> yield in it.
I’d rather not have 2nd yield and have things a bit simpler in that space...

> On 18 Jul 2023, at 17:06, Chris Angelico  wrote:
> 
> On Tue, 18 Jul 2023 at 23:41, Stephen J. Turnbull
>  wrote:
>> 2.  Comparing floats, even against zero, is a bad idea.  So I would
>>wrap them in math.isclose:
>> 
>>val = a ? (not isclose(c, 0) ? c : d) : (not isclose(d, 0) ? d : c)
> 
> That's overly simplistic; there are a lot of times when it's
> absolutely fine to compare floats for equality, particularly with
> zero, where the idea of "close" can be ill-defined. But this is the
> difficulty with toy examples - we have no idea how realistic this
> actually is. For now, though, I'd be inclined to keep the semantics
> unchanged and just look at the syntax.
> 
>>In general you will have function calls
>>adding parentheses -- and thus confusion.  Perhaps there will be
>>lists or tuples involved.  You can precompute them and assign
>>them to short name variables, but then you lose the one-liner-ness.
> 
> This is true, almost trivially so; one-liners aren't all that common
> because real-world use-cases are often complicated. However, they DO
> exist. It'd be nice to have really good examples but we may well not
> have that luxury.
> 
>> 3.  OK, how about ints then?  Yes, that would work, but how frequently
>>are you going to be comparing against 0?  Here's a more realistic
>>case, with readable short argument names:
>> 
>>def clamp_int(n: int, lo: int, hi: int):
>># I wouldn't elide this test because if lo > hi you get a
>># plausible but necessarily erroneous value
>>if lo > hi:
>>raise ValueError(f'lo = {lo} > {hi} = hi')
>>val = n < lo ? lo : (n > hi ? hi : n)
>>return val
>> 
>>Agreed, the expression using Python's syntax would be worse, but I
>>think this is much more readable:
>> 
>>def clamp_int(n: int, lo: int, hi: int):
>>if lo > hi:
>>raise ValueError(f'lo = {lo} > {hi} = hi')
>>if n < lo:
>>val = lo
>>elif n > hi:
>>val = hi
>>else:
>>val = n
>>return val
>> 
>>and it would be more readable yet if you got rid of the
>>assignments and just returned the value as soon as you see it:
>> 
>>def clamp_int(n: int, lo: int, hi: int):
>>if lo > hi:
>>raise ValueError(f'lo = {lo} > {hi} = hi')
>># Hi, David!  Default first!!
>>if lo <= n <= hi:# Yes, Virginia, valid Python!
>>return n
>>elif n > hi:
>>return hi
>>else:
>>return lo
>> 
>>(Yes, I know that some folks argue that suites should have one
>>entry point and one exit point, but I don't think it's a problem
>>here because of the extreme symmetry and simplicity of the
>>conditional.  IMHO YMMV of course)
> 
> def clamp_int(n: int, lo: int, hi: int):
>if lo > hi:
>raise ValueError(f'{lo = } > {hi = }')
>return max(lo, min(n, hi))
> 
> Nobody said we weren't allowed to use builtins, right? :)
> 
>> Now, you can add a new one that does the same thing, and that's been
>> done.  IIRC it took a while to get +=
> 
> Note that augmented operators are not simply shorthands for the
> expanded version. There are a few differences between:
> 
> a.b.c.d.e += value
> 
> and
> 
> a.b.c.d.e = a.b.c.d.e + value
> 
> including that the basis object (a.b.c.d) would only be evaluated
> once, and especially, the addition is done in-place if supported (eg
> with lists).
> 
>> and C-like ++/-- increment
>> operators have been requested over and over again.  AFAIK the async
>> syntaxes do nothing that can't be done with generators, but they make
>> it a lot easier to do it right in the most common cases.
> 
> A plain async function pretty much IS a generator, but without the
> risk of removing the last await point and having the function stop
> being a generator. But async generators are also a thing, and there's
> no easy way to 

[Python-ideas] Re: Proposal for get_or function in Python dictionaries

2023-07-18 Thread Dom Grigonis
Thanks for reply,

I can see most of what you have written.

> But "encourages one-liners" is generally considered an anti-pattern in
> Python.  Let's see why,
Here I am a bit confused, how is this the case in the language containing list 
comprehensions?

I would understand if it was swapped with “bad quality & unreadable 1-liners”.

Also, I would rephrase “encourage 1-liners” to “promote readable and expressive 
structures that are balanced in their brevity versus complexity”.

I am not encouraging 1-liners, I am more arguing that certain things in 
relation to average complexity should take no more than 1-line. I am always 
very happy to write multiple lines.

E.g. I often use loops instead of list comprehensions:
l = list()
for i in range(10):
l.append(func(i))
These 3 lines justify themselves. A reasonable amount of logic and complexity 
is contained in them. While I could not say the same about:
if a < 1:
c = a
else:
c = default
For what it does, it feels it should’t take more than half the space that the 
“for” loop above is taking.

Btw, here I would probably prefer:
def clamp_int(n: int, lo: int, hi: int):
if lo > hi:
raise ValueError(f'{lo=} > {hi=}')
return lo <= n <= hi ? n : (n > hi ? hi : lo)
I emphasize readability more in high-level code, APIs, non-numeric routines and 
similar.

E.g. In numpy code I sacrifice a lot of that “english” readability for 
aesthetics and brevity, as it is closer to scientific space, where everything 
is pretty much named with 1-letter + glossary.

I think the place I am coming from is more about balance than brevity. In other 
words, outliers in multi-dimensional spacecan  feel awkward to me. Obviously, 
my dimensions might not be the same as someone else's.

> On 18 Jul 2023, at 16:38, Stephen J. Turnbull 
>  wrote:
> 
> Dom Grigonis writes:
> 
>> I came to this, because people seem to want one-liners for certain
>> things and what I came up with is that maybe more concise if-else
>> expression could help.
> 
> But "encourages one-liners" is generally considered an anti-pattern in
> Python.  Let's see why,
> 
>> # Fairly reasonable case.
> 
>> def foo(a: bool, c: float, d: float)
>>val = a ? (c ? c : d) : (d ? d : c)
>>return val
> 
> What's not so great here?
> 
> 1.  The argument names are not going to be single characters, unless
>you intentionally name that way for the sake of one-line-ism.
>That severely detracts from your claim of readability.  The
>one-liner is arguably[1] more readable than the Python version,
>but you've definitely made the whole function less readable.
> 
> 2.  Comparing floats, even against zero, is a bad idea.  So I would
>wrap them in math.isclose:
> 
>val = a ? (not isclose(c, 0) ? c : d) : (not isclose(d, 0) ? d : c)
> 
>Pretty long, not that easy to read.  Of course if you had
>intelligible variable names it would be worse.
> 
>The point is *not* to give you a hard time about comparing floats
>for equality, we've all done that.  It's that in even in this
>example, done safely you have more complex expressions than just
>variable references.  In general you will have function calls
>adding parentheses -- and thus confusion.  Perhaps there will be
>lists or tuples involved.  You can precompute them and assign
>them to short name variables, but then you lose the one-liner-ness.
> 
> 3.  OK, how about ints then?  Yes, that would work, but how frequently
>are you going to be comparing against 0?  Here's a more realistic
>case, with readable short argument names:
> 
>def clamp_int(n: int, lo: int, hi: int):
># I wouldn't elide this test because if lo > hi you get a
># plausible but necessarily erroneous value
>if lo > hi:
>raise ValueError(f'lo = {lo} > {hi} = hi')
>val = n < lo ? lo : (n > hi ? hi : n)
>return val
> 
>Agreed, the expression using Python's syntax would be worse, but I
>think this is much more readable:
> 
>def clamp_int(n: int, lo: int, hi: int):
>if lo > hi:
>raise ValueError(f'lo = {lo} > {hi} = hi')
>if n < lo:
>val = lo
>elif n > hi:
>val = hi
>else:
>val = n
>return val
> 
>and it would be more readable yet if you got rid of the
>assignments and just returned the value as soon as you see it:
> 
>def clamp_int(n: int, lo: int, hi: int):
>if lo > hi:
>raise ValueError(f'lo = {lo} > {hi} = hi')
># Hi, David!  Default first!!
>if lo <= n <= hi:# Yes, Virginia, valid Python!
&g

[Python-ideas] Re: Conditional 1-line expression in python (Dom Grigonis)

2023-07-18 Thread Dom Grigonis
Thank you.

I meant “superset of 671, not 505”…

One question:
def bar(a => None);
return foo(a)

def foo(a => object()):
return a
How would I force foo’s default from bar’s call?

Would something like this work?
def foo(a => object() if a is None else a):
return a


> On 18 Jul 2023, at 09:45, Chris Angelico  wrote:
> 
> On Tue, 18 Jul 2023 at 16:25, Dom Grigonis  wrote:
>> 
>> Yes, thank you, this would definitely be nice to have.
>> 
>> Although, "A generic system for deferred evaluation has been proposed at 
>> times“ sound better if it was a superset of PEP505. Could you refer me to 
>> any resources about such considered system?
>> 
> 
> Hrm, you'd probably have to scour the archives. It's one of those
> things that comes up periodically and spawns a discussion thread, but
> never really gets to a concrete proposal. The best I can find is this,
> which never even got submitted to the official PEP repository, but
> it's someone's attempt to make something that could potentially become
> one, so it's a start.
> 
> https://github.com/DavidMertz/peps/blob/master/pep-.rst
> 
> The trouble is, it's really REALLY hard to pin down useful semantics
> for deferred evaluation. We already have lambda functions, which cover
> a lot of situations, leaving a lot of uncertainty as to what's being
> handled by this new proposal - and since no proposal ever truly comes
> from a single person, that results in a certain amount of chaos.
> 
> ChrisA

___
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/XCX54U7H7QWTGHEHUTHCPERW6LVAOUJT/
Code of Conduct: http://python.org/psf/codeofconduct/


[Python-ideas] Re: Conditional 1-line expression in python

2023-07-18 Thread Dom Grigonis
Maybe could be a part of https://peps.python.org/pep-0463/ 


Maybe if it was more expressive, e.g. covering the case such as you suggesting, 
it would go through?

Also, I still don't see why changing analogous statement order when making 
1-line expressions is a good idea.

E.g. there was a statement:
# Statement
try:
expression1
except Exception:
expression2
except Exception:
expression1
el
finally:
expression6
It’s analogous expression then could be:

val = try expr1() except Exception ? expr2() el finally expr5()

Simple if-else statement would be everything in between <> in both statement 
and expression.

Functional, consistent, expressive, in line with what is already there. Both 
“continue” and “break" would also be used in expressions same place as the 
statement. Maybe something else instead of “?”, but it doesn’t matter much to 
me, “?” would be just fine.

This would also partly cover my “rant” about C’s conditional expression. I.e. 
The order. Which probably has more weight in my aversion than it’s verbosity.

* Now argument that expressions read more naturally in this order raises a 
question "Why then isn’t it the same in statements?”.
* And argument that it’s easier for someone to learn without programming 
background also fails as even they would probably prefer “consistency" as 
opposed to "inconsistency, but 1 part reads like english."

I personally find it easier to learn when I understand and I understand when 
things make sense and follow patterns. Can it be that too much of this is being 
sacrificed for the sake of factors which are not as important?

> On 18 Jul 2023, at 09:08, Stephen J. Turnbull 
>  wrote:
> 
> David Mertz, Ph.D. writes:
> 
>> I think the Python version does the right thing by emphasizing the
>> DEFAULT by putting it first, and leaving the predicate and fallback
>> until later in the expression (right for Pythonic code, not right
>> for other languages necessarily).
> 
> Aside: I think that's true for Pythonic scripting, but in general I
> think you're just as likely to find that it's a genuine choice, and
> that the condition is as interesting as either choice.
> 
> Variation on the theme of conditional expression: I'd often like to
> write
> 
>var = computed() if cond() else break
> 
> or
> 
>var = computed() if cond() else continue
> 
> I wonder if that syntax has legs, or if it's too cute to stand.
> 

___
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/3GBJSOMBDFRQSP7IRK3CHAVF57E57O5Q/
Code of Conduct: http://python.org/psf/codeofconduct/


[Python-ideas] Re: Conditional 1-line expression in python (Dom Grigonis)

2023-07-18 Thread Dom Grigonis
Yes, thank you, this would definitely be nice to have.

Although, "A generic system for deferred evaluation has been proposed at times“ 
sound better if it was a superset of PEP505. Could you refer me to any 
resources about such considered system?

> On 18 Jul 2023, at 08:33, Chris Angelico  wrote:
> 
> On Tue, 18 Jul 2023 at 14:07, Dom Grigonis  wrote:
>> PEP505 would solve this nicely, but it only applies to None and would not 
>> apply to say user-defined sentinels and many other cases where permutations 
>> of different conditionals arise.
>> 
> 
> PEP 671 would solve this nicely too.
> 
> ChrisA
> ___
> 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/R4HVE2MYZT7GJAB6SNKHW6UVC2G4OYYO/
> 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/OUYIXJ5ZYQUXJBXR5U554YMKLVU6AAKB/
Code of Conduct: http://python.org/psf/codeofconduct/


[Python-ideas] Re: Conditional 1-line expression in python (Dom Grigonis)

2023-07-17 Thread Dom Grigonis
Ok, thanks. I think what I am aiming at is that there is a pool of suggestions 
and PEPs that are pointing towards very similar direction and I find myself 
often wandering in the same space, just trying to figure out what it exactly is.

It sometimes feels more verbose than it could be for what it is in the context 
of how simple python is to use in general.

I am fully well aware that current if-else expression is not going anywhere. 
Chances that another expression is introduced, which does exactly the same 
thing are close to none.

So I am just gauging if it is a matter of conciseness of existing expressions 
or absence of something that could be there. Conditional if-else is just a 
place where I got to naturally. 

Got some useful references to PEPs, python history and opinions. Maybe it will 
become more clear in the future or maybe something new is already being worked 
that is going to fill the gap which I am not aware of.

I haven’t even started any proposal myself, I was just following e-mail 
requests and rejected PEPs that were mentioned here. Combined it with my own 
experience and this is where I got to.

Currently seems like it’s a dead end. Decision’s have been made, opinions taken 
into account, but I still have to write either:

a) awkward 1-liner
self.value = value if value is not None else DefaultClass()
b) 3 nicely readable lines with 1 unnecessary assignment.
self.value = value
if value is None:
self.value = DefaultClass()
c) 4 lines, no unnecessary assignments with excellent readability.
if value is None:
self.value = DefaultClass()
else:
self.value = value

The issue with b) and c) is that if I use those ones, my constructors become 
unbearably long and finally lead to the point where development becomes 
awkward. I would think that for what it does, it shouldn’t be more than 1 line. 
Max - 2. But a) is somewhat awkward. All (well not all, just several things) 
taken into account I ended up at inconvenience of `ifelse` expression, which 
would make a) my natural choice in this case. I am not even suggesting to 
introduce analogous `ifelse` with different syntax, just trying to get some 
ideas, references, opinions or alternatives that I don’t know about.

Maybe I need to spend some time on it and some solution will come out using 
existing python’s functionality or an idea which actually has a chance of being 
considered.

How would you write this? Doesn’t the below feel more verbose than it could be? 
Add 10 more constructor argument and there are 50 lines of code that do pretty 
much nothing. Not very pythonic…? One-line conditionals aren’t very readable 
(to me! I am aware that some might not feel this way) and for longer variable 
names sometimes don’t even fit into 80 characters.
def __init__(self,
 arg1=None,
 argument2=None,
 arg3foo=None,
 ...)
if arg1 is None:
self.arg1 = DefaultClass()
else:
self.arg1 = arg1
if argument2 is None:
self.argument2 = DefaultClass()
else:
self.argument2 = argument2
if arg3foo is None:
self.arg3foo = DefaultClass()
else:
self.arg3foo = arg3foo
...

PEP505 would solve this nicely, but it only applies to None and would not apply 
to say user-defined sentinels and many other cases where permutations of 
different conditionals arise.

Just want to stress out, that I know that this is something very primitive and 
might seem insubstantial to consider, but to me personally, solution to this 
would make a very big difference. I have been stuck on many such decisions of 
best practice and I have found satisfactory solutions to seemingly much more 
complex `problems` and am fairly happy having found optimal ways to do many 
different things in python - makes life easy. But this one is of very few that 
still bother me to this day. And it does seem related to certain queries that 
arise here.

So just trying to see what others think, etc, etc

Ok, I have been repeating myself for a bit, but from certain responses it felt 
like I have failed to convey where I am coming from. Or maybe no-one else has 
issue here, so if I am actually alone that is so bothered about this, it as 
also good information.

> On 18 Jul 2023, at 04:40, Greg Ewing  wrote:
> 
> On 18/07/23 10:30 am, Dom Grigonis wrote:
>> Although, the argument that python is meant to be read as english is very 
>> much valid, but I do not see why it has to be an overarching one if the 
>> opportunity cost of it is too great in other dimensions.
> 
> It's not overarching. Many things in Python don't read like English,
> and nobody is suggesting changing them to be more English-like.
> 
> I think you've got it backwards here. The fact that it reads like
> English is just a possible explanation of why many people find it more
> readable. The fact that people (well, just Guido at that time) find it
> readable is the reason it was ch

[Python-ideas] Re: Conditional 1-line expression in python (Dom Grigonis)

2023-07-17 Thread Dom Grigonis
Much of what you respond to me indicates that you did not properly read what I 
have written and did not really understand where I am coming from.

> On 18 Jul 2023, at 04:04, Chris Angelico  wrote:
> 
> On Tue, 18 Jul 2023 at 10:37, Dom Grigonis  wrote:
>> As opposed to
>> 
>> if a == 0:
>>   foo, bar = var1, variable2
>> else:
>>   foo, bar = default, default2
>> 
>> 
>> Again, one is `a == 0`, another is `b == 0`. I didn’t do a good job 
>> conveying this did I… Will try to be more precise and leave less room for 
>> misinterpretation.
> 
> Would you really go through and change all your variable names if it
> turns out that what you actually need is "a == 0" and "b == 15"? This
> sort of alignment is so fragile and unnecessary. Yes, it's nice when
> it works out, but it should never be a high priority.
> 
>> foo = foo3 if foo2 == 0 else default
>> bar = barbarbar if bar2 == 0 else default2
>> 
>> # As opposed to
>> 
>> foo = foo2 == 0 ? foo3 : default
>> bar = bar2 == 0 ? barbarbar : default2
> 
> Extremely artificial. You've shown that, if the conditions are the
> same lengths but the "if-true" expressions aren't, you can align them
> using ?: and can't align them using if-else. It's just as valid to
> show:
> 
> foo = "yes" if foo2 else "no"
> bar = "yes" if barbarbar else "no"
> 
> Like I said, extremely fragile.
> 
>> I don’t think it is that easy to draw the line here.
>> Everything in both of those PEPs can be expressed using current constructs. 
>> So maybe they are about more compact expressions?
> 
> "Can be expressed"? Well, yes. Python is Turing-complete. So is
> Brainf*. Doesn't mean we want to use it though.
> 
> Expressiveness is a spectrum or a scale. You can improve on it without
> the older version being impossible to write. In fact, Python really
> doesn't NEED all the syntax it has. Have a read of this series of blog
> posts:
> 
> https://snarky.ca/tag/syntactic-sugar/
> 
> (Brett Cannon also did a talk on this at PyCon US 2023; not sure if
> that's been made public yet.) There are only a handful of pieces of
> syntax that you really can't do without. But you CAN skip having an
> "if" statement. No kidding - you can eliminate the if statement by
> smart use of the while statement.
> https://snarky.ca/unravelling-if-statements/
> 
> Improvements to expressiveness allow us to write better code, to make
> it clearer what the *programmer's intent* is. Sometimes that aligns
> with compactness; sometimes it doesn't.
> 
>> Was python made for conciseness or expressiveness? Everything it does can 
>> already be done in C isn’t it? So I would argue any abstraction is really 
>> more about conciseness. Expressiveness is more about incorporation of what 
>> is already there, but not in the abstraction, i.e. extension. But python 
>> being interpreted language written in another language, I really FAIL to see 
>> how is all of this NOT about conciseness and modularity?
>> 
> 
> Expressiveness. It's about how well the source code represents the
> programmer's intent. You could write all of your code as a massive
> matrix of logic gates, but that wouldn't improve readability. And
> since you can implement logic gates with water - see
> https://www.youtube.com/watch?v=IxXaizglscw for proof - your program
> source code could be an acrylic sheet with a bunch of buckets glued
> onto it.
> 
> But none of us want to write code like that, and definitely none of us
> want to read code like that.
> 
> ChrisA
> ___
> 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/B5YRPPGSGQTAMM6WOKGULK2SKVR4H7KT/
> 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/HUTXYJC66CYJ7QCLZHEQNMYVUZHLVCQV/
Code of Conduct: http://python.org/psf/codeofconduct/


[Python-ideas] Re: Conditional 1-line expression in python (Dom Grigonis)

2023-07-17 Thread Dom Grigonis

>> # Code becomes easily read when there is a nice alignment in horizontal 
>> space. e.g.:
>> 
>> variable = None
>> length_1 = None
>> somethin = None
>> 
> 
> variable = length_1 = somethin = None

Obviously they would not all be None, just chosen None as `any dummy value`, 
mistake on my part - None is not suitable for that.

>> foo = var1 if a == 0 else default
>> bar = variable2 if a == 0 else default2
>> 
>> # As opposed to
>> 
>> foo = a == 0 ? var1 : default
>> bar = a == 0 ? variable2 : default2
> 
> As opposed to
> 
> if a == 0:
>foo, bar = var1, variable2
> else:
>foo, bar = default, default2

Again, one is `a == 0`, another is `b == 0`. I didn’t do a good job conveying 
this did I… Will try to be more precise and leave less room for 
misinterpretation.
foo = foo3 if foo2 == 0 else default
bar = barbarbar if bar2 == 0 else default2

# As opposed to

foo = foo2 == 0 ? foo3 : default
bar = bar2 == 0 ? barbarbar : default2

>> From what I have gathered, these:
>> https://peps.python.org/pep-0505/
>> https://peps.python.org/pep-0463/
>> , and certain number of proposals in this group at their root are pointing 
>> approximately to the same direction. I.e. some things are too verbose (and 
>> too many lines of code) given the simplicity of what is needed to be done.
> 
> Both of those are about *expressiveness*. This is not the same thing
> as compactness. The two do sometimes align but the purpose is
> different.

I don’t think it is that easy to draw the line here.
Everything in both of those PEPs can be expressed using current constructs. So 
maybe they are about more compact expressions?

Same as proposal regarding more expressive dict.get from which my train of 
thought has started.
Is it a request for:
a) more expressive dict.get?
b) more concise way do what can be done in a several lines of code anyways?

I just can’t see any substance that you are coming from with this…

Was python made for conciseness or expressiveness? Everything it does can 
already be done in C isn’t it? So I would argue any abstraction is really more 
about conciseness. Expressiveness is more about incorporation of what is 
already there, but not in the abstraction, i.e. extension. But python being 
interpreted language written in another language, I really FAIL to see how is 
all of this NOT about conciseness and modularity?

I agree that there are other dimensions, but I always thought python being 
closer to unix than windows...

> On 18 Jul 2023, at 03:08, Chris Angelico  wrote:
> 
> On Tue, 18 Jul 2023 at 08:34, Dom Grigonis  wrote:
>> 
>> I still feel that compared to list comprehension and other functional and 
>> elegant python constructs, python's if-else expression is lacking. I often 
>> choose to go multi-line much more verbose code as opposed to more brief 
>> constructs just because it becomes unreadable - a more elegant and logically 
>> convenient expression would change the decision ratio significantly, at 
>> least for me.
>> 
> 
> You choose to go multi-line because the one-liner becomes less
> readable? Then that's a win for the current system. This is NOT a
> problem to be solved. Everything is working correctly. You have chosen
> the readable option over the compact one!
> 
>> # Code becomes easily read when there is a nice alignment in horizontal 
>> space. e.g.:
>> 
>> variable = None
>> length_1 = None
>> somethin = None
>> 
> 
> variable = length_1 = somethin = None
> 
>> # I often take this into account on variable name selection. Now:
> 
> Poor choice IMO. You could have had more consistent variable names by
> taking advantage of chained assignment.
> 
>> foo = var1 if a == 0 else default
>> bar = variable2 if a == 0 else default2
>> 
>> # As opposed to
>> 
>> foo = a == 0 ? var1 : default
>> bar = a == 0 ? variable2 : default2
> 
> As opposed to
> 
> if a == 0:
>foo, bar = var1, variable2
> else:
>foo, bar = default, default2
> 
>> From what I have gathered, these:
>> https://peps.python.org/pep-0505/
>> https://peps.python.org/pep-0463/
>> , and certain number of proposals in this group at their root are pointing 
>> approximately to the same direction. I.e. some things are too verbose (and 
>> too many lines of code) given the simplicity of what is needed to be done.
> 
> Both of those are about *expressiveness*. This is not the same thing
> as compactness. The two do sometimes align but the purpose is
> different.
> 
>> https://peps.python.org/pep-0308/#detailed-results-of-voting
>> It seems that C’s expression was ranked 2nd most favourable… The 

[Python-ideas] Re: Proposal for get_or function in Python dictionaries

2023-07-17 Thread Dom Grigonis
What I meant is that it is not affected by prejudices to such a degree that a 
'challenger' wanted to make it look.

“I find it more readable” is a fair statement. The recognition of subjectivity 
is very transparent in it. In other words, such statement is not trying to be 
bigger than it actually is.

I realise that. I actually sometimes do use conditional `ifelse` and well aware 
of it’s existence. I am just trying to connect dots here.

Some proposals here are answered very clearly and in line with:
"There should be one-- and preferably only one --obvious way to do it.”

And some fall into category “there are workarounds, just deal with it". As I 
said, it seems that (at least to me) there is a big part of them that are 
pointing towards this direction - those that are confused about the elegant and 
simple way of doing certain simple things.

Maybe this 20-year late discussion will have some impact on future python 
expressions. E.g. some new expression will be a superset of `ifelse` and this 
will be taken into account. Maybe not, but hopefully it had at least a bit of 
positive value.

> On 18 Jul 2023, at 01:49, Christopher Barker  wrote:
> 
> On Tue, 18 Jul 2023 at 04:37, Dom Grigonis  <mailto:dom.grigo...@gmail.com>> wrote:
> > This is why, I would dare to say that this preference of mine is not 
> > affected by prejudices.
> 
> Of course it's affected by prejudices -- all our preferences are. A sample of 
> one "I find it more readable" is about as useful as any sample of one to 
> represent a population.
> 
> Personally, I find the C syntax completely opaque and the Python syntax 
> totally understandable the first time I saw it -- and it's very much more 
> "Pythonic".
> 
> But that's influenced by my prejudice.
> 
> But anyway, this conversation is 20 (!) years too late[*] -- and it did take 
> place then. It's not going to change now.
> 
> -CHB
> 
> [*] https://peps.python.org/pep-0308/ <https://peps.python.org/pep-0308/>
> 
> 
> -- 
> Christopher Barker, PhD (Chris)
> 
> Python Language Consulting
>   - Teaching
>   - Scientific Software Development
>   - Desktop GUI and Web Development
>   - wxPython, numpy, scipy, Cython
> ___
> 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/YQGA4KWF7G4I32GZNYLWQ2EIZOHMEZJY/
> 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/PXQRW6W5GMGOJSS7QJEYBQGBLAIYK274/
Code of Conduct: http://python.org/psf/codeofconduct/


[Python-ideas] Re: Proposal for get_or function in Python dictionaries

2023-07-17 Thread Dom Grigonis
Just to add, I think your statement actually works in my favour rather than 
against my proposal.

People from this group are potentially biased and lack objectivity against what 
I am proposing because they are familiar with python and more experienced ones 
participated in “carved in stone” decision regarding already existent `ifelse` 
expression. 

So I expected that my proposal might even look humorous to some. E.g. In survey 
I got a comment “to learn python if I want to use it”. I am doing my best, just 
some parts of it are hard to digest in the context of other parts that are so 
easily digestible.

> On 17 Jul 2023, at 21:37, Dom Grigonis  wrote:
> 
> This is NOT a good example, my first language was R, second - python, third 
> matlab, etc.
> 
> I only became familiar with C/C++ after several years of coding experience.
> 
> This is why, I would dare to say that this preference of mine is not affected 
> by prejudices.
> 
>> On 17 Jul 2023, at 20:44, Chris Angelico  wrote:
>> 
>> On Tue, 18 Jul 2023 at 03:13, Dom Grigonis  wrote:
>>> Maybe for someone who majored in languages python’s if-else is more easily 
>>> understood. To me, personally, 2nd one is unbearable, while 1st one is 
>>> fairly pleasant and satisfying.
>>> 
>> 
>> This is a REALLY good example of how hard it is to be objective about
>> syntax. Being familiar with something really truly does make it
>> immensely better - for you. You're comfortable with the C syntax.
>> That's great! So am I. But that isn't a good indication of how it
>> would be accepted by someone who isn't familiar with either syntax.
>> 
>> The ?: syntax has the advantage that the evaluation order is
>> left-to-right, which is the most common (though far from universal)
>> evaluation order. That is a definite advantage, to be sure, but
>> perhaps not as big as you might think. The if/else syntax is more
>> consistent with other Python syntax by using words, though.
>> 
>> Ultimately, *all* syntax has to be learned.
>> 
>> ChrisA
>> ___
>> 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/NGJ5GH6JXOZZLSTJT323F4TUEH5YXN3V/
>> 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/5IQM3DSGOF25Y4STSTAPHV2H2LBL4GC2/
Code of Conduct: http://python.org/psf/codeofconduct/


[Python-ideas] Re: Proposal for get_or function in Python dictionaries

2023-07-17 Thread Dom Grigonis
> Was that really the intention? Because I was there when PEP 572 was
> written, and I don't recall "beautiful one-liners" as one of the
> justifying reasons. Use around if/while conditions was a strong
> reason, and yes, that can save a line, but "beautiful one-liners"
> hasn't generally been a justifying factor in any Python feature.

Never said about the intention, just stated that I see it as being a part of 
their construction.

However, in the PEP you have referred and also as I remember reading python’s 
“what’s new”, list comprehensions and other 1-liners were close to half of all 
examples.

> On 18 Jul 2023, at 00:04, Chris Angelico  wrote:
> 
> On Tue, 18 Jul 2023 at 06:40, Dom Grigonis  wrote:
>> 
>> We even got a new operator “:=“ to help us with those beautiful one-liners 
>> (or not) to move towards aesthetics and brevity.
>> 
> 
> Was that really the intention? Because I was there when PEP 572 was
> written, and I don't recall "beautiful one-liners" as one of the
> justifying reasons. Use around if/while conditions was a strong
> reason, and yes, that can save a line, but "beautiful one-liners"
> hasn't generally been a justifying factor in any Python feature.
> 
> ChrisA
> ___
> 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/MJI5UNLOCJK4WTFBFNC2YFBE7PXHRAL7/
> 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/EIG4E2OCQONZVDOKJIABAQTPB44BJEIC/
Code of Conduct: http://python.org/psf/codeofconduct/


[Python-ideas] Re: Conditional 1-line expression in python (Dom Grigonis)

2023-07-17 Thread Dom Grigonis
Ah, I can’t do that post-publish. This will have to suffice for now.

If this got to a point where there was a case to revise 2005 decision or 
introduce an alternative (which I very much doubt can happen any time soon), 
much more elaborate research and survey would have to be done and all options 
considered.

I like `IF(cond, true, false)`, even better than `ifelse(cond, true, false)` - 
shorter. But in python this would indicate a function call, meaning all 
arguments would need to be evaluated before the expression logic. If evaluation 
is not costly, one can simply use his own function to do this.

I still feel that compared to list comprehension and other functional and 
elegant python constructs, python's if-else expression is lacking. I often 
choose to go multi-line much more verbose code as opposed to more brief 
constructs just because it becomes unreadable - a more elegant and logically 
convenient expression would change the decision ratio significantly, at least 
for me.

Your examples nicely emphasise it.

Another perspective:
# Code becomes easily read when there is a nice alignment in horizontal space. 
e.g.:

variable = None
length_1 = None
somethin = None

# I often take this into account on variable name selection. Now:

foo = var1 if a == 0 else default
bar = variable2 if a == 0 else default2

# As opposed to

foo = a == 0 ? var1 : default
bar = a == 0 ? variable2 : default2

# Naturally, one can argue: what if condition length differs - same problem.
# But in practice, the number of conditionals is greatly smaller than variables.
# Thus, much more easier to adapt to that.
Although, the argument that python is meant to be read as english is very much 
valid, but I do not see why it has to be an overarching one if the opportunity 
cost of it is too great in other dimensions.

Finally, it is always an option to have 2 conditional expressions. Maybe 
another python expression which is a superset of current `ifelse`. Just not 
sure what it could be and what other gaps or extensions it could fill.

From what I have gathered, these:
https://peps.python.org/pep-0505/ <https://peps.python.org/pep-0505/>
https://peps.python.org/pep-0463/ <https://peps.python.org/pep-0463/>
, and certain number of proposals in this group at their root are pointing 
approximately to the same direction. I.e. some things are too verbose (and too 
many lines of code) given the simplicity of what is needed to be done.


https://peps.python.org/pep-0308/#detailed-results-of-voting 
<https://peps.python.org/pep-0308/#detailed-results-of-voting>
It seems that C’s expression was ranked 2nd most favourable… The decision was 
3rd. This kinda suggests that I am not as delusional as I initially thought I 
might appear to be with this...

The initial proposal wasn’t too bad - I could work with it. Being in line with 
a sequential logic of multiline `if-else` statement is a plus.
(if :  else: )


> On 18 Jul 2023, at 00:36, Laurent Lyaudet  wrote:
> 
> Hello all,
> 
> Please Dom Grigonis add choices :
> - "No preference" choice to first question
> - "I don't know" or "I can't tell" to third question
> And I will answer to your poll and probably other people will feel and
> do the same.
> I agree that question 2 makes me prefer C syntax.
> But C is not the nicest syntax in my point of view.
> In MySQL SQL, there is IF(condition, if_result, else_result)
> which I find nice.
> Moreover, it fits well with black style of formatting:
> foo_var = IF(
>this_is_a very_long_condition_expression_which_may_have_nested_parts,
>this_is_a very_long_if_result_expression_which_may_have_nested_parts,
>this_is_a very_long_else_result_expression_which_may_have_nested_parts,
> )
> to compare with :
> foo_var = (
>this_is_a very_long_condition_expression_which_may_have_nested_parts,
>? this_is_a very_long_if_result_expression_which_may_have_nested_parts,
>: this_is_a very_long_else_result_expression_which_may_have_nested_parts,
> )
> I can enjoy both, but I prefer the SQL apart from the fact that "IF"
> keyword would be ambiguous.
> I also enjoy very much :
> foo_var = CASE
>WHEN condition THEN if_result
>WHEN condition2 THEN elif_result
>ELSE else_result
> END
> from SQL.
> And CASE is not a reserved keyword and WHEN, THEN, ELSE could have
> specific meaning inside of case.
> Truly, I would enjoy the following syntax for Python à la black :
> foo_var = case(
>when condition then if_result
>when condition2 then elif_result
>else else_result
> )
> or even more concise and still readable :
> foo_var = case(
>condition : if_result,
>condition2 : elif_result,
>else_result,
> )
> 
> Best regards,
>Laurent Lyaudet
> 
> Le lun. 17 juil. 2023 à 22:42,  a écrit :
>> 
>&

[Python-ideas] Re: Conditional 1-line expression in python

2023-07-17 Thread Dom Grigonis
A bit disappointing, but very much expected. I just though a bit of effort is 
worth even for 0.1% probability of success. At least from where I stand, such 
change would make a fairly big impact on the things I do, given my expected 
relationship with python.

I haven’t studied much of a history of python and I know how much I do not know.

I always let go when there is a conviction it is a right thing to do. :)

Thank you for your reply. PEPs that get referred to in this group are always 
informative to me.

Maybe I will spend some time going through PEPs to get a bit more familiar.

> On 18 Jul 2023, at 00:23, David Mertz, Ph.D.  wrote:
> 
> This ship has sailed and the ternary operator isn't going to change.  
> Seriously, let it go.
> 
> I forget the PEP, but this was well discussed long ago when the ternary was 
> added.  In general, Python prefers words to punctuation symbols for most of 
> its constructs.  So the decision was consistent with that.  I do believe that 
> such a choice is friendlier for people learning a first programming language, 
> since it resembles English prose.  While I like the C-style operator as well, 
> I think the Python version does the right thing by emphasizing the DEFAULT by 
> putting it first, and leaving the predicate and fallback until later in the 
> expression (right for Pythonic code, not right for other languages 
> necessarily).
> 
> Either way, the question is moot.
> 
> On Mon, Jul 17, 2023 at 4:42 PM Dom Grigonis  <mailto:dom.grigo...@gmail.com>> wrote:
> Hi everyone,
> 
> I am not very keen on long discussions on such matter as I do not think there 
> is much to discuss: there is no technical complexity in it and it doesn’t 
> really change or introduce anything new. It is only a matter of opinion & 
> style/design preferences with respect to logical order and brevity of a 
> statement.
> 
> So I thought, if anyone can be bothered on such question and instead of 
> writing 3-minute e-mail, would take few seconds to answer 3-question poll.
> 
> https://q5yitzu62.supersurvey.com <https://q5yitzu62.supersurvey.com/>
> 
> Would be interesting to see if my preference is an outlier or not really.
> 
> 
> Kind regards,
> D. Grigonis
> 
> 
> ___
> Python-ideas mailing list -- python-ideas@python.org 
> <mailto:python-ideas@python.org>
> To unsubscribe send an email to python-ideas-le...@python.org 
> <mailto:python-ideas-le...@python.org>
> https://mail.python.org/mailman3/lists/python-ideas.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/NZVLR56BFMBJXE6GN2GWRXIG6ZVAAWZZ/
>  
> <https://mail.python.org/archives/list/python-ideas@python.org/message/NZVLR56BFMBJXE6GN2GWRXIG6ZVAAWZZ/>
> Code of Conduct: http://python.org/psf/codeofconduct/ 
> <http://python.org/psf/codeofconduct/>
> 
> 
> -- 
> The dead increasingly dominate and strangle both the living and the 
> not-yet born.  Vampiric capital and undead corporate persons abuse 
> the lives and control the thoughts of homo faber. Ideas, once born, 
> become abortifacients against new conceptions.

___
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/GWR63MIEGSRZTL2BU5MGQQUCTFZZIBG4/
Code of Conduct: http://python.org/psf/codeofconduct/


[Python-ideas] Re: Proposal for get_or function in Python dictionaries

2023-07-17 Thread Dom Grigonis
> Never said C was your first language, only that you're familiar with
> it.

But that is more like an obvious fact about everything rather than a 
counter-argument. Your e-mail, at least how I interpreted it, was a fairly 
straight forward accent on my strong bias with a flavour of making it an 
example for everyone to note.

It would supposedly hold as an argument if I was used to C more than python, 
which would indicate my strong bias. While now, I am mostly interested in 
python and it’s long term trajectory, given I suspect I will be using it in 2 
or 3 years time. If I see a pseudocode of a non-existent language and I get an 
idea how to make python nicer, I will use it. But the argument that I am 
familiar with something that others are not is not really a counter-argument 
(to anything).

Except maybe serves to emphasise a general human aversion to change, which is 
naturally less for someone who is a bit familiar. So yes, I am less averse to 
such change because of 2 factors:
1. I am familiar with expression that I am proposing
2. This is my proposal

But neither 1 nor 2 are valid counter-arguments against what I am proposing.

And yes, 

> On 17 Jul 2023, at 23:57, Chris Angelico  wrote:
> 
> On Tue, 18 Jul 2023 at 04:37, Dom Grigonis  wrote:
>> 
>> This is NOT a good example, my first language was R, second - python, third 
>> matlab, etc.
>> 
>> I only became familiar with C/C++ after several years of coding experience.
>> 
>> This is why, I would dare to say that this preference of mine is not 
>> affected by prejudices.
>> 
> 
> Never said C was your first language, only that you're familiar with
> it. And that familiarity inevitably WILL affect your perception, as
> per what I said.
> 
> ChrisA
> ___
> 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/ZC2O5RFH6VC2IVJVV5IFA2YWQAH7XOH5/
> 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/XMZ3TUJKSKGIZKIGNDLKUD3JAYR4HUGL/
Code of Conduct: http://python.org/psf/codeofconduct/


[Python-ideas] Conditional 1-line expression in python

2023-07-17 Thread Dom Grigonis
Hi everyone,

I am not very keen on long discussions on such matter as I do not think there 
is much to discuss: there is no technical complexity in it and it doesn’t 
really change or introduce anything new. It is only a matter of opinion & 
style/design preferences with respect to logical order and brevity of a 
statement.

So I thought, if anyone can be bothered on such question and instead of writing 
3-minute e-mail, would take few seconds to answer 3-question poll.

https://q5yitzu62.supersurvey.com 

Would be interesting to see if my preference is an outlier or not really.


Kind regards,
D. Grigonis


___
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/NZVLR56BFMBJXE6GN2GWRXIG6ZVAAWZZ/
Code of Conduct: http://python.org/psf/codeofconduct/


[Python-ideas] Re: Proposal for get_or function in Python dictionaries

2023-07-17 Thread Dom Grigonis
> 
> Why are we trying to write one-liners in the first place?  Conditional 
> expressions are a rare spice that should be used sparingly. No matter the 
> syntax, three of them nested together isn't readable code, it's a puzzle.
> 
Why are they a rare spice that should be used sparingly? Is it in line with 
python best practices? Anything to support this?

I think python list comprehensions is a direct antithesis to what you are 
saying. I thought they are considered to be a good and preferable practice, 
even nested cases.

We even got a new operator “:=“ to help us with those beautiful one-liners (or 
not) to move towards aesthetics and brevity.

Also, I disagree that the referred code isn’t readable. My point is exactly 
that such code is not readable and is a puzzle if current conditional 
expression is used. While having a more elegant if-else expression, this would 
not be a case.

Combination of list comprehensions, “:=“ operator and good conditional 1-liners 
could be an excellent toolkit to do complex things in simple, readable and 
brief manner. Now I think all is there, except if-else expression does not 
satisfy in either of those dimensions, namely brevity & readability (maybe it 
is better readable than C's for someone with major in languages…?).

So I am just trying to gauge if anyone else feels this way. 

As I already said, my code would look fairly differently if anything similar to 
what I am proposing existed.

And I do not have a bias towards C or C++, 99% of what I do is python so if 
anything I am biased towards how python does things, not the other way round.

Is there any place 


> On 17 Jul 2023, at 23:09, Ned Batchelder  wrote:
> 
> On 7/17/23 1:10 PM, Dom Grigonis wrote:
>> This whole thing started from dict’s `get` extension:
>> def get_substitute(self, key, default=None, subs=()):
>> return key in self ? (self[key] := val in subs ? subs[val] : val) : 
>> default
>> I dare you to do a 1-liner with current if-else.
>> 
> Why are we trying to write one-liners in the first place?  Conditional 
> expressions are a rare spice that should be used sparingly. No matter the 
> syntax, three of them nested together isn't readable code, it's a puzzle.
> 
> --Ned.
> 
> 
> 
>> 
>> 
>> 
>> 
>>> On 17 Jul 2023, at 18:09, Rob Cliffe >> <mailto:rob.cli...@btinternet.com>> wrote:
>>> 
>>> 
>>> 
>>> On 15/07/2023 21:08, Dom Grigonis wrote:
>>>> Just to add. I haven’t thought about evaluation. Thus, to prevent 
>>>> evaluation of unnecessary code, introduction of C-style expression is 
>>>> needed anyways:
>>>>> 1. result = bar is None ? default : bar
>>>> 
>>>> The below would have to evaluate all arguments, thus not achieving 
>>>> benefits of PEP505.
>>>>> 2. result = ifelse(bar is None, default, bar)
>>>> 
>>>> 
>>>> So I would vote for something similar to:
>>>>> result = bar is None ? default : bar
>>>> 
>>>> 
>>>> Where default and bar is only evaluated if needed. Although not to the 
>>>> extent as initially intended, it would offer satisfiable solutions to 
>>>> several proposals.
>>>> 
>>> Well, default is only evaluated if needed; bar is always evaluated.
>>> What is wrong with the Python equivalent
>>> 
>>> result = default if bar is None else bar
>>> or if you prefer
>>> result = bar if bar is not None else default
>>> 
>>> Perhaps you didn't know about this construction?
>> 
>> 
>>> Best wishes
>>> Rob Cliffe
>> 
>> 
>> 
>> ___
>> Python-ideas mailing list -- python-ideas@python.org 
>> <mailto:python-ideas@python.org>
>> To unsubscribe send an email to python-ideas-le...@python.org 
>> <mailto:python-ideas-le...@python.org>
>> https://mail.python.org/mailman3/lists/python-ideas.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/Q4HZ5ME6V473L25AV33BA6C7JMXTI2PJ/
>>  
>> <https://mail.python.org/archives/list/python-ideas@python.org/message/Q4HZ5ME6V473L25AV33BA6C7JMXTI2PJ/>
>> Code of Conduct: http://python.org/psf/codeofconduct/ 
>> <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/IBDNP5LCVXRO5FXMCGD75J5OVO7BCGQW/
> 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/DD3RDWQVU7C6RQLKWJ6GNLHBYTFMYKJR/
Code of Conduct: http://python.org/psf/codeofconduct/


[Python-ideas] Re: Proposal for get_or function in Python dictionaries

2023-07-17 Thread Dom Grigonis
This is NOT a good example, my first language was R, second - python, third 
matlab, etc.

I only became familiar with C/C++ after several years of coding experience.

This is why, I would dare to say that this preference of mine is not affected 
by prejudices.

> On 17 Jul 2023, at 20:44, Chris Angelico  wrote:
> 
> On Tue, 18 Jul 2023 at 03:13, Dom Grigonis  wrote:
>> Maybe for someone who majored in languages python’s if-else is more easily 
>> understood. To me, personally, 2nd one is unbearable, while 1st one is 
>> fairly pleasant and satisfying.
>> 
> 
> This is a REALLY good example of how hard it is to be objective about
> syntax. Being familiar with something really truly does make it
> immensely better - for you. You're comfortable with the C syntax.
> That's great! So am I. But that isn't a good indication of how it
> would be accepted by someone who isn't familiar with either syntax.
> 
> The ?: syntax has the advantage that the evaluation order is
> left-to-right, which is the most common (though far from universal)
> evaluation order. That is a definite advantage, to be sure, but
> perhaps not as big as you might think. The if/else syntax is more
> consistent with other Python syntax by using words, though.
> 
> Ultimately, *all* syntax has to be learned.
> 
> ChrisA
> ___
> 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/NGJ5GH6JXOZZLSTJT323F4TUEH5YXN3V/
> 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/FEQF6QW4RPGTWUZWVHKE34ANJX5HOO73/
Code of Conduct: http://python.org/psf/codeofconduct/


[Python-ideas] Re: Proposal for get_or function in Python dictionaries

2023-07-17 Thread Dom Grigonis

> It does exactly the same as the C version and is more readable.  Or am I 
> missing something?

My point is exactly that it is not easily readable compared to C version. Also, 
unnecessarily verbose. The order of components is rather awkward.

I came to this, because people seem to want one-liners for certain things and 
what I came up with is that maybe more concise if-else expression could help.

# Fairly reasonable case.

def foo(a: bool, c: float, d: float)
val = a ? (c ? c : d) : (d ? d : c)
return val

# Comapred to
def bar(a: bool, c: float, d: float)
val = (c if c else d) if a else (d if d else c)
return val

Maybe for someone who majored in languages python’s if-else is more easily 
understood. To me, personally, 2nd one is unbearable, while 1st one is fairly 
pleasant and satisfying.

This whole thing started from dict’s `get` extension:
def get_substitute(self, key, default=None, subs=()):
return key in self ? (self[key] := val in subs ? subs[val] : val) : default
I dare you to do a 1-liner with current if-else.

Also, https://peps.python.org/pep-0505/ <https://peps.python.org/pep-0505/>
Why was it even considered if it doesn’t introduce any new functionality? I 
also dare you go through that PEP’s examples and re-write them with current 
if-else expression.


So maybe, just maybe, making already existing expression more readable can also 
be a valid suggestion?

As I said, in my opinion it would solve many existing queries and requests, 
just because certain things would become very pleasant and obvious how to do in 
simple one-liners.

Simpler and more logically convenient if-else combined with other elegant 
python expressions would potentially fill that gap.

From where I currently stand it just seems fairly happy middle solution 
between: very concise narrow functionality requests and very verbose ways of 
how they need to be done at the moment.

I fully appreciate how likely what I am proposing is going to be even 
considered. But I really think it should be.




> On 17 Jul 2023, at 18:09, Rob Cliffe  wrote:
> 
> 
> 
> On 15/07/2023 21:08, Dom Grigonis wrote:
>> Just to add. I haven’t thought about evaluation. Thus, to prevent evaluation 
>> of unnecessary code, introduction of C-style expression is needed anyways:
>>> 1. result = bar is None ? default : bar
>> 
>> The below would have to evaluate all arguments, thus not achieving benefits 
>> of PEP505.
>>> 2. result = ifelse(bar is None, default, bar)
>> 
>> 
>> So I would vote for something similar to:
>>> result = bar is None ? default : bar
>> 
>> 
>> Where default and bar is only evaluated if needed. Although not to the 
>> extent as initially intended, it would offer satisfiable solutions to 
>> several proposals.
>> 
> Well, default is only evaluated if needed; bar is always evaluated.
> What is wrong with the Python equivalent
> 
> result = default if bar is None else bar
> or if you prefer
> result = bar if bar is not None else default
> 
> Perhaps you didn't know about this construction?


> Best wishes
> Rob Cliffe

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


[Python-ideas] Re: Proposal for get_or function in Python dictionaries

2023-07-15 Thread Dom Grigonis
I am well aware of that.

I just argue that it is not very pleasant to read.

Personally, I am not a big user of it.

C’s although maybe doesn’t have words to read, but is much more pleasant in 
both conciseness and logical sequence.

Maybe it is not a big issue for others, but if C’s style conditional expression 
existed, it would significantly change the way I write things.

So just checking. :)

> On 16 Jul 2023, at 00:06, Paul Moore  wrote:
> 
> On Sat, 15 Jul 2023 at 21:09, Dom Grigonis  <mailto:dom.grigo...@gmail.com>> wrote:
> So I would vote for something similar to:
>> result = bar is None ? default : bar
> 
> 
> result = default if bar is None else bar
> 
> Python has a conditional expression already.
> Paul 

___
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/QARSVXWITOLFAXZZJLIEBSPFO35PRDDS/
Code of Conduct: http://python.org/psf/codeofconduct/


[Python-ideas] Re: Proposal for get_or function in Python dictionaries

2023-07-15 Thread Dom Grigonis
Just to add. I haven’t thought about evaluation. Thus, to prevent evaluation of 
unnecessary code, introduction of C-style expression is needed anyways:
> 1. result = bar is None ? default : bar

The below would have to evaluate all arguments, thus not achieving benefits of 
PEP505.
> 2. result = ifelse(bar is None, default, bar)


So I would vote for something similar to:
> result = bar is None ? default : bar


Where default and bar is only evaluated if needed. Although not to the extent 
as initially intended, it would offer satisfiable solutions to several 
proposals.


> On 15 Jul 2023, at 22:37, Dom Grigonis  wrote:
> 
> def fu(bar, default=1):
> bar = bar or default
> return bar
> 
> print(fu(None))   # 1 - as expected
> print(fu(2))  # 2 - as expected
> print(fu(0))  # 1 - not as expected
> 
> class A:
> def __bool__(self):
> return False
> 
> print(fu(A()) # 1 - not as expected
> 
> So it only works if ALL possible bar values are limited to those that 
> evaluate to True on truth test. And even if I have such cases, when this is 
> the case, I restrain from doing this for the sake of consistency of coding 
> style and to eliminate risk if I ever decide to introduce new input options 
> that do not comply with this restriction. Just to be on the safe side.
> 
> Obviously, one could do:
> def fu(bar, default=1):
> bar = bar if bar is not None else default
> return bar
> But not having lengthy, hard to read expressions to do such a simple thing is 
> the key here isn’t it?
> 
> So my latest resolve for such cases is simply:
> def fu(bar, default=1):
> if bar is None:
> bar = default
> return bar
> So 2 lines instead of 1, but easy to read, risk-free simple code.
> 
> In case of class construction, I suffer 1 extra assignment here:
> def __init__(self, bar, default=1):
> self.bar = bar
> if bar is None:
> self.bar = default
> Which I don’t like! Extra assignment is not ideal. Of course I could use:
> def __init__(self, bar, default=1):
> if bar is None:
> self.bar = default
> else:
> self.bar = bar
> Or the 1-line if-else, but (to repeat myself) these 2 don’t read nicely and 
> lack aesthetics for such a simple case as this.
> 
> IMO, what could probably be a good (time tested and convenient) solution is 
> to introduce something similar to C-style, low-level `ifelse` expression.
> 
> string result = (time < 18) ? "Good day." : "Good evening.”;
> 
> My personal opinion is that 1-line pythonic if-else expression lacks pythonic 
> aesthetics.
> 
> The PEP505 looks nice, but it is mostly concerned with `None`, which I IMO is 
> the reason it didn’t go through. It’s the same as with sentinels: 
> https://peps.python.org/pep-0661/ <https://peps.python.org/pep-0661/>
> 
> The proposal is too narrow and specific, to be implemented in core python. In 
> other words, it only solves one corner case, but not the root issue. My 
> solution to PEP661 was to use `unittest.sentinel` so I can define my own 
> `None` alternatives.
> 
> Now, if PEP505 was accepted, then it would only work for `None`, but not for 
> user-defined sentinels, meaning it is not a good solution either - something 
> more general is needed. What I think could potentially be optimal is either:
> 1. result = bar is None ? default : bar
>   However, in this case, new operator had to be introduced instead of 
> “:”, which I am sure would arise many discussions. Although, I think this is 
> a very elegant expression
> 2. result = ifelse(bar is None, default, bar)
>   Having such well-optimised builtin in core python, would also be a good 
> solution without introduction of any new operators.
> 
> Now, this doesn’t directly solve your initial proposal:
> ifelse(dict.get('key') is None, {}, dict.get('key')).get('child_key')
> However, then it could be easier to define a new method when subclassing 
> `dict` or `UserDict`
> from unittest.sentinel import Sentinel
> NotGiven = Sentinel.NotGiven
> 
> class PlayDict(dict):
> def get_or(self, key, default=NotGiven, arbitrary=None):
> value = self.get(key, default)
> return value is NotGiven ? arbitrary : value
> # OR
> return ifelse(value is NotGiven, arbitrary, value)
> Whether this is included in core-python or not is another matter. It is not 
> as elegant as proposal in PEP505, but it is not limited to `None` sentinel, 
> while making use of nicely-read 1-liner.
> 
> So IMO, a more elegant if-else 1-liner is potentially a happy middle, which 
> would cover many different cases, although not as elegantly as PEP505.
> 
&g

[Python-ideas] Re: Proposal for get_or function in Python dictionaries

2023-07-15 Thread Dom Grigonis
> I understand your perspective, but the fact is that this makes the code 
> lengthier and adds an extra step to what I am already trying to do. 
> Additionally, if I understand correctly, I could implement a built-in method 
> as a function that takes in the key and uses a try-except block to get the 
> value or return None, which is essentially Python's way of handling missing 
> values (similar to get()).
> I proposed this solution because Python is widely used by many people and 
> organizations for web scraping and API integrations, where None values are 
> often expected and need to be handled efficiently. I believe this could be a 
> valuable addition, but please correct me if I'm wrong.
I think adding an extra method is the only reasonable solution anyways. 
Modifying `dict.get` even if not breaking any existing functionality, would 
result in decreased performance across the whole landscape of code that uses 
`get`, which doesn’t seem like a big cost, but from experience, dictionary 
methods do tend to become bottlenecks in highly-optimised python code (which is 
often the case given the obvious disadvantage of interpreted language).

So the only question here is whether to add an extra method in python core. 
Such as you did e.g. `get_if`, or leave it to the user. If left to the user, 
then maybe it is possible to solve several issues at the same time by providing 
elegant, optimised & flexible one-liners (see my other e-mail) to do such 
thing, leaving implementation details to the user.

You are concerned about `None`, maybe someone else is concerned about some 
other value that he wishes to treat as non-valid. Permutations are endless in 
value-space and depth.

Implementing and especially changing already existing functionality in 
core-python requires consideration of many perspectives, which I, myself, do 
not have enough, so this is just my opinion.

But from what I have gathered from experience analysing others' and my own 
suggestions in this group, the one you are proposing (at least taken at it’s 
face value) is too limiting, and potentially too invasive for too little 
benefit in relation to how close to `python’s metal` it is.


> On 15 Jul 2023, at 20:57, Jothir Adithyan  wrote:
> 
> Dom Grigonis wrote:
>> This feels superfluous. Instead of creating new dict class I would propose 
>> either:
>> 1. Not to have None values
>>  a) It is most likely possible to pre-delete all None values before you use 
>> the dict = {k: v for k, v in dict if v is not None}
>>  b) Not to create them in the first place (if it depends on you)
>> 2. Or simply: (dict.get(‘k1’) or dict()).get(‘child_key')
>>> On 10 Jul 2023, at 22:18, Jothir Adithyan adithyanjot...@gmail.com wrote:
>>> Hi everyone,
>>> I would like to briefly present my idea regarding the `get` function 
>>> commonly used with dictionaries. When working with large amounts of JSON 
>>> data, I often encounter code that doesn't feel very Pythonic to me.
>>> Problem Statement:
>>> The `get` function allows chaining of method calls, which is quite useful 
>>> when working with dictionaries. It also has a convenient `default` 
>>> parameter that returns a default value if the key is not found in the 
>>> dictionary. This feature makes it safe and easy to use. However, problems 
>>> arise when the dictionary contains the key we are accessing, but the 
>>> corresponding value is `None`. In such cases, subsequent `get` calls fail 
>>> because the `get` method belongs to objects of type `dict` and not `None`. 
>>> To address this, I propose adding a new parameter to the `get` function or 
>>> introducing a new function called `get_or` that swiftly handles this issue. 
>>> This new parameter, called `arbitrary`, would accept an arbitrary value to 
>>> be returned by subsequent `get` calls in case the retrieved value of the 
>>> key is `None`.
>>> Assumptions:
>>> The problem statement is based on a few assumptions:
>>> 
>>> You prefer chaining `get` statements for cleaner code.
>>> You expect at least some of the `get` methods to return `None`.
>>> You want to avoid the hassle of using `try` and `except` for every `get` 
>>> chain.
>>> 
>>> If you fall into the category of people who wish for a simpler way to work 
>>> with dictionaries and handle large amounts of data, I hope you can 
>>> empathise with this proposal.
>>> I have made a simple implementation by modifying the `get` method, which is 
>>> below this thread. I would appreciate your valuable input on this feature. 
>>> Before diving into coding, I want to make sure this is not a bad idea 
>>> waiting t

[Python-ideas] Re: Proposal for get_or function in Python dictionaries

2023-07-15 Thread Dom Grigonis
def fu(bar, default=1):
bar = bar or default
return bar

print(fu(None))   # 1 - as expected
print(fu(2))  # 2 - as expected
print(fu(0))  # 1 - not as expected

class A:
def __bool__(self):
return False

print(fu(A()) # 1 - not as expected

So it only works if ALL possible bar values are limited to those that evaluate 
to True on truth test. And even if I have such cases, when this is the case, I 
restrain from doing this for the sake of consistency of coding style and to 
eliminate risk if I ever decide to introduce new input options that do not 
comply with this restriction. Just to be on the safe side.

Obviously, one could do:
def fu(bar, default=1):
bar = bar if bar is not None else default
return bar
But not having lengthy, hard to read expressions to do such a simple thing is 
the key here isn’t it?

So my latest resolve for such cases is simply:
def fu(bar, default=1):
if bar is None:
bar = default
return bar
So 2 lines instead of 1, but easy to read, risk-free simple code.

In case of class construction, I suffer 1 extra assignment here:
def __init__(self, bar, default=1):
self.bar = bar
if bar is None:
self.bar = default
Which I don’t like! Extra assignment is not ideal. Of course I could use:
def __init__(self, bar, default=1):
if bar is None:
self.bar = default
else:
self.bar = bar
Or the 1-line if-else, but (to repeat myself) these 2 don’t read nicely and 
lack aesthetics for such a simple case as this.

IMO, what could probably be a good (time tested and convenient) solution is to 
introduce something similar to C-style, low-level `ifelse` expression.

string result = (time < 18) ? "Good day." : "Good evening.”;

My personal opinion is that 1-line pythonic if-else expression lacks pythonic 
aesthetics.

The PEP505 looks nice, but it is mostly concerned with `None`, which I IMO is 
the reason it didn’t go through. It’s the same as with sentinels: 
https://peps.python.org/pep-0661/ <https://peps.python.org/pep-0661/>

The proposal is too narrow and specific, to be implemented in core python. In 
other words, it only solves one corner case, but not the root issue. My 
solution to PEP661 was to use `unittest.sentinel` so I can define my own `None` 
alternatives.

Now, if PEP505 was accepted, then it would only work for `None`, but not for 
user-defined sentinels, meaning it is not a good solution either - something 
more general is needed. What I think could potentially be optimal is either:
1. result = bar is None ? default : bar
However, in this case, new operator had to be introduced instead of 
“:”, which I am sure would arise many discussions. Although, I think this is a 
very elegant expression
2. result = ifelse(bar is None, default, bar)
Having such well-optimised builtin in core python, would also be a good 
solution without introduction of any new operators.

Now, this doesn’t directly solve your initial proposal:
ifelse(dict.get('key') is None, {}, dict.get('key')).get('child_key')
However, then it could be easier to define a new method when subclassing `dict` 
or `UserDict`
from unittest.sentinel import Sentinel
NotGiven = Sentinel.NotGiven

class PlayDict(dict):
def get_or(self, key, default=NotGiven, arbitrary=None):
value = self.get(key, default)
return value is NotGiven ? arbitrary : value
# OR
return ifelse(value is NotGiven, arbitrary, value)
Whether this is included in core-python or not is another matter. It is not as 
elegant as proposal in PEP505, but it is not limited to `None` sentinel, while 
making use of nicely-read 1-liner.

So IMO, a more elegant if-else 1-liner is potentially a happy middle, which 
would cover many different cases, although not as elegantly as PEP505.


> On 15 Jul 2023, at 21:07, Jothir Adithyan  wrote:
> 
> Dom Grigonis wrote:
>> I like this. Something that I would use for sure.
>> I have used a lot of:
>> ```
>> (value: None | object ) or default
>> ```
>> , but I stopped for obvious reasons. However, I miss those days, when I was 
>> ignorant that this is not a good idea.
>>> On 11 Jul 2023, at 01:17, David Mertz, Ph.D. david.me...@gmail.com wrote:
>>> This is basically PEP 505 – None-aware operators 
>>> (https://peps.python.org/pep-0505/ https://peps.python.org/pep-0505/).
>>> I've generally been opposed to that, but clearly some serious and smart 
>>> Pythonistas have supported it.  That PEP is a bigger lift than your 
>>> suggestion,  but correspondingly more general.
>>> On Mon, Jul 10, 2023, 6:04 PM Jothir Adithyan >> mailto:adithyanjot...@gmail.com> wrote:
>>> Hi everyone,
>>> I would like to briefly present my idea regarding the `get` function 
>>> commonly used with dictionaries. When working with large

[Python-ideas] Re: Proposal for get_or function in Python dictionaries

2023-07-10 Thread Dom Grigonis
I like this. Something that I would use for sure.

I have used a lot of:

```
(value: None | object ) or default
```

, but I stopped for obvious reasons. However, I miss those days, when I was 
ignorant that this is not a good idea.

> On 11 Jul 2023, at 01:17, David Mertz, Ph.D.  wrote:
> 
> This is basically PEP 505 – None-aware operators 
> (https://peps.python.org/pep-0505/ ).
> 
> I've generally been opposed to that, but clearly some serious and smart 
> Pythonistas have supported it.  That PEP is a bigger lift than your 
> suggestion,  but correspondingly more general.
> 
> On Mon, Jul 10, 2023, 6:04 PM Jothir Adithyan  > wrote:
> Hi everyone,  
> 
> I would like to briefly present my idea regarding the `get` function commonly 
> used with dictionaries. When working with large amounts of JSON data, I often 
> encounter code that doesn't feel very Pythonic to me.  
> 
> Problem Statement:  
> 
> The `get` function allows chaining of method calls, which is quite useful 
> when working with dictionaries. It also has a convenient `default` parameter 
> that returns a default value if the key is not found in the dictionary. This 
> feature makes it safe and easy to use. However, problems arise when the 
> dictionary contains the key we are accessing, but the corresponding value is 
> `None`. In such cases, subsequent `get` calls fail because the `get` method 
> belongs to objects of type `dict` and not `None`. To address this, I propose 
> adding a new parameter to the `get` function or introducing a new function 
> called `get_or` that swiftly handles this issue. This new parameter, called 
> `arbitrary`, would accept an arbitrary value to be returned by subsequent 
> `get` calls in case the retrieved value of the key is `None`.  
> 
> Assumptions:  
> 
> The problem statement is based on a few assumptions:  
> - You prefer chaining `get` statements for cleaner code.  
> - You expect at least some of the `get` methods to return `None`.  
> - You want to avoid the hassle of using `try` and `except` for every `get` 
> chain.  
> 
> If you fall into the category of people who wish for a simpler way to work 
> with dictionaries and handle large amounts of data, I hope you can empathise 
> with this proposal.  
> 
> I have made a simple implementation by modifying the `get` method, which is 
> below this thread. I would appreciate your valuable input on this feature. 
> Before diving into coding, I want to make sure this is not a bad idea waiting 
> to reveal itself in the dark.  
> 
> Thank you for taking the time to read this thread. Your feedback is greatly 
> appreciated.  
> 
> Best regards,  
> Jothir Adithyan  
> 
> 
> 
> 
> **Runnable Version**  
> https://replit.com/@Adithyan71/GetOr 
> 
> 
> 
> **Code Samples.**  
> 
> ```  
> class PlayDict(dict):  
> def get_or(self, key, arbitrary=None, default=None):  
> if not self.__contains__(  
> key  
> ):  # case 1 the key does not exist hence the default value  
> return default  
> elif (  
> self[key] is None  
> ):  # case 2 key does exist but the value is None return the arb 
> value  
> return arbitrary  
> return self[key]  # case 3 the key is present and the value is not 
> None  
> 
> 
> import contextlib  
> parent_dict = PlayDict()  
> parent_dict['k1'] = None  
> parent_dict['k2'] = {"child_key": "val"} # Parent dict can contain nested 
> dicts  
> 
> with contextlib.suppress(AttributeError):  
> result = parent_dict.get("k1", {}).get("child_key") # This will raise 
> AttributeError  
> 
> result = parent_dict.get_or("k1", default={}, arbitrary={}).get("child_key") 
> # This will work  
> 
> print(result)  
> ```
> ___
> 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/IELDCURRVQXCPGD4EPPLL7MYWJT4XHKV/
>  
> 
> 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/4BCGPZ6TJFN4DCXIPR5I24ND7MOYPV5T/
> Code of Conduct: http://python.org/psf/codeofconduct/


[Python-ideas] Re: Proposal for get_or function in Python dictionaries

2023-07-10 Thread Dom Grigonis
This feels superfluous. Instead of creating new dict class I would propose 
either:
1. Not to have None values
  a) It is most likely possible to pre-delete all None values before you use 
the dict = {k: v for k, v in dict if v is not None}
  b) Not to create them in the first place (if it depends on you)
2. Or simply: (dict.get(‘k1’) or dict()).get(‘child_key')

> On 10 Jul 2023, at 22:18, Jothir Adithyan  wrote:
> 
> Hi everyone,  
> 
> I would like to briefly present my idea regarding the `get` function commonly 
> used with dictionaries. When working with large amounts of JSON data, I often 
> encounter code that doesn't feel very Pythonic to me.  
> 
> Problem Statement:  
> 
> The `get` function allows chaining of method calls, which is quite useful 
> when working with dictionaries. It also has a convenient `default` parameter 
> that returns a default value if the key is not found in the dictionary. This 
> feature makes it safe and easy to use. However, problems arise when the 
> dictionary contains the key we are accessing, but the corresponding value is 
> `None`. In such cases, subsequent `get` calls fail because the `get` method 
> belongs to objects of type `dict` and not `None`. To address this, I propose 
> adding a new parameter to the `get` function or introducing a new function 
> called `get_or` that swiftly handles this issue. This new parameter, called 
> `arbitrary`, would accept an arbitrary value to be returned by subsequent 
> `get` calls in case the retrieved value of the key is `None`.  
> 
> Assumptions:  
> 
> The problem statement is based on a few assumptions:  
> - You prefer chaining `get` statements for cleaner code.  
> - You expect at least some of the `get` methods to return `None`.  
> - You want to avoid the hassle of using `try` and `except` for every `get` 
> chain.  
> 
> If you fall into the category of people who wish for a simpler way to work 
> with dictionaries and handle large amounts of data, I hope you can empathise 
> with this proposal.  
> 
> I have made a simple implementation by modifying the `get` method, which is 
> below this thread. I would appreciate your valuable input on this feature. 
> Before diving into coding, I want to make sure this is not a bad idea waiting 
> to reveal itself in the dark.  
> 
> Thank you for taking the time to read this thread. Your feedback is greatly 
> appreciated.  
> 
> Best regards,  
> Jothir Adithyan  
> 
> 
> 
> 
> **Runnable Version**  
> https://replit.com/@Adithyan71/GetOr
> 
> 
> 
> **Code Samples.**  
> 
> ```  
> class PlayDict(dict):  
> def get_or(self, key, arbitrary=None, default=None):  
> if not self.__contains__(  
> key  
> ):  # case 1 the key does not exist hence the default value  
> return default  
> elif (  
> self[key] is None  
> ):  # case 2 key does exist but the value is None return the arb 
> value  
> return arbitrary  
> return self[key]  # case 3 the key is present and the value is not 
> None  
> 
> 
> import contextlib  
> parent_dict = PlayDict()  
> parent_dict['k1'] = None  
> parent_dict['k2'] = {"child_key": "val"} # Parent dict can contain nested 
> dicts  
> 
> with contextlib.suppress(AttributeError):  
> result = parent_dict.get("k1", {}).get("child_key") # This will raise 
> AttributeError  
> 
> result = parent_dict.get_or("k1", default={}, arbitrary={}).get("child_key") 
> # This will work  
> 
> print(result)  
> ```
> ___
> 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/IELDCURRVQXCPGD4EPPLL7MYWJT4XHKV/
> 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/D4PFXZS7J27LYLXRSWTZVGCMGBYPOVL2/
Code of Conduct: http://python.org/psf/codeofconduct/


[Python-ideas] Re: "Curated" package repo?

2023-07-06 Thread Dom Grigonis
Thanks David,

Not keen to take it on solo.

Ideally, IMO, this could be a joint project of this whole group. Someone more 
senior from this group creates a repo and oversights the progress, couple of 
more experienced members make initial decisions to get things going, someone 
issues a review PR, couple of new OPs are suggested to write a review on their 
queries.

Would be good to know if:
1. Someone has their own little benchmarking/reviews and would be willing to 
spend a little time to issue PR for some initial content.
2. People from this group see themselves of going to such place and adding a 
new great package they have just found to existing reviews (or even more 
importantly an awful package)
3. Someone sees the opportunity to contribute given someone took such project 
on. e.g.
  a) someone is very excited about benchmarking automation
  b) someone has some working scripts to fetch github stats / stack trends that 
are waiting to be used
  c) someone wants to take their devops to next level and sees this as a good 
opportunity
  d) someone is very keen on high level view and would like to contribute in 
working on categorisation (partially relying on python stdlib/libref could be 
intuitive, although then it is a dependency)

A lot of “someones” in this e-mail...

> On 6 Jul 2023, at 16:55, David Mertz, Ph.D.  wrote:
> 
> Dom:
> 
> I'd recommend you simply start a GitHub project for "Curated PyPI", find a 
> catchy domain name, and publish that via GH Pages.  That's a few hours of 
> work to get a skeleton.  But no, I'm not quite volunteering to create and 
> maintain it myself today.
> 
> After there is a concrete site existing, you can refine the presentation and 
> governance procedure iteratively.  As a start, it can basically just be a web 
> page with evaluations like yours of the JSON libraries.  At a first pass, 
> there's no need for anything dynamic on the page, just some tables (or maybe 
> accordions, or side-bar navigation, or whatever).
> 
> I'd be very likely to make some PRs to such a repository myself.  At some 
> point, with enough recommendations, you might add some automation. E.g. some 
> script that checks all the submitted "package reviews" and creates an 
> aggregation ("10 reviews with average rating of 8").  Even there, running 
> that thing offline every once in a while is plenty to start (you could do GH 
> Actions or something too, if you like).
> 
> There are a few decisions to make, but none that difficult.  For example, 
> what format are reviews? Markdown? YAML? TOML? JSON? Python with conventions? 
> Whatever it is, it should have a gentle learning curve and be human readable 
> IMO.
> 
> 
> 
> On Thu, Jul 6, 2023 at 9:26 AM Dom Grigonis  <mailto:dom.grigo...@gmail.com>> wrote:
> It is possible, that issues being discussed at this stage are not as relevant 
> as they seem at stage 0, which this idea is at.
> (Unless someone here is looking for a very serious commitment.)
> 
> If some sort of starting point which is “light” in approach was decided on, 
> then the process can be readjusted as/if it progresses. Maybe no need to put 
> a “stamp” on a package, but simply provide comparison statistics given some 
> initial structure.
> 
> I think a lot of packages can be filtered on objective criteria, without even 
> reaching the stage of subjective opinions.
> 
> ———
> 
> General info - fairly easy to inspect without the need of subjective opinions.
> 1. License
> 2. Maintenance - hard stack overflow & repo stats
> 
> Performance - hard stats:
> 1. There will be lower level language extensions, which even if not up to 
> standards in other aspects are worth attention, someone else might pick it up 
> and rejuvenate if explicitly indicated.
> 2. There will be a pure python packages:
>   a) good coding standards with good knowledge on efficient programming in 
> pure python
>   b) pure python packages that take ages to execute
> 
> In many areas, this will filter out many libraries. Although, there are some, 
> where it wouldn’t. E.g. schema-based low level serialisation, where 
> benchmarks can be quite tight.
> 
> The remaining evaluation can be subjective opinions, where preferences of 
> curators can be taken into account:
> 1. Coding standards
> 2. Integration
> 3. Flexibility/functionality
> 4. …
> 
> IMO, all of this can be done while being on the safe side - if unsure, leave 
> the plain statistics for users and developers to see.
> 
> ———
> 
> An example. (I am not the developer of any of these)
> Json serialisers:
> 1. json - stdlib, average performance, well maintained, flexible, very safe 
> to depend on
> 2. simplejson - 3rd party, pure python, perfo

[Python-ideas] Re: "Curated" package repo?

2023-07-06 Thread Dom Grigonis
It is possible, that issues being discussed at this stage are not as relevant 
as they seem at stage 0, which this idea is at.
(Unless someone here is looking for a very serious commitment.)

If some sort of starting point which is “light” in approach was decided on, 
then the process can be readjusted as/if it progresses. Maybe no need to put a 
“stamp” on a package, but simply provide comparison statistics given some 
initial structure.

I think a lot of packages can be filtered on objective criteria, without even 
reaching the stage of subjective opinions.

———

General info - fairly easy to inspect without the need of subjective opinions.
1. License
2. Maintenance - hard stack overflow & repo stats

Performance - hard stats:
1. There will be lower level language extensions, which even if not up to 
standards in other aspects are worth attention, someone else might pick it up 
and rejuvenate if explicitly indicated.
2. There will be a pure python packages:
  a) good coding standards with good knowledge on efficient programming in pure 
python
  b) pure python packages that take ages to execute

In many areas, this will filter out many libraries. Although, there are some, 
where it wouldn’t. E.g. schema-based low level serialisation, where benchmarks 
can be quite tight.

The remaining evaluation can be subjective opinions, where preferences of 
curators can be taken into account:
1. Coding standards
2. Integration
3. Flexibility/functionality
4. …

IMO, all of this can be done while being on the safe side - if unsure, leave 
the plain statistics for users and developers to see.

———

An example. (I am not the developer of any of these)
Json serialisers:
1. json - stdlib, average performance, well maintained, flexible, very safe to 
depend on
2. simplejson - 3rd party, pure python, performance in line with 1), drop-in 
replacement for json, been around for a while, safe to depend on
2. ultrajson - 3rd party, written in C, >3x performance boost on 1) & 2), 
drop-in replacement for json, been around for a while, safe to depend on
3. ijson - 3rd party, C, average performance, proprietary interface 
relying heavily on iterator protocol, status 
4. orjson - 3rd party, highly optimised C, performance on par with fastest 
serialisers on the market, not-a-drop-in-replacement for json, due to 
sacrifices for performance, rich in functionality, well maintained, safe to 
depend on
5. pyjson5 - 3rd party, c++ performance similar to ultrajson, can be a drop-in 
replacement for json, extends json to json5 features such as comments, well 
maintained, safe to depend on

(THIS IS JUST AN EXAMPLE OF COMPARISON, NOT TO BE RELIED ON)

So there is still a bit of opinion here, but all of this can be standardised 
and put in numbers, and comparison of this type can be  done with 
little-to-none personal opinion.

———

After structure for this is in place, it would be easier to discuss further 
whether more serious curation is needed/worthwhile/makes sense.

Allow queries from users, package developers, places to gather opinions, maybe 
volunteering to do a deeper analysis… 

And once there is enough input, maybe a curated guidance can be added to the 
review. But this is the next stage, which is not necessarily needed to be 
thoroughly thought out before putting in place something simple, objective & 
risk-free.

———

Maybe stage 1. is all that users need - a reliable place to check hard stats, 
where users and developers can update them for the benefit of all. With enough 
popularity, package developers should be motivated to issue stat updates (e.g. 
add additional column to benchmarking script), and users would issue similar 
updates (e.g. add additional column to benchmarking script, where the library 
is extremely slow).

It is possible that the project would naturally turn to direction of hard stat 
coverage instead of “deep” curation. E.g.
json serialisers become a sub-branch of schema-less serialisers,
which in turn become a branch of serialisers

Then the user can then view comparable stats of the whole branch, sub-branch, 
sub-sub-branch to get the information he needs to make decisions. And apply 
different filters in the process to get to the final list of packages on which 
the user will have to do hiss final subjective analysis anyways.

———

E.g. User needs a serialiser. He prefers schema-less, but willing to go 
schema-based given large increases in performance. Does not mind low 
maintenance status given he aims to maintain his own proprietary serialisation 
library in the long run. Naturally, clean & simple coding with permissive 
license is preferred.

Just a portal with up-to-date stats where user could interactively navigate 
such decisions would be a good start and potentially a “safe” route to begin 
with.

The starting work on such thing then would be more heavy on automation, rather 
than politics, which in turn will be easier to tackle later 

[Python-ideas] Re: "Curated" package repo?

2023-07-05 Thread Dom Grigonis
One way would be to categorise areas and sub-areas and have a clear indication, 
where the work has not been done.

So that if I came to such place, I could find the sub-topic that I am 
interested in with clear indication of the status.

> On 5 Jul 2023, at 21:48, Brendan Barnwell  wrote:
> 
> On 2023-07-04 17:21, Christopher Barker wrote:
>> Anyway, I'd love to hear your thoughts on these ideas (or others?)  - both 
>> technical and social.
> 
>   To my mind there are two interrelated social problems that make this 
> task difficult:
> 
> 1) Promulgating a list of "good" packages tends to make people think packages 
> not on the list are not good (aka "implied exhaustiveness")
> 2) In order to curate all or nearly all packages, you need curators with a 
> wide range of areas of interest and expertise (aka "breadth").
> 
>   The reason these are interrelated is that once people start thinking 
> your list is exhaustive, it's really important to have breadth in the 
> curation, or else entire domains of utility can wind up having all packages 
> implicitly proscribed.
> 
>   As an example, a few months ago I wanted to do some automated email 
> manipulations via IMAP.  I looked at the builtin imaplib module and found it 
> useless, so I went looking for other things.  I eventually found one that 
> more or less met my needs (imap_tools).
> 
>   The question is, what happens when a person goes to our curated index 
> looking for an IMAP library?  If they don't find one, does that mean there 
> aren't any, or there are but they're all junk, or just that there was no 
> curator who had any reason to explore the space of packages available in this 
> area?  In short, it becomes difficult for a user to decide whether a tool's 
> *absence" from the index indicates a negative opinion or no opinion.
> 
>   There are ways around this, like adding categories (so if you see a 
> category you know someone at least attempted to evaluate some packages in 
> that category), but they can also have their own problems (like increasing 
> the level of work required for curation).  I'm not sure what the best 
> solution is, but just wanted to mention this issue.
> 
> -- 
> Brendan Barnwell
> "Do not follow where the path may lead.  Go, instead, where there is no path, 
> and leave a trail."
>   --author unknown
> 
> ___
> Python-ideas mailing list -- python-ideas@python.org
> 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/WYLHRIBIRKP6W3HGCGFJGYHDL3GCSOR2/
> 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/O233MP5I5MJLTTVK7FRIKJPD6736R3KX/
Code of Conduct: http://python.org/psf/codeofconduct/


[Python-ideas] Re: Double "at" operator for matmul exponentiation

2023-07-05 Thread Dom Grigonis


> On 5 Jul 2023, at 21:07, Chris Angelico  wrote:
> 
> On Thu, 6 Jul 2023 at 04:02, Dom Grigonis  wrote:
>> What I would alternatively propose is to introduce a couple of (meaningless 
>> operators), so that library developers can make use of them as they wish. 
>> What characters aren't used? “$, ?, `” (or are they?).
>> 
> 
> What should their precedences be? Operators have to be given that, at
> least. Unfortunately, whatever precedence you choose, it's going to be
> awkwardly wrong for at least some potential use-cases.
Lowest precedence?

a + b + c ?op? a / b / c
a + b + (c ?op? a) / b / c

As this in theory is the highest level operator, given it would mostly be used 
in framework level packages, it’s precedence naturally begs for the lowest 
status.

But yes, then this would limit the operator to certain use cases. E.g. it 
wouldn’t be suitable to solve the problem of OP.

> That said, though, there are some pretty cool packages out there that
> create arbitrary operators. Some of them take advantage of multiple
> operators to allow multiple effective precedences. Consider for
> example:
> https://pypi.org/project/infix/
Infix operator is where my though process began in the first place - see the 
e-mail. My proposal is exactly to have a free operator to be used in packages 
such as the one you pointed to. Ok, so Infix works in the way that operands can 
not recognise object in between operators, so that it falls to `dunders` of the 
object between operators. Although this works, there would be more flexibility 
if both the operands and operator class had `free` operator implementation 
space. Some new patterns might arise.

It would be cleaner approach, currently `Infix` feels a bit hacky to me due to 
reusing of operators, which have another purpose.


> ChrisA
> ___
> 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/YQDJ5UMH23FYL5FVFNBLWPOROD5ZZQOG/
> 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/RVAKUXJ53QUBWFBGOSWTHP47HE3C4GCR/
Code of Conduct: http://python.org/psf/codeofconduct/


  1   2   >