[Python-ideas] Re: Allowing non-ASCII bracket and quote characters in source code

2022-01-18 Thread 2QdxY4RzWzUUiLuE
On 2022-01-18 at 12:07:15 +1100,
Steven D'Aprano  wrote:

> I would be more sympathetic to this idea if:

> 1. I knew how to easily type all those brackets on the keyboard,
> without having to use a GUI character picker.

That's between you and your OS.  I believe all the major ones have ways
to enter arbitrary characters and/or switch keyboards without a GUI (I
use Linux, and I know for sure that it does).

Someone on this list keeps saying that everyone wants to know how to
play the piano, but that no one wants to put in the hard work to learn
to play the piano.  ;-)  I don't know the entire unicode database, but I
have learned the code points I use often (and how to type them without a
GUI picker).

The unicode database clearly marks open and close parentheses, and even
contains enough data (on initial examination) to match up the pairs
(that doesn't help you easily type them, but it does help utility
programs, GUI or otherwise, help you pick an approprite one at the right
time).

> 2. I had a guarantee that all of the bracket characters would be both
> available and easily distinguishable in any typeface I used.

You don't have that gurantee now, unless you check for all those things
yourself ("easily distinguishable" is subjective) before you use a
typeface.  *only half a wink*
___
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/3MANLAJ5DPQD2ON6BE52ZCBX43KHYBXQ/
Code of Conduct: http://python.org/psf/codeofconduct/


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

2021-12-11 Thread 2QdxY4RzWzUUiLuE
On 2021-12-12 at 17:28:23 +1300,
Greg Ewing  wrote:

> On 11/12/21 1:22 pm, Christopher Barker wrote:
> > Darn — the P and A are swapped there.
> 
> "Argument" and "actual" both start with "A" -- does that help?

Then Parameters must be Potential (before they become Actualized as
Arguments)?
___
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/2T3NHAA3D5JKWTJRCEZWCWPCRVSKD6W3/
Code of Conduct: http://python.org/psf/codeofconduct/


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

2021-12-10 Thread 2QdxY4RzWzUUiLuE
On 2021-12-10 at 17:24:22 -0500,
"Eric V. Smith"  wrote:

> [0]: Or arguments, I can never remember which is which: someone needs
> to invent a memorable mnemonic device.

Pass Arguments
Accept Parameters

(I don't know.  I just made that up.  For some reason, the fact that
functions have "formal parameters" stuck with me (to me?) from
somewhere, and then I can put the pieces together to figure out where
the arguments must come from.  And you can't unsee it now; sorry.)
___
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/3KR5WACTXRJQDNXNEBQ6RXEYKNDBXGPN/
Code of Conduct: http://python.org/psf/codeofconduct/


[Python-ideas] Re: Should Python enforce Type-checking in the future?

2021-12-10 Thread 2QdxY4RzWzUUiLuE
On 2021-12-10 at 20:20:05 +,
deavid  wrote:

> A lot of you are referring to scripting, learning, and other ways of
> using Python that would be badly impacted. I already acknowledged that
> these exist (or at least I didn't notice here any other that I wasn't
> aware), and that's why I mentioned that there should be a way to avoid
> type-enforcing for these scenarios. Maybe by flag, by Python version,
> file extension...  The method doesn't matter much at this moment.  If
> it were "easy" to continue writing the old programs without types,
> what's the problem in trying to make types more popular?

I concede that certain programmers believe that type declarations and
static type checking are unilaterally and universally beneficial, and
that's why I think that there should be a way to request type-enforcing
for these scenarios.  Maybe by flag, by Python version, file
extension...  The method doesn't matter, because in all my decades of
writing software, in a dozen or more languages, getting the types right
at coding time has never been an issue.

It's very easy to get type checking if you want it, what's the problem
in trying to make types more popular?

[insert your own perfect-joking-serious-balance emoticon (no emoji,
please!)  here]
___
Python-ideas mailing list -- python-ideas@python.org
To unsubscribe send an email to python-ideas-le...@python.org
https://mail.python.org/mailman3/lists/python-ideas.python.org/
Message archived at 
https://mail.python.org/archives/list/python-ideas@python.org/message/LQ4CQOKHQXI6QTTYSFFCXPVZR26W3MPI/
Code of Conduct: http://python.org/psf/codeofconduct/


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

2021-12-05 Thread 2QdxY4RzWzUUiLuE
On 2021-12-06 at 02:15:36 +1100,
Chris Angelico  wrote:

> On Mon, Dec 6, 2021 at 1:48 AM <2qdxy4rzwzuui...@potatochowder.com> wrote:
> >
> > On 2021-12-05 at 20:30:53 +1100,
> > Chris Angelico  wrote:
> >

[...]

> > > https://pyauth.github.io/pyotp/#time-based-otps
> >
> > I agree.  *Not* conflating timestamps and event IDs is a good thing!
> > APIs and libraries like that are making my point:  the very notion of
> > "overriding the current time" is a bad one.  The notion of "defaulting
> > to the current time" might be okay, in some systems, until it isn't.
> 
> Time-based OTPs are using timestamps. That's what they do. Defaulting
> to the current time is *precisely* how most 2FA systems work. Being
> able to override the time is useful primarily for testing. So for the
> TOTP case, I would say that "timestamp=>time.time()" is the perfect
> way to spell it.

If time-based OTPs use timestamps, then why is there a timestamp
parameter at all?  "Current time" is part of the function, not part of
the API.

Testing functions like that is another problem; adding parameters to the
API does not solve it.  IMO, a better solution is a test harness that
can provide a known "current time" value.

[...]

> I don't know why you'd have something in a logger that lets you
> configure the time, but my guess would be that it's the same thing:
> you can unit-test the logger with consistent inputs. For instance:
> 
> def format_log_line(event, time=>current_time(), host=>get_host()):
> return ...

It's not a question of configuring *the* time, it's a question of
recognizing that there's more than one time:  the time the event
occurred is different from the time the event is logged.  Yes, in many
cases in many systems, it's a difference without a distinction.  In
other systems, timestamps added by loggers are wholly irrelevant.

Out of curiosity, why did you make host a late-binding parameter?

> # shorthand, obv you'd be using a proper testing framework
> assert format_log_line({...}, time=1638717131, host="example") == "..."
> 
> TBH, I think that defaulting to "event happened right now" is about as
> good a default as you'll ever get. In some situations you'll know when
> the event happened... but honestly, I'd rather know when the log line
> happened too. So if I have an event with an inbuilt timestamp, I'll
> incorporate that into the *body* of the log line, and still have the
> logger add its own timestamp.
> 
> But maybe I've spent too much time rummaging through logs from buggy systems.

In time-critical code, I'm not going to waste resources (time, memory,
CPU cycles) formatting a log entry.  The event occurred and has a
timestamp; formatting and logging will happen in a whole different
context (another thread?  another CPU?  another OS?  the O&M system at
the time the user asks to look at the logs?).  I'm not denying that
there are times you want both timestamps; I'm denying that you can
always conflate them without losing important information.

I'm sticking to my story, which is no doubt a product of the sorts of
systems I've built (and debugged, and not built):  the apparent use case
of "defaulting to a value that changes, like the current time or a
function-generated ID" is conflating the logic of the function with that
function's API.
___
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/IAG5LLCOOGNLVC54BFVWHV3H2ZO6YYSV/
Code of Conduct: http://python.org/psf/codeofconduct/


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

2021-12-05 Thread 2QdxY4RzWzUUiLuE
On 2021-12-05 at 20:30:53 +1100,
Chris Angelico  wrote:

> On Sun, Dec 5, 2021 at 5:41 PM <2qdxy4rzwzuui...@potatochowder.com> wrote:
> > Also FWIW, I still think that if you're doing (b) or (c), then you're
> > *not* doing default values anymore, you're moving pieces of the logic or
> > the design into the wrong place.  One example of (b) goes something like
> > this:
> >
> > def write_to_log(event, time=>current_time()):
> > actually_write_to_log(event, time)
> 
> Very very common use-case for that:
> 
> https://pyauth.github.io/pyotp/#time-based-otps

I agree.  *Not* conflating timestamps and event IDs is a good thing!
APIs and libraries like that are making my point:  the very notion of
"overriding the current time" is a bad one.  The notion of "defaulting
to the current time" might be okay, in some systems, until it isn't.

Any feature can be abused, but I don't think we should be using bad
designs and bad APIs to justify the feature in the first place.

> The vast majority of calls are going to leave the time parameter at
> the default. (The one I linked to has separate "at" and "now"
> functions, but combining them makes very good sense.)

I disagree.  Combining/conflating the time an event occurred and the
time it's actually logged doesn't make sense at all.  Or maybe I've
spent too much time rummaging through logs from concurrent and parallel
systems.

Oh, wait, we're veering off topic, but you like you said, this is Python
Ideas!  ;-)
___
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/X4OI6OANR7WGJG4EV2KRR4SMBJUPESQL/
Code of Conduct: http://python.org/psf/codeofconduct/


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

2021-12-04 Thread 2QdxY4RzWzUUiLuE
On 2021-12-01 at 17:16:34 +1100,
Chris Angelico  wrote:

> *PEP 671: Syntax for late-bound function argument defaults*
> 
> Questions, for you all:
> 
> 1) If this feature existed in Python 3.11 exactly as described, would
> you use it?

No.  I understand the arguments (pun intended) for the proposal, but I
find none of them compelling.

> 2) Independently: Is the syntactic distinction between "=" and "=>" a
> cognitive burden?

No.  The biggest cognitive burden I have with either is the lack of
white space around the = or =>, but that's a different problem.

> (It's absolutely valid to say "yes" and "yes", and feel free to say
> which of those pulls is the stronger one.)
> 
> 3) If "yes" to question 1, would you use it for any/all of (a) mutable
> defaults, (b) referencing things that might have changed, (c)
> referencing other arguments, (d) something else?

That depends on what you mean by "use."  I wouldn't *write* code that
uses it (I can't find many (if any) cases of (a), (b), or (c) in my
code), but I would have to *read* other people's code that does.

FWIW, the PEP doesn't mention mutability or mutable values at all.

Also FWIW, I still think that if you're doing (b) or (c), then you're
*not* doing default values anymore, you're moving pieces of the logic or
the design into the wrong place.  One example of (b) goes something like
this:

def write_to_log(event, time=>current_time()):
actually_write_to_log(event, time)

IOW, default to the current time, but allow the caller to specify a some
other time instead.  Maybe I'm old school, or overly pedantic, but IMO,
those are two different use cases, and there should be two separate
functions (potentially with separate authorization and/or notations in
the log, or maybe I've spent too much time deciphering badly designed
logs and log entries).  *Maybe* a better example would be something like
this:

def write_to_log(event, id=>generate_appropriate_uuid()):
actually_write_to_log(event, id)

but I would still personally rather (for testability and maintainability
reasons) write two functions, even (or perhaps especially) if they both
called a common lower-level function to do the actual work.

> 4) If "no" to question 1, is there some other spelling or other small
> change that WOULD mean you would use it? (Some examples in the PEP.)

No.

> 5) Do you know how to compile CPython from source, and would you be
> willing to try this out? Please? :)

Yes, and no.  (Seriously:  Apparently, I don't create APIs, in any
language, that would/could/might benefit from late binding default
values.  What would I be trying?)

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


[Python-ideas] Re: Adding pep8-casing-compliant aliases for the entire stdlib

2021-11-11 Thread 2QdxY4RzWzUUiLuE
On 2021-11-12 at 14:43:07 +1100,
Steven D'Aprano  wrote:

> On Thu, Nov 11, 2021 at 10:06:45PM -0500, Ricky Teachey wrote:
> 
> > Is there a standard idiom-- perhaps using a type-hint-- to signal to the
> > IDE/linter that my user-defined class is intended to be used as a
> > function/factory, and not as a type (even though it is in fact a type)?
> 
> Not really. I don't think there is even a standard idiom for the human 
> reader to decide whether something is used as a "function" or a "class". 
> It is subjective, based on usage and convention. As others have pointed 
> out, many functions in Python can be considered as class constructor:

Isn't that why we like duck typing?  I don't care what something is, I
just care what it does.  So when I call zip(x, y) and get an iterable,
what's the difference (to me, as the user) whether zip is a class or a
function or some arbitraru callable, let alone what the implementation
of the resulting iterable is?

If I want Java, I know where to find it.
___
Python-ideas mailing list -- python-ideas@python.org
To unsubscribe send an email to python-ideas-le...@python.org
https://mail.python.org/mailman3/lists/python-ideas.python.org/
Message archived at 
https://mail.python.org/archives/list/python-ideas@python.org/message/SLYABYDVTYDVY3WNEMAUKPCM6NRU7QNZ/
Code of Conduct: http://python.org/psf/codeofconduct/


[Python-ideas] Re: PEP 671: Syntax for late-bound function argument defaults

2021-10-30 Thread 2QdxY4RzWzUUiLuE
On 2021-10-31 at 14:56:36 +1100,
Chris Angelico  wrote:

> On Sun, Oct 31, 2021 at 2:43 PM <2qdxy4rzwzuui...@potatochowder.com> wrote:
> >
> > On 2021-10-30 at 18:54:51 -0700,
> > Brendan Barnwell  wrote:
> >
> > > On 2021-10-30 18:29, Chris Angelico wrote:
> >
> > > > Right. That is a very real difference, which is why there is a very
> > > > real difference between early-bound and late-bound defaults. But both
> > > > are argument defaults.
> > >
> > >   I don't 100% agree with that.
> >
> > This seems to be the crux of this whole sub-discussion.  This whole
> > thing scratches an itch I don't have, likely because of the way I
> > learned to design interfaces on all levels.  A week or so ago, I was
> > firmly in Brendan Barnwell's camp.  I really don't like how the phrase
> > "default value" applies to PEP-671's late binding, and I'm sure that
> > there will remain cases in which actual code inside the function will be
> > required.  But I'm beginning to see the logic behind the arguments (pun
> > intended) for the PEP.
> 
> Current versions of the PEP do not use the term "default value" when
> referring to late binding (or at least, if I've made a mistake there,
> then please point it out so I can fix it). I'm using the term "default
> expression", or just "default" (to cover both values and expressions).

I still see anything more complicated than a constant or an extremely
simple expression (len(a)? well, ok, maybe; (len(a) if is_prime((len(a))
else next_larger_prime(len(a)))? don't push it) as no longer being a
default, but something more serious, but I don't have a better name for
it than "computation" or "part of the function" or even "business logic"
or "a bad API."

> And yes; there will always be cases where you can't define the default
> with a simple expression. For instance, a one-arg lookup might raise
> an exception where a two-arg one could return a default value ...

Am I getting ahead of myself, or veering into the weeds, if I ask
whether you can catch the exception or what the stacktrace might show?

(At this point, that's probably more of a rhetorical question.  Again,
this is an itch I don't have, so I probably won't use it much.)

> > The human description language/wording is different; , but what Python
> > spells "default value," Common Lisp spells "initform."  Python is
> > currently much less flexible about when and in what context default
> > values are evaluated; PEP-671 attempts to close that gap, but is
> > hampered by certain technical and emotional baggage.
> 
> Lisp's execution model is quite different from Python's, but I'd be
> curious to hear more about this. Can you elaborate?

https://www.cs.cmu.edu/Groups/AI/html/cltl/clm/node64.html explains it
in great detail with examples; you're interested in &optional, initform,
and possibly supplied-p.  Summarizing what I think is relevant:

(lambda (&optional x)) is a function with an optional parameter
called x.  Calling that function without a parameter results in x
being bound to nil (Lisp's [overloaded] canonical
"false"/undefined/null value) in the function body.

(lambda (&optional (x 4))) is a function with an optional parameter
called x with an initform.  Calling that function without a
parameter results in x being bound to the value 4 in the function
body.  Calling that function with a parameter results in x being
bound to the value of that parameter.

(lambda (&optional (x 4 p))) is a function with an optional
parameter called x with an initform and a supplied-p parameter
called p.  Calling that function without a parameter results in p
being bound to nil and x being bound to the value 4 in the function
body.  Calling that function with a parameter results in p being
bound to t (Lisp's canonical "true" value) and x being bound to the
value of that parameter.

By default (no pun intended), all of that happens at function call time,
before the function body begins, but Lisp has ways of forcing evaluation
to take place at other times.

(lambda (a &optional (hi (length a works as expected; it's a
function that takes one parameter called a (presumably a sequence), and
an optional parameter called hi (which defaults to the length of a, but
can be overridden by the calling code).

I am by no means an expert, and again, I tend not to use optional
parameters and default values (aka initforms) except in the simplest
ways.
___
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/YZOVN5UX53QPF54EDPJ4C2KEUB5XJBXZ/
Code of Conduct: http://python.org/psf/codeofconduct/


[Python-ideas] Re: PEP 671: Syntax for late-bound function argument defaults

2021-10-30 Thread 2QdxY4RzWzUUiLuE
On 2021-10-30 at 18:54:51 -0700,
Brendan Barnwell  wrote:

> On 2021-10-30 18:29, Chris Angelico wrote:

> > Right. That is a very real difference, which is why there is a very
> > real difference between early-bound and late-bound defaults. But both
> > are argument defaults.
> 
>   I don't 100% agree with that.

This seems to be the crux of this whole sub-discussion.  This whole
thing scratches an itch I don't have, likely because of the way I
learned to design interfaces on all levels.  A week or so ago, I was
firmly in Brendan Barnwell's camp.  I really don't like how the phrase
"default value" applies to PEP-671's late binding, and I'm sure that
there will remain cases in which actual code inside the function will be
required.  But I'm beginning to see the logic behind the arguments (pun
intended) for the PEP.

As prior art, consider Common Lisp's lambda expressions, which are
effectively anonymous functions (such expressions are often bound to
names, which is how Common Lisp creates named functions); see
https://www.cs.cmu.edu/Groups/AI/html/cltl/clm/node64.html for
reference.

The human description language/wording is different; , but what Python
spells "default value," Common Lisp spells "initform."  Python is
currently much less flexible about when and in what context default
values are evaluated; PEP-671 attempts to close that gap, but is
hampered by certain technical and emotional baggage.

(OTOH, Common Lisp's lambda expressions take one more step and include
so-called "aux variables," which aren't parameters at all, but variables
local to the function itself.  I don't have enough background or context
to know why these are included in a lambda expression.)
___
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/MBGORGQFXHSZWJYERNYDMYJXIA4W4CPY/
Code of Conduct: http://python.org/psf/codeofconduct/


[Python-ideas] Re: PEP 671: Syntax for late-bound function argument defaults

2021-10-26 Thread 2QdxY4RzWzUUiLuE
On 2021-10-27 at 13:47:31 +1100,
Chris Angelico  wrote:

> On Wed, Oct 27, 2021 at 1:15 PM Brendan Barnwell  
> wrote:
> >
> > On 2021-10-26 17:41, Christopher Barker wrote:
> > > Python used to be such a simple language, not so much anymore :-(
> >
> > I quite agree, and I feel like this is my biggest reason why I don't
> > want this "feature" (or any of another gazillion features that have been
> > suggested and/or accepted here, including the walrus).  The benefit of
> > this PEP simply does not justify the added complexity of the language as
> > a whole.  Using None (or some sentinel) and including code to check for
> > it works fine.  It's not worth it to add a whole new layer of behavior
> > to something as basic as argument-passing just to avoid having to type
> > `if arg is None`.
> >
> 
> >>> help(bisect.bisect)
> 
> bisect_right(a, x, lo=0, hi=None, *, key=None)
> ...
> Optional args lo (default 0) and hi (default len(a)) bound the
> slice of a to be searched.

[...]

> Suppose this function were written as:
> 
> bisect_right(a, x, lo=None, hi=None, *, key=None)
> 
> Do we really need the ability to specify actual function defaults? I
> mean, you can just have a single line of code "if lo is None: lo = 0"
> and it'd be fine. Why do we need the ability to put "lo=0" in the
> signature? I put it to you that the same justification should be valid
> for hi.

I agree.  Why do we need the ability to put "lo=0" in the signature?  If
we have to rewrite parts of bisect_right for late binding anyway, then
why not go all out?  If you want to bisect a slice, then bisect a slice:

result = bisect_right(a[lo:hi], x)

Oh, wait, what if a has billions of elements and creating a slice
containing a million or two out of the middle is too expensive?  Then
provide two functions:

def bisect_right(a, x, key=None):
return bisect_slice_right(a, x, 0, len(a), key)

def bisect_slice_right(a, x, lo, hi, key=None):
"actual guts of bisect function go here"
"don't actually slice a; that might be really expensive"

No extraneous logic to (re)compute default values at all.  Probably
fewer/simpler units tests, too, but that might depend on the programmer
or other organizational considerations.  On the other side, parts of doc
strings may end up being duplicated, and flat is better than nested.

(No, I don't know the backwards compatibility issues that might arise
from re-writing bisect_right in this manner, nor do I know what the
options are to satisfy IDEs and/or users thereof.)

Running with Brandon Barnwell's point, is there a lot of code that gets
a lot simpler (and who gets to define "simpler"?) with late binding
default values?  Can that same code achieve the same outcome by being
refactored the same way as I did bisect_right?  I'm willing to accept
that my revised bisect_right is horrible by some reasonably objective
standard, 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/JYKWRN6KMW4KOSFFTXAZ3EDFETQKIAEP/
Code of Conduct: http://python.org/psf/codeofconduct/


[Python-ideas] Re: PEP 671: Syntax for late-bound function argument defaults

2021-10-25 Thread 2QdxY4RzWzUUiLuE
On 2021-10-26 at 12:51:43 +1100,
Chris Angelico  wrote:

> On Tue, Oct 26, 2021 at 12:40 PM <2qdxy4rzwzuui...@potatochowder.com> wrote:
> >
> > On 2021-10-26 at 12:12:47 +1100,
> > Chris Angelico  wrote:

> > > The difference between early evaluation and late evaluation is that
> > > one retains the *value* and the other retains the *expression*. So
> > > it's something like:
> > >
> > > _b_default = assign_targets(); _d_default = FIRE()
> > > def f(a, b, c, d):
> > > if a is not set: a = enter_codes()
> > > if b is not set: b = _b_default
> > > if c is not set: c = unlock_missiles()
> > > if d is not set: d = _d_default
> >
> > Is the phrase/concept "retains the expression" new?  Unless it's really
> > a new concept, is there an existing way to say that?
> 
> It's sloppy terminology, so the expression is probably new. You'll
> find similar phenomena ...

I get the feature (and I've stated my opinion thereof), and I understand
what you meant.  I guess I learned a long time ago not to make up new
words for existing things, or to reuse old words for new things.  You're
staying pretty focused (good job, and thank you!), but there's enough
random ideas floating around this thread that I thought I'd say
something.
___
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/XVL5GISCMZDOW26OGARWENGXG3VWUNWM/
Code of Conduct: http://python.org/psf/codeofconduct/


[Python-ideas] Re: PEP 671: Syntax for late-bound function argument defaults

2021-10-25 Thread 2QdxY4RzWzUUiLuE
On 2021-10-26 at 12:12:47 +1100,
Chris Angelico  wrote:

> On Tue, Oct 26, 2021 at 11:44 AM Rob Cliffe via Python-ideas
>  wrote:
> > I prefer 1).  Easier to understand and debug in examples with side-effects 
> > such as
> > def f(a := enter_codes(), b = assign_targets(), c := unlock_missiles(), 
> > d = FIRE()):
> > (not that this is something to be particularly encouraged).
> >
> 
> It's worth noting that this would call the functions at different
> times; assign_targets and FIRE would be called when the function is
> defined, despite not entering the codes and unlocking the missiles
> until you actually call f().

So much for evaluating default values from left to right; this could be
trouble even if the functions themsevles don't have side effects, but
merely access data that has been mutated between function definition
time and function call time.  Requiring that all late bound defaults
come after all early bound defaults (which has already come up as a
possibility) seems like a reasonable solution.

> The difference between early evaluation and late evaluation is that
> one retains the *value* and the other retains the *expression*. So
> it's something like:
> 
> _b_default = assign_targets(); _d_default = FIRE()
> def f(a, b, c, d):
> if a is not set: a = enter_codes()
> if b is not set: b = _b_default
> if c is not set: c = unlock_missiles()
> if d is not set: d = _d_default

Is the phrase/concept "retains the expression" new?  Unless it's really
a new concept, is there an existing way to say that?
___
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/OH3XLE5AUR77GOZDTE3KJBZL33RCJ4WA/
Code of Conduct: http://python.org/psf/codeofconduct/


[Python-ideas] Re: Syntax for late-bound arguments

2021-10-23 Thread 2QdxY4RzWzUUiLuE
On 2021-10-24 at 13:23:51 +1100,
Steven D'Aprano  wrote:

> On Sat, Oct 23, 2021 at 02:54:54PM -0700, 2qdxy4rzwzuui...@potatochowder.com 
> wrote:
> 
> [...]
> > > The function header is a syntactic construct - the "def" line, any
> > > decorators, annotations, etc.
> > 
> > If you mean that def statements and decorators run at compile time, then
> > I agree.  If you mean something else, then I don't understand.
> 
> Pedantic note: def statements and decorators run at runtime, the same as 
> all other statements. (Including class statements.)

Yep.  My mistake.

> > I can't make the leap to claiming that late binding is part of defining
> > the function's arguments.  You say "late binding of function arguments";
> > I say "the part of the function that translates the arguments into
> > something useful for the algorithn the function encapsulates."
> 
> Consider what happens when you call a function now:
> 
> bisect(alist, obj)

[good explanation of what happens with default parameters snipped]

> Now consider what would happen if we used late binding. Everything would 
> be the same, *except* that instead of fetching a static reference to a 
> pre-existing object, the interpreter would have to fetch a reference to 
> some code, evaluate the code, and use *that* object as the default.
> 
> There is no reason to consider that part of the function body, it is 
> still performed by the interpreter.
> 
> It is only habit from 30 years of working around the lack of late- 
> binding defaults by putting the code inside the function body that leads 
> us to think that late-binding is necessarily part of the body.
> 
> In Python today, of course late-binding is part of the body, because 
> that's the only way we have to delay the evaluation of an expression ...

Aha.  I see it now (and it's not just those 30 years of Python, it's the
previous decade of Basic, FORTRAN, Pascal, C, etc.).  My first impulse
remains that all those things "the interpreter" does with default values
are still part of the function, and that the shorthand declarative
syntax is still just sugar for the explicit logic.

> But consider languages which have late-binding, I think Smalltalk and 
> Lisp are the two major examples. I'm not an expert on either, but I can 
> read StackOverflow and extrapolate a meaning to code :-)
> 
> (defun test1 (&optional (x 0))
>(+ x x))
> 
> is a function that takes one argument with a default value of 0. Lisp 
> uses late-binding: the default value is an expression (an S-expression?) 
> that is evaluated when the code is called, not at compile time, but it 
> is not part of the body of the function (the `(+ x x)` expression.

Yep.  I've written some non-toy Lisp code, and perhaps because of the
language in Lisp documentation ("initial forms" rather than "default
values"), I definitely see all of that binding as part of the function,
whether I write it in the body or in the lambda list.

(FWIW, there's also a 3-tuple form of optional parameter, where the
third element is a predicate that is bound to a boolean value that
indicates whether the value of the argument came from the caller or the
default value (thus eliminating the need for unique sentinels).  If
you're so inclined, find "supplied-p-parameter" on
.)

As I said before, pushing this sort of logic into "late binding"
scratches an itch I don't have.  I gladly write two (or more) [public]
functions that call a common [possibly private] function rather than one
[public] function with optional arguments and default values.  Easy to
write; easy to read; and easy to test, maintain, and extend.  Yes,
theoretically, the number of functions grows exponentially, but rarely
do I need more than a few such glue functions to cover most (if not all)
of the real use cases.
___
Python-ideas mailing list -- python-ideas@python.org
To unsubscribe send an email to python-ideas-le...@python.org
https://mail.python.org/mailman3/lists/python-ideas.python.org/
Message archived at 
https://mail.python.org/archives/list/python-ideas@python.org/message/B6OK2OZ5UEF76T4O3VYTKRYSBR4Q3PBY/
Code of Conduct: http://python.org/psf/codeofconduct/


[Python-ideas] Re: Syntax for late-bound arguments

2021-10-23 Thread 2QdxY4RzWzUUiLuE
On 2021-10-24 at 06:54:36 +1100,
Chris Angelico  wrote:

> On Sun, Oct 24, 2021 at 6:18 AM <2qdxy4rzwzuui...@potatochowder.com> wrote:
> > > The expression would be evaluated in the function's context, having
> > > available to it everything that the function has. Notably, this is NOT
> > > the same as the context of the function definition, but this is only
> > > rarely going to be significant (eg class methods where a bare name in
> > > an early-bound argument default would come from class scope, but the
> > > same bare name would come from local scope if late-bound).
> >
> > > The purpose of this change is to have the function header define, as
> > > fully as possible, the function's arguments. Burying part of that
> > > definition inside the function is arbitrary and unnecessary.
> >
> > Those two paragraphs contradict each other.  If the expression is
> > evaluated in the function's context, then said evaluation is (by
> > definition?) part of the function and not part of its argumens.
> 
> The function header is a syntactic construct - the "def" line, any
> decorators, annotations, etc.

If you mean that def statements and decorators run at compile time, then
I agree.  If you mean something else, then I don't understand.

> But for the late-binding expressions to be useful, they MUST be
> evaluated in the context of the function body, not its definition.
> That's the only way that expressions like len(a) can be of value.
> (Admittedly, this feature would have some value even without that, but
> it would be extremely surprising and restrictive.)

I think we're saying the same thing, but drawing different conclusions.
I agree with everything in the first paragraph I quoted above, but I
can't make the leap to claiming that late binding is part of defining
the function's arguments.  You say "late binding of function arguments";
I say "the part of the function that translates the arguments into
something useful for the algorithn the function encapsulates."

> > As a separate matter, are following (admittedly toy) functions (a) an
> > infinite confusion factory, or (b) a teaching moment?
> >
> > def f1(l=[]):
> > l.append(4)
> > return l
> >
> > def f2(l=:[]):
> > l.append(4)
> > return l
> 
> Teaching moment. Currently, the equivalent second function would be this:
> 
> def f2(l=None):
> if l is None: l = []
> l.append(4)
> return l
> 
> And the whole "early bind or late bind" question is there just the
> same; the only difference is that the late binding happens somewhere
> inside the function body, instead of being visible as part of the
> function's header. (In this toy example, it's the very next line,
> which isn't a major problem; but in real-world examples, it's often
> buried deeper in the function, and it's not obvious that passing None
> really is the same as passing the array's length, or using a system
> random number generator, or constructing a new list, or whatever it
> is.)

It's only not obvious if the documentation is lacking, or the tools are
lacking, or the programmer is lacking.  The deeper "it" is in the
function, the more you make my point that it's part of the function
itself and not part of setting up the arguments.

> This is, ultimately, the same teaching moment that you can get in
> classes:
> 
> class X:
> items = []
> def add_item(self, item): self.items.append(item)
> 
> class Y:
> def __init__(self): self.items = []
> def add_item(self, item): self.items.append(item)
> 
> Understanding these distinctions is crucial to understanding what your
> code is doing. There's no getting away from that.

Understanding the difference between defining a class and instantiating
that class is crucial, as is noticing the very different source code
contexts in which X.items and self.item are created.  I agree.

Stuff in class definitions (X.items, X.add_item, Y.__init__, Y.add_item)
happens when X is created, arguably at compile time.  The code inside
the function suites (looking up and otherwise manipulating self.items)
happens later, arguably at run-time.

In f1, everything in the "def" statement happens when f1 is defined.  In
f2, part of the "def" statement (i.e., defining f2) happens when f2 is
defined (at compile-time), but the other part (the logic surrounding l
and its default value) happens when f2 is called (at run-time).

> I'm aware that blessing this with nice syntax will likely lead to a
> lot of people (a) using late-binding everywhere, even if it's
> unnecessary; or (b) using early-binding, but then treating
> late-binding as a magic bandaid that fixes problems if you apply it in
> the right places. Programmers are lazy. We don't always go to the
> effort of understanding what things truly do. But we can't shackle
> ourselves just because some people will misuse a feature - we have
> plenty of footguns in every language, and it's understood that
> programmers should be allowed to use them if they choose.

I 

[Python-ideas] Re: Syntax for late-bound arguments

2021-10-23 Thread 2QdxY4RzWzUUiLuE
On 2021-10-24 at 03:07:45 +1100,
Chris Angelico  wrote:

> def bisect(a, x, lo=0, hi=None):
> if lo < 0:
> raise ValueError('lo must be non-negative')
> if hi is None:
> hi = len(a)
> 
> It's clear what value lo gets if you omit it. It's less clear what hi
> gets. And the situation only gets uglier if None is a valid argument,
> and a unique sentinel is needed; this standard idiom makes help()
> rather unhelpful:
> 
> _missing = object()
> def spaminate(thing, count=_missing):
> if count is _missing: count = thing.getdefault()
> 
> Proposal: Proper syntax and support for late-bound argument defaults.
> 
> def spaminate(thing, count=:thing.getdefault()):
> ...
> 
> def bisect(a, x, lo=0, hi=:len(a)):
> if lo < 0:
> raise ValueError('lo must be non-negative')

[...]

> The expression would be evaluated in the function's context, having
> available to it everything that the function has. Notably, this is NOT
> the same as the context of the function definition, but this is only
> rarely going to be significant (eg class methods where a bare name in
> an early-bound argument default would come from class scope, but the
> same bare name would come from local scope if late-bound).

> The purpose of this change is to have the function header define, as
> fully as possible, the function's arguments. Burying part of that
> definition inside the function is arbitrary and unnecessary.

Those two paragraphs contradict each other.  If the expression is
evaluated in the function's context, then said evaluation is (by
definition?) part of the function and not part of its argumens.

As a separate matter, are following (admittedly toy) functions (a) an
infinite confusion factory, or (b) a teaching moment?

def f1(l=[]):
l.append(4)
return l

def f2(l=:[]):
l.append(4)
return l
___
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/5AFFSYSQDCPBKZ3JFPEZURVYFIHJRVXB/
Code of Conduct: http://python.org/psf/codeofconduct/


[Python-ideas] Re: Implementing string unary operators

2021-10-19 Thread 2QdxY4RzWzUUiLuE
On 2021-10-20 at 11:48:30 +1100,
Chris Angelico  wrote:

> TBH swapcase is a bit of a minefield if you don't know what language
> you're working with.

[...]

> The most logical "negation" of a string would be reversing it, which
> WOULD be... well, reversible. But that doesn't need an operator, since
> it already has slice notation.

Slice notation is also a minefield; [some] explosives are combining
characters.
___
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/W4P7XRM5C4DFSZUUSWEZAEA7HAC7ODEI/
Code of Conduct: http://python.org/psf/codeofconduct/


[Python-ideas] Re: Implementing additional string operators

2021-10-13 Thread 2QdxY4RzWzUUiLuE
On 2021-10-14 at 04:34:24 +1100,
Chris Angelico  wrote:

> On Thu, Oct 14, 2021 at 2:21 AM <2qdxy4rzwzuui...@potatochowder.com> wrote:
> >
> > On 2021-10-14 at 00:00:25 +0900,
> > "Stephen J. Turnbull"  wrote:
> >
> > > Chris Angelico writes:
> > >
> > >  > +1, although it's debatable whether it should be remove suffix or
> > >  > remove all. I'd be happy with either.
> > >
> > > If by "remove all" you mean "efefef" - "ef" == "", I think that's a
> > > footgun.  Similarly for "efabcd" - "ef" == "abcdef" - "ef".
> >
> > I don't know whether it qualifies as prior art, but in Erlang (a
> > language emphatically *not* known for its string handling), strings are
> > lists of codepoints, and the list subtraction operator¹ is spelled "--":
> >
> > The list subtraction operator -- produces a list that is a copy of
> > the first argument. The procedure is a follows: for each element in
> > the second argument, the first occurrence of this element (if any)
> > is removed.
> >
> > Example:
> >
> > 2> [1,2,3,2,1,2]--[2,1,2].
> > [3,1,2]
> >
> > And from my interactive prompt:
> >
> > 4> "abcdef" -- "ef".
> > "abcd"
> > 5> "abcdef" -- "ab".
> > "cdef"
> >
> > ¹ http://erlang.org/doc/reference_manual/expressions.html#list-operations
> 
> It definitely counts as prior art. Another language that allows string
> subtraction is Pike:
> 
> > "abcdef" - "ab";
> (1) Result: "cdef"
> 
> I don't think it's quite such a foot-gun as you might think; but on
> the other hand, I'm also quite happy to see string subtraction defined
> in terms of removesuffix, since that IS a closer inverse to string
> addition. It'd end up being one of those cases where both behaviours
> are useful, and I'd just have to change gears when coding in multiple
> languages. (Which has to happen anyway. There's plenty of little
> differences, like modulo with negative numbers.)

The footgun is coding in multiple languages.  You're in a maze of twisty
little passages, all different.  ;-)  Just remember to use your clutch
when you change gears.

So aside from filename extensions, what are the real use cases for
suffix removal?  Plurals?  No, too locale-dependent and too many
exceptions.  Whitespace left over from external data?  No, there's
already other functions for that (and regexen and actual parsers if
they're not good enough).  Directory traversal?  No, that's what path
instances and the os module are for.
___
Python-ideas mailing list -- python-ideas@python.org
To unsubscribe send an email to python-ideas-le...@python.org
https://mail.python.org/mailman3/lists/python-ideas.python.org/
Message archived at 
https://mail.python.org/archives/list/python-ideas@python.org/message/LRUGCVPQDCFKVW52OD2F5S34BVYS2TWA/
Code of Conduct: http://python.org/psf/codeofconduct/


[Python-ideas] Re: Implementing additional string operators

2021-10-13 Thread 2QdxY4RzWzUUiLuE
On 2021-10-14 at 00:00:25 +0900,
"Stephen J. Turnbull"  wrote:

> Chris Angelico writes:
> 
>  > +1, although it's debatable whether it should be remove suffix or
>  > remove all. I'd be happy with either.
> 
> If by "remove all" you mean "efefef" - "ef" == "", I think that's a
> footgun.  Similarly for "efabcd" - "ef" == "abcdef" - "ef".

I don't know whether it qualifies as prior art, but in Erlang (a
language emphatically *not* known for its string handling), strings are
lists of codepoints, and the list subtraction operator¹ is spelled "--":

The list subtraction operator -- produces a list that is a copy of
the first argument. The procedure is a follows: for each element in
the second argument, the first occurrence of this element (if any)
is removed.

Example:

2> [1,2,3,2,1,2]--[2,1,2].
[3,1,2]

And from my interactive prompt:

4> "abcdef" -- "ef".
"abcd"
5> "abcdef" -- "ab".
"cdef"

¹ http://erlang.org/doc/reference_manual/expressions.html#list-operations
___
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/WGIJAJSVR4XKXV4F34QFUIC65T7HE4N7/
Code of Conduct: http://python.org/psf/codeofconduct/


[Python-ideas] Re: dict_items.__getitem__?

2021-10-06 Thread 2QdxY4RzWzUUiLuE
On 2021-10-06 at 08:52:22 -0600,
Finn Mason  wrote:

> I'm not a huge fan. Sure, dicts are ordered now, but I doubt that many
> people use that feature. I honestly still think of them as unordered
> ;)

+1 on still think of mappings as unordered (but finding myself screaming
Get Off My Lawn more and more).  I won't comment on popularity, except
to note that there's a big part of me that thinks that it's popular for
all the wrong reasons.

I don't have any new arguments, but call me -1 on making mappings less
distinct from lists, unless and until there is *no* performance penalty
(space or speed) for using the former instead of the latter.
___
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/M2GZ2OWWQO7LYDS6VBWGW3XJSMOOPU4Q/
Code of Conduct: http://python.org/psf/codeofconduct/


[Python-ideas] Re: Power Assertions: Is it PEP-able?

2021-09-12 Thread 2QdxY4RzWzUUiLuE
On 2021-09-12 at 07:28:53 -0700,
Guido van Rossum  wrote:

> What about asserts that are not used for testing, but as classic
> “unless there’s a bug, this should hold”? Those may not want to incur
> the extra cost.

I was actually thinking exactly the opposite:  this would more useful in
production than in testing.

When I'm testing, tests build on each other.  I should know that the
inner parts work, and I should be testing specific aspects of the outer
parts.  If I don't have confidence in those inner parts, then I need to
write more tests against them.  If I don't "know" where the data comes
from in my assertions, then my tests are trying to test too much at
once.

On the other hand, weird things happen in production, and my first
reaction to "this shouldn't happen unless there's a bug" are is to start
looking in the logs at how we got there.  These power assertions are
like a retroactive or JIT logging mechanism (in the sense that I may not
have logged enough detail), or a sort of first order run-time debugger
that shows me what's relevant at the point of the failure.

As far as the extra cost goes, how does that cost compare to the full
stack trace I already get from the exception being raised?
___
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/RC373JSGZE2O6FOYJSPNZMOZU4DPNPKS/
Code of Conduct: http://python.org/psf/codeofconduct/


[Python-ideas] Re: PEP8 mandatory-is rule

2021-08-31 Thread 2QdxY4RzWzUUiLuE
On 2021-08-31 at 11:15:22 -0700,
Nick Parlante  wrote:

> As mentioned, PEP8 is formally for narrow cases, and includes
> disclaimers about not applying it mechanically, reflecting a basic
> reasonableness.  Nothing to complain about there.

> As a practical matter, the IDEs just default to having PEP8 checking
> on, and they do it in a very visual way - akin to a text editor which
> puts little squiggles under words it thinks are misspelled.

Aha:  The IDEs are the zealots.  :-)

(I might liken PEP8 violations to natural language grammar
recommendations rather than spelling mistakes:  words are either
misspelled or they're not; many grammar "violations" are matters of
style, individual preference, or accepted norms that change over time.)

I'm not sure I have much to add that hasn't been said already, except
perhaps that your issue is, indeed, with the IDEs and the linters rather
than with PEP8.

Do you tell your students which IDE(s) and linters to use, and/or how to
set them up?

[...]

> I want to get to a world that is, let's say, "== tolerant" ...

Do you use floating point values in your course?
___
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/WFXZV25SNM6HRXTURTKK7FJWWRFZO2ZY/
Code of Conduct: http://python.org/psf/codeofconduct/


[Python-ideas] Re: We should have an explicit concept of emptiness for collections

2021-08-23 Thread 2QdxY4RzWzUUiLuE
On 2021-08-23 at 21:06:46 -,
Tim Hoffmann via Python-ideas  wrote:

> - Re bool: As experienced python users we are used to translate `if
> not users` to "if users is empty" or "if we have no users", but it
> *is* less explicit than `if users.is_empty()`.

I mentally translate "if not users" to "if there are not users" or "if
there are no users."  Whether users is a list (or some other sequence),
a dict (or some other mapping), a set, or even some oddball collection
type (e.g., the responses from a database query) is an implementation
detail about which I don't care at that point.

> - Re len: `if not len(users)` or `if len(users) == 0` is more
> explicit, but its semantically on a lower level. Counting elements is
> a more detailed operation than only checking if we have any
> element. That detail is not needed and distracting if we are only
> interested in is_empty. This is vaguely similar to iterating over
> indices (`for i in range(len(users))`) vs. iterating over elements
> (`for user in users`). We don't iterate over indices because that's
> usually a detail we don't need.

Exactly.  Asking whether a collection contains an element is on a
slightly lower level than asking whether or not "there are any [Xs]."
___
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/B2ECN5IXNOOUVOMIHCTTAD3NQXSSXVTK/
Code of Conduct: http://python.org/psf/codeofconduct/


[Python-ideas] Re: Notation for subscripts.

2021-08-13 Thread 2QdxY4RzWzUUiLuE
On 2021-08-13 at 23:18:29 +1100,
Matsuoka Takuo  wrote:

> Given a subscriptable object s, the intended rule for the notation for
> getting an item of s seems that, for any expression {e}, such as
> "x, ",
>   s[{e}]
> (i.e., s[x, ] if {e} is "x, ") means the same as
>   s[({e})]

If e is an expression, then s[e] means s[e].

Sometimes, e happens to be a tuple, but Python doesn't create a tuple
just to call __getitem__.  The following expression:

x,

is a tuple all by itself.  Also:

(x,)

is that same tuple.

> (i.e., s[(x, )] in the considered case), namely, should be evaluated
> as s.__getitem__(({e})) (or s.__class_getitem__(({e})) when that
> applies). If this is the rule, then it looks simple and hence
> friendly to the user. However, there are at least two exceptions:
> 
> (1) The case where {e} is the empty expression "":

There is no such thing as an "empty expression."  "" is a string
containing no characters.

> The expression
>   s[]
> raises SyntaxError ...

Because there is no expression (which is different from a hypothetical
"empty expression."

> ... instead of being evaluated in the same way as
> s[()] is.

() is a tuple with no elements, just as [] is a list with no elements,
and "" is a string with no elements.
___
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/ZCSPKRQMVJ5RCR4WD62QIGLPYPJOFE4P/
Code of Conduct: http://python.org/psf/codeofconduct/


[Python-ideas] Re: slices syntactic sugar

2021-08-12 Thread 2QdxY4RzWzUUiLuE
On 2021-08-12 at 14:05:23 -,
eloi.riv...@aquilenet.fr wrote:

> This is how slices are used in the python standard library, indeed,
> but that does not stop me from interpreting the slices as "inclusive
> by default" in my library.  The inconsistency with the rest of the
> python standard library could be misleading, but I think maybe less
> than off-by-1 errors?

https://docs.python.org/3/library/functions.html#slice says that slice
objects represent "the set of indices specified by range(start, stop,
step)."  You are free to interpret a slice differently, but you may be
in for a fight against (or bug reports from) existing Pythonistas.

Also, given that slices explicitly represent indices, your API may be
clearer if you used ranges instead of slices, but the question of what
the end is would remain.  YMMV.

> You raise a good point however, that is: how to write a slice with
> expliciting the inclusiveness of one of the limit values?

By definition, slices derive from ranges, and by definition, ranges do
not include their ends.  A (stop, stop) pair that includes the stop
value is not a Python slice or a Python range.  If you're willing to
write your own gt class or function, then why not bt?

That said, I don't think I've ever explicitly created a slice.  And the
better iteration works, the less I use range.  I also can't recall using
BETWEEN in database queries (except maybe for dates?), but databases and
database queries are *not* my thing.  In that light, consider me -0 on
any new syntax for creating slices.
___
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/DPVAUYPLFOKF3T6HTDDVOJBEERVAPFOP/
Code of Conduct: http://python.org/psf/codeofconduct/


[Python-ideas] Re: slices syntactic sugar

2021-08-12 Thread 2QdxY4RzWzUUiLuE
On 2021-08-12 at 08:56:22 -,
eloi.riv...@aquilenet.fr wrote:

> Hi. I am working on a kinda-ORM library, which usage often implies to request 
> data within specific ranges:
> 
>  Foobar.search(
> attr1="foo",
> attr2=gt(10),
> attr3=between(42, 50)
> )
> 
> The use of "gt" or "between" methods to describe those operations feels a bit 
> cumbersome (as it is long to write, and you need to import those functions in 
> a lot of files), and I though it could be more pythonic to use slices instead.
> 
>  Foobar.search(
> attr1="foo",
> attr2=slice(10),
> attr3=slice(42, 50)
> )
> 
> I suggest an alternative way to instanciate slices, that would look like this:
> 
>  Foobar.search(
> attr1="foo",
> attr2=[10:],
> attr3=[42:50]
> )
> 
> What do you think?

I think there will be a lot of off-by-1 errors.

BETWEEN is inclusive on both ends.  BETWEEN 42 AND 50 includes records
where the value is 50.

Python slices are open ended intervals.  slice(42, 50) would *not*
include the value 50.

That tells me that slices are *not* a good substitute for BETWEEN when
it comes to database queries.
___
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/HDXSMLLD3NZ7UN2KF6J4PMSYP4HZFU2E/
Code of Conduct: http://python.org/psf/codeofconduct/


[Python-ideas] Re: Argparse.add_argument() argument for additional functionallity

2021-08-08 Thread 2QdxY4RzWzUUiLuE
On 2021-08-08 at 21:37:28 -,
Hasan Aliyev  wrote:

> For example we can have one ArgumentParser instance, for (windows, linux), 
> (community edition, pro edition) apps. It could give ability to show and be 
> able to run only allowed commands based on version of os, app or some other 
> logic.
> 
> import argparse
> 
> def some_callable():
> if edition() == 'pro_edition':
> return True
> return False
> 
> parser = argparse.ArgumentParser(
> prog="CustomProgramm", 
> description="CustomProgramms custom description",
> epilog='Epilog of this',
> )
> 
> parser.add_argument('--full-function', target=some_callable)
> 
> This --full-function argument will be available only if some_callable 
> function is True, otherwise it will not be shown in command line arguments.

How/why is that better than

if some_callable():
parser.add_argument('--full-function')

especially if there's more than option in the "pro edition"?
___
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/BPUCESZHW5TODUO65WPQMV7SKQIUZPJC/
Code of Conduct: http://python.org/psf/codeofconduct/


[Python-ideas] Re: Pattern matching in python function headers

2021-08-08 Thread 2QdxY4RzWzUUiLuE
On 2021-08-08 at 11:30:20 +0400,
Abdulla Al Kathiri  wrote:

> ... if we write “case” before “def” similar to “async” before “def” in
> async function it should be clear we are doing pattern matching. The
> function will be named case function.
> 
> case def fib(0):
>   return 0
> 
> case def fib(1):
>   return 1
> 
> case def fib(int(n)):
>   return fib(n-1) + fib(n-2) 
> 
> If you none of the parameters you pass match your case functions, an
> exception will be raised ...

Because the order of cases is significant, these would be difficult to
work with in the REPL.  If, for example, I start with your three
definitions, and then decide to write a special case¹ for 2, how do I
convince Python that

case def fib(2):
  return 1

belongs before the general case?

¹ Yeah, I know, special cases aren't special enough.  In a non-toy case
(pun intended), there could be any number of reasons to add a new case
in the middle, or to redfine/fix a case that already exists rather than
add a new case to the end.
___
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/4OWHKTPCNJML7Y5GRKI3DP2KBUFKDZKI/
Code of Conduct: http://python.org/psf/codeofconduct/


[Python-ideas] Re: C API for converting Python integers to/from bytes sequences

2021-08-08 Thread 2QdxY4RzWzUUiLuE
On 2021-08-08 at 09:41:34 +0100,
Barry Scott  wrote:

> What is mixed endian? I would guess that its use would be application
> specific - so I assume you would not need to support it.

Not AFAIK application specific, but hardware specific:

https://en.wikipedia.org/wiki/Endianness#Mixed
___
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/HTOGYMYROL5UGS5YXZAUA6HMRXE54B7G/
Code of Conduct: http://python.org/psf/codeofconduct/


[Python-ideas] Re: Pattern matching in python function headers

2021-08-06 Thread 2QdxY4RzWzUUiLuE
On 2021-08-06 at 21:57:47 +1000,
Steven D'Aprano  wrote:

> On Thu, Aug 05, 2021 at 09:39:44AM +0100, Sam Frances wrote:

> > def fib(0):
> > return 0
> > 
> > def fib(1):
> > return 1
> > 
> > def fib(n):
> > return fib(n-1) + fib(n-2)
> 
> I think that there is something rather disturbing about writing a
> function definition with a constant literal as parameter. It looks
> wrong and I'm sure it's going to confuse beginners.

You are not a beginner (nor am I); what's disturbing to you may or may
not look wrong or confuse someone else.  When I was a beginner,
x = x + 1 was disturbing, wrong, and confusing to me.

The proposed definition of the Fibonacci sequence mirrors the ones in
Wikipedia¹ and OEIS,² and will certainly be at least familiar to those
with a background in mathematics or coming to Python from functional
languages.

That said, I agree that it's not a good fit for Python, for reasons
expressed elsewhere in this thread.

FWIW, Lisp Flavored Erlang³ (a syntactically imperative language built
atop the Erlang VM and run-time) doesn't repeat the "def," only the
argument lists:

lfe> (defun ackermann
   ((0 n) (+ n 1))
   ((m 0) (ackermann (- m 1) 1))
   ((m n) (ackermann (- m 1)
 (ackermann m (- n 1)

Something like that might work in Python, but at that point, it's no
different from a function that matches on its *args argument.

¹ https://en.wikipedia.org/wiki/Fibonacci_number
² https://oeis.org/A45
³ https://lfe.io/
___
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/TCBZOFYGD7ZKCK3ITPXOEDZFDZDMDBVX/
Code of Conduct: http://python.org/psf/codeofconduct/


[Python-ideas] Re: writelines2?

2021-07-13 Thread 2QdxY4RzWzUUiLuE
On 2021-07-13 at 14:11:15 -,
sandhoners...@gmail.com wrote:

> Maybe (to be consistent with other functions like print), end= since
> that would allow even custom line endings

As it stands, writelines is consistent with readlines.  Both preserve
newlines.

All else being equal, the following copies a file:

input_file = open(input_pathname, 'r')
output_file = open(output_pathname, 'w')
lines = input_file.readlines()
output_file.writelines(lines)
input_file.close()
output_file.close()

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


[Python-ideas] Re: Extension methods in Python

2021-06-20 Thread 2QdxY4RzWzUUiLuE
On 2021-06-20 at 12:18:24 -,
Johan Vergeer  wrote:

> After working with Kotlin for a while I really started to like the
> idea of extension methods. I delivers a great way to extend the
> language without having to add features to the language itself.

I disagree with the premise that such a thing is great, although it does
have limited use cases (mostly revolving around bugs, whether you know
about the bug or are tracking it down).

That said, Python already allows it:

>>> class C: pass
>>> c = C()
>>> C.f = lambda self, *a: a # add method f to class C
>>> c.f(5, 6)
(5, 6)

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


[Python-ideas] Re: Add static variable storage in functions

2021-05-27 Thread 2QdxY4RzWzUUiLuE
On 2021-05-28 at 12:22:22 +1000,
Chris Angelico  wrote:

> [...] calculate something once and reuse the value, because you know
> that it won't change (or don't care if it changes) [...]

> (Some day I'll learn how to do this in real life. Why can't I buy just
> one egg, and then reuse the same egg for every meal?)

Those are mutable eggs.  Try immutable eggs instead.

Or obtain a hen, aka an egg factory (and a rooster, too, but that's off
topic, even for Python Ideas).

ObPython:

>>> egg = Egg()
>>> egg.scramble()
>>> egg.fry()
Traceback (most recent call last):
  File "", line 1, in 
EggStateError: cannot fry a scrambled egg

Mutability is the root of all evil.
___
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/7TTGNMQIHZKENGIYASYFBZI3KNJWY6CB/
Code of Conduct: http://python.org/psf/codeofconduct/


[Python-ideas] Re: Add static variable storage in functions

2021-05-27 Thread 2QdxY4RzWzUUiLuE
On 2021-05-27 at 22:33:25 +1000,
Steven D'Aprano  wrote:

> Aside from globals, which we agree are Considered Harmful, you've 
> suggested two alternative implementations:
> 
> - something with closures;
> 
> - hidden state in an object with a `__call__` method.
> 
> Closures are cool, but the hidden state really is inaccessible from 
> outside the function. (At least I've never worked out how to get to it.) 
> So the callable object is better for introspection and debugging.

Then fix your debugger.  ;-)

As I recall, you're a proponent of fixing what's broken rather than
creating workarounds.

(I also recall many discussions regarding failed sandboxes because of
Python's nearly infinite capacity for introspection.  Maybe closures are
the path to a true sandbox.)

Globals, persistent locals, closures, statics, class variables, instance
variables, etc. are all just different ways to hide state.  IMO, we
don't need another one.
___
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/LOB2FKM5XV3Y3TGQB532G7F2RF4JOHLN/
Code of Conduct: http://python.org/psf/codeofconduct/


[Python-ideas] Re: Introduce constants in Python (constant name binding)

2021-05-26 Thread 2QdxY4RzWzUUiLuE
On 2021-05-26 at 12:53:32 -,
Shreyan Avigyan  wrote:

> I've already given one. Since Python is dynamically typed changing a
> critical variable can cause huge instability. Want a demonstration?
> Here we go,
> 
> import sys
> sys.stdout = None
> 
> Now what? Now how can we print anything? Isn't this a bug? There are
> lots of code out there where we need to protect things from being
> overwritten. Though I'm never telling to use constants in Python
> stdlib or else I could have never done this demonstration. :)

In C:

fclose(stdout);

Now what?  Now how can we print anything?

(I'm sure other languages allow programs to close stdout, but C has come
up in this thread before.)

There are a handful of real use cases for closing (or otherwise
changing) stdout; e.g., background/daemon processes, programs that
operate exclusively in a graphical environment.
___
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/WJP6SHVNHCX35T4M5VRR2FOFIKYHH2TG/
Code of Conduct: http://python.org/psf/codeofconduct/


[Python-ideas] Re: New Idea: A safe keyword to execute the following statement in a failsafe mode.

2021-05-23 Thread 2QdxY4RzWzUUiLuE
On 2021-05-24 at 01:34:29 +1000,
Steven D'Aprano  wrote:

> On Sun, May 23, 2021 at 06:52:38PM +0530, Shivam Saini wrote:
> 
> > After all, python is known for one liners and this would be an another
> > great one liner if implemented.
> 
> Python isn't known for one-liners. You might be thinking of Perl.

I agree.

> Being known for one-liners is a bad thing. It means that your language 
> is famous for being written in an obfuscated, hard to read, hard to 
> maintain, style.

Being known for one-liners can (*can*, not must) mean that my language
has the right features, abstractions, and APIs for common use cases and
task(s) at hand.

Most programs are composed of multiple one-liners.  ;-)

Any program can be one line long if I put all the details into a library
function.  That said, a [standard] library that contains everything is
not a good goal.
___
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/A7UJZXGCSKMZAVFWHXKNX7FCOAVCD33C/
Code of Conduct: http://python.org/psf/codeofconduct/


[Python-ideas] Re: Add support for private variables, methods and functions in Python

2021-05-23 Thread 2QdxY4RzWzUUiLuE
On 2021-05-23 at 16:30:35 +0200,
Marco Sulla  wrote:

> On Sun, 23 May 2021 at 14:50, Chris Angelico  wrote:
> >
> > On Sun, May 23, 2021 at 10:42 PM Marco Sulla
> >  wrote:
> > >
> > > On Sun, 23 May 2021 at 14:35, Chris Angelico  wrote:
> > > >
> > > > On Sun, May 23, 2021 at 10:30 PM Marco Sulla
> > > >  wrote:
> > > > >
> > > > > I think the only reason to introduce something like `private` is
> > > > > refactoring. If you added a `_variable` and later you decided to
> > > > > expose it, you have to change it to `variable`. This is something that
> > > > > in languages like Java is not necessary, you have only to change the
> > > > > variable from private to public. This sometimes bothered me in Python.
> > > >
> > > > Since you started with it private, you should be able to solve this
> > > > with a simple search-and-replace within the class's own definition.
> > > > Nothing outside the class should be affected. If it's that hard to
> > > > replace "self._variable" with "self.variable"
> > >
> > > And, in non-trivial cases, it is :)
> >
> > I'm curious as to what sort of non-trivial cases you have to deal
> > with, where you have something harder than search-and-replace
> 
> For example, having _variable in another class.

Then it isn't/wasn't private.

> > Do you yearn for actual refactoring tools - which do exist?
> 
> Renaming tools of IDE do not work in 100% of the cases. For example,
> if you have _variable in an eval string, it's not replaced.

Another reason not to use eval.

> > Or maybe most Python programmers don't think in terms of private
> > members, and it's easier to just make something public from the start.
> 
> N, I see private vars used a lot. It's @property that, it seems to
> me, is used sporadically.

I suspect that I am not "most Python programmers,", but I always think
of state (aka members, variables, attributes) as private and internal.
If I think I need to reach into an application level object for its
state (to read it or to write it), or that I need a getter, let alone a
setter, then I'm doing (or have done) somthing else wrong.
___
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/MDCRGZBOHLTC5DGJFYXGOIJZ2WECT5YL/
Code of Conduct: http://python.org/psf/codeofconduct/


[Python-ideas] Re: Add support for private variables, methods and functions in Python

2021-05-06 Thread 2QdxY4RzWzUUiLuE
On 2021-05-06 at 18:34:55 -,
Shreyan Avigyan  wrote:

> Chris:
> > I'm not sure about other people, but I have never, not once, used
> > @property as a means of controlling access. So giving me another way
> > to do something that I am not, and don't want to, do... isn't much of
> > an argument. :)
> 
> Ok. I'm giving you another example that doesn't cause security issues but 
> instead instability. Consider this,
> 
> class A:
> def __init__(self, name):
> self.name = name
> def create_file(self):
> with open(name, "a") as file:
>   name.write("something")

At the risk of summoning Muphry's Law, ITYM file.write.

> Now consider this,
> 
> [1]: x = A("Name")
> [2]: x.create_file() # Creates a file named "Name"
> [3]: x.name = "name"
> [4]: x.create_file() # Creates a file named "name"
> 
> We never created a object for "name" but still there's a file named
> "name" out there. This is the work of read-only attribute. They
> prevent such instability issues.

What if I do this:

[1]: x = A("arbitrary-string")
[2]: x.create_file = lambda: os.unlink(self.name)
[3]: x.create_file() # Creates a file named "arbitrary-string"

We did create an object for "arbitrary-string" (and invoked it, too) but
now there's no such file out there.  Should I file a bug report against
class A?  *wink*

This is the work of un-pythonicity.  If that attribute is that
important, then call it _name instead of name, or make it a property
without a setter, or implement setattr as appropriate, or document it as
read-only outside of A.__init__.  Or even more than one of the above.
Then line [3] of your example violates the stated and/or implied API,
and is a bug.

Python is a Consenting Adults language; if it hurts when you do that,
then it's on you not to do that, or at least to report an actual case
where it hurt.  There are already mechanisms to design, document, and
implement mostly read-only data (stipulated:  allegedly 100% fool proof
solutions never seem to work out that way).
___
Python-ideas mailing list -- python-ideas@python.org
To unsubscribe send an email to python-ideas-le...@python.org
https://mail.python.org/mailman3/lists/python-ideas.python.org/
Message archived at 
https://mail.python.org/archives/list/python-ideas@python.org/message/S73KVN644ZWL442UOIXQ2CWZGGDPRRTT/
Code of Conduct: http://python.org/psf/codeofconduct/


[Python-ideas] Re: String comprehension

2021-04-30 Thread 2QdxY4RzWzUUiLuE
On 2021-05-01 at 03:05:51 -,
Valentin Berlier  wrote:

> Also I haven't seen anyone acknowledge the potential performance
> benefits of string comprehensions. The "".join() idiom needs to go
> through the entire generator machinery to assemble the final string,
> whereas a decent implementation of string comprehensions would enable
> some pretty significant optimizations.

In certain special cases, maybe.  In the general case, no.  How much
optimization can you do on something like the following:

c"f(c) for c in some_string if g(c)"

I'll even let you assume that f and g are pure functions (i.e., no side
effects), but you can't assume that f always returns a string of length
1.  Even the simpler c"c + c for c in some_string" at some point has to
decide whether (a) to collect all the pieces in a temporary container
and join them at the end, or (b) to suffer quadratic (or worse) behavior
by appending the pieces to an intermediate accumulator as it iterates.

Also, how often do any of the use cases come up in inner loops, where
performance is important?
___
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/4PMGNOW2OOKAJBZMULWB3FU6JA4IS3KR/
Code of Conduct: http://python.org/psf/codeofconduct/


[Python-ideas] Re: String comprehension

2021-04-30 Thread 2QdxY4RzWzUUiLuE
On 2021-04-30 at 14:14:50 -0400,
David Álvarez Lombardi  wrote:

[...]

> new = c"x.lower() for x in old if x in HARDCODED_LIST"  # filter-in chars
> that appear in earlier-defined HARDCODED_LIST and convert to lower
> new = c"x for x in old if not x.isprintable()"  # filter-in
> non-printable chars
> new = c"str(int(x) + 1) for x in old if isinstance(x, int)"  # increment
> all integers by 1

[...]

> My goal is to *decrease* complexity, and personal/higher-order/nested
> procedures do not accomplish this in my eyes.

Embedding a[nother] domain specific language in a string also doesn't
decrease complexity; look at all the regular expression builders.

Unless you're a core developer (or perhaps not even then), I suspect
that most library functions started as "personal" functions.  Hey,
here's something I need for this project ... hey, I just wrote that for
the last project ... how many times will I write this before I stick it
in general_utilities ... let's see what python-ideas thinks ...

Add the following to your personal library and see how many times you
use it in the coming weeks or months:

def string_from_iterable_of_characters(iterable):
return ''.join(iterable)

I haven't tested anything, but string_from_iterable_of_characters should
take everything inside your c-strings unchanged.
___
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/SCPXXP4QC5MKGCOIVHDZIAY5PDQM2DXN/
Code of Conduct: http://python.org/psf/codeofconduct/


[Python-ideas] Re: Iterable scalar values returning itself ones?

2021-04-15 Thread 2QdxY4RzWzUUiLuE
On 2021-04-16 at 04:03:33 +1000,
Chris Angelico  wrote:

> So brace-left, brace-right is "{}" but compose, brace-left,
> brace-right is "∅". If absolutely every Python programmer had this
> available, it might be enough to distinguish empty dict from empty
> set.

But if an empty set is composed from an empty dict, then the empty set
is not empty.

Unless it weighs as much as a duck?

Or your're Dutch?
___
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/2A4H67PTTBURVAPNTP6DASFNNWASEJLD/
Code of Conduct: http://python.org/psf/codeofconduct/


[Python-ideas] Re: Change the exception type and message raised when _curses is not found

2021-04-04 Thread 2QdxY4RzWzUUiLuE
On 2021-04-04 at 18:05:12 -,
Shreyan Avigyan  wrote:

> When importing the curses module, be it on Windows or Darwin or
> UNIX-based OS or any other platform, if the _curses module is not
> found then just a ModuleNotFoundError is raised. But this error is not
> very informational in case of _curses module. Since the curses module
> is packaged with the Python interpreter itself at first it may seem,
> to beginners especially, that the Python interpreter was not installed
> correctly and then they would go searching for an answer for about 4-5
> days.
> 
> We know that curses library is not installed on windows by default and
> may or may not be present on other operating systems. Most UNIX system
> have ncurses or other curses library installed by default.
> 
> Python errors have a reputation of being very informational. I would
> like to submit a PR to modify the curses module a little bit by
> declaring a BaseException class and raising that Exception with the
> message "_curses module not found. Make sure a curses library is
> installed" or some kind of message like that.
> 
> But before I do that I would like to take advice from experienced
> developers about somethings. Is this change in the exception, raised
> when _curses module is not found, acceptable by the Python Community?
> If it is then should a draft PEP be submitted or should a PR be
> directly submitted to https://github.com/python/cpython?

BaseException seems, well, wrong to me, and arguably less informational
(or worse, misinformational).  Why not just improve the error message in
the (presumably existing) ModuleNotFoundError?  Or create a specialized
CursesNotFoundError derived from ModuleNotFoundError?
___
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/M2UI5LR5ADOOBOBLTIEQ2VOUXY7LYGFO/
Code of Conduct: http://python.org/psf/codeofconduct/


[Python-ideas] Re: allow initial comma

2021-03-12 Thread 2QdxY4RzWzUUiLuE
On 2021-03-12 at 11:02:50 -0500,
Ned Batchelder  wrote:

> I think the only reason anyone ever used leading commas to begin with
> was because of languages that didn't allow a final trailing comma.  In
> those worlds, to keep the editing smooth, people moved the commas to
> the beginning of the line, breaking with every comma-tradition.

Allowing a trailing comma makes historical diffs shorter and easier to
read.

For exmaple, if I have a multiline list like this:

x = [
  1,
  2
]

and add a new element to the end, then I end up with the diff including
the 2 even though I didn't change the 2.  But if I had had a trailing
comma, then the diff only shows the new entry.

I see a lot of SQL with the commas at the beginnings of the lines
(mostly, I think, due to SQL's syntax), but it solves the same problem.

> I don't see a reason to make that odd style easier.

I like allowing a trailing comma (for all of the previously stated
reasons), but I agree that "we" (except the SQL people!) seem to have
settled on trailing delimiters rather than leading delimiters, probably
because of the way we write human languages.
___
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/BQIIQFR4W723C6DQDTQIRXKCMCZHKO4N/
Code of Conduct: http://python.org/psf/codeofconduct/


[Python-ideas] Re: Make list.reverse() more flexible

2021-03-05 Thread 2QdxY4RzWzUUiLuE
On 2021-03-05 at 16:27:27 -,
Vincent Cheong  wrote:

> Currently, list.reverse() only works for an entire list. If one wants
> to reverse a section of it 'in-place', one needs to slicing which
> makes the space complexity no longer O(1). One can also manually make
> a loop and do the reversal but that is even slower than
> slicing. List.reverse() does not take any arguments. Wouldn't it be a
> good if it can take in parameters such as 'start' and 'stop' to enable
> list.reverse() work even for a section of the list? When no arguments
> are specified, then it works on the whole list, like usual.

Try this:

def slice_reverse(the_list, start, stop):
the_list[start:stop] = the_list[stop - 1, start - 1, -1]

I'll defer on whether or not this deserves a place in the standard
library; the older I get, the more I prefer building new data than
mutating existing data.
___
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/DWV7DH3H7MIWQXMI2A5C5GAW4CYLSNDI/
Code of Conduct: http://python.org/psf/codeofconduct/


[Python-ideas] Re: SimpleNamespace vs object

2021-02-20 Thread 2QdxY4RzWzUUiLuE
On 2021-02-20 at 13:44:21 -0500,
David Mertz  wrote:

> Cheeseshop!

But then it would never contain the attribute I ask for, and throw a
different exception every time!  ;-)
___
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/5XPGE73JM6MA2275JW2ZVMZ6Q7VS74GL/
Code of Conduct: http://python.org/psf/codeofconduct/


[Python-ideas] Re: Alternate lambda syntax

2021-02-18 Thread 2QdxY4RzWzUUiLuE
On 2021-02-18 at 18:10:16 +0400,
Abdulla Al Kathiri  wrote:

> I will be very happy if those versions of Callable and anonymous
> functions exist in Python right now. See how elegant that would look
> like..
> 
> def func(x: int, y: int, f: (int, int) -> int) -> int:
>   return f(x, y) 

Elegant?  I realize that this is a contrived scenario, but even if the
identifiers x, y, and f were meaningful (e.g., account_balance,
socket_descriptor), the signal to noise ratio in that definition makes
me cringe.  And it only gets worse once I'm not dealing with ints.

> print(func(3, 4, (x, y) => x + y)) #Out: 7
> 
> Imagine your mouse is on :func: ‘func’ in VSC or PyCharm and see that
> you need the third parameter to be of type (int, int) -> int, you can
> immediately write an anonymous function that mirrors the structure of
> the annotation but instead of ->, you have =>. Straight forward.

If my IDE is that clever, then it can also type "lambda x, y: " for me
in addition to showing me that signature.

Aside:  And then a thousand developers/engineers/maintainers, auditors,
and testers (not to mention future me) have to read that anonymous
function.  Over and over.  And over.  Unless it's trivial, or simpler,
use a def statement, give it a name and a doc string, test it, and reuse
it.  And if it's that trivial, then trading "lambda" for "->" (or "=>")
doesn't matter.
___
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/4QNOE7AFAAYWZWQQJ24GCUMFVX2JBI4F/
Code of Conduct: http://python.org/psf/codeofconduct/


[Python-ideas] Re: SimpleNamespace vs object

2021-02-17 Thread 2QdxY4RzWzUUiLuE
On 2021-02-18 at 06:21:19 +1100,
Chris Angelico  wrote:

> On Thu, Feb 18, 2021 at 1:53 AM Ricky Teachey  wrote:
> > 
> > I would personally love for SimpleNamespace to get a shorter name and 
> > become a built-in.
> 
> Okay. Let's start bikeshedding. If SimpleNamespace were to become a
> builtin, what should its name be? It needs to be short (obviously),
> but not TOO short, and it needs to be at least somewhat descriptive,
> and it needs to not cause confusion with "object". Ideally, it should
> get a name that's unlikely to conflict with names already in frequent
> use.
> 
> * namespace
> * ns
> * Thing
> * dump
> * plunkit
> 
> I'm not a fan of any of those, but let's see how inspired other people are :)

stuff (thank you, George Carlin!)
bag

Using a initial lower case letter makes it feel more built in, at the
expense of likely breaking more existing code.  Using an initial capital
letter makes it feel more like a class, which may or may not be a good
thing.
___
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/GFEWKTMWR5VJJSH2LP6XC2CLBNMDRJXX/
Code of Conduct: http://python.org/psf/codeofconduct/


[Python-ideas] Re: Adding `open_text()` builtin function. (relating to PEP 597)

2021-01-24 Thread 2QdxY4RzWzUUiLuE
On 2021-01-25 at 00:29:41 +1100,
Steven D'Aprano  wrote:

> On Sat, Jan 23, 2021 at 03:24:12PM +, Barry Scott wrote:
> 
> > I think that you are going to create a bug magnet if you attempt to auto
> > detect the encoding.
> > 
> > First problem I see is that the file may be a pipe and then you will block
> > until you have enough data to do the auto detect.
> 
> Can you use `open('filename')` to read a pipe?

Yes.  Named pipes are files, at least on POSIX.

And no.  Unnamed pipes are identified by OS-level file descriptors, so
you can't open them with open('filename'), but you can open them with
os.fdopen.  Once opened, such data sources "should be" interchangeable.

> Is blocking a problem in practice? If you try to open a network file,
> that could block too, if there are network issues. And since you're
> likely to follow the open with a read, the read is likely to block. So
> over all I don't think that blocking is an issue.

If open blocks too many bytes, then my application never gets to respond
unless enough data comes through the pipe.  Consider protocols like FTP
and SMTP, where commands and responses are often only handfuls of bytes
long.  OTOH, if I'm opening a file (or a pipe) for such a protocol, then
both ends should know the encoding ahead of time and there's no need to
guess.
___
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/55ZMKKQES3EYMXZFYPHOT3WYOKXMUG3Q/
Code of Conduct: http://python.org/psf/codeofconduct/


[Python-ideas] Re: timeit improvement idea: add an option to measure a script execution time

2021-01-10 Thread 2QdxY4RzWzUUiLuE
On 2021-01-10 at 18:38:12 +0100,
Alex Prengère  wrote:

> Today I had a quite simple need, I am unsure about the best way to do
> it, and saw a possible improvement for the *timeit *module.
> 
> I have about 30 Python scripts and I want to measure precisely their
> execution times, without measuring the interpreter startup time, because
> for most of them it is quite short (<1ms).

Are you solving the right problem?  If starting up the interpreter
dominates actual wall clock execution time and/or user time in your
computer, then why are you concerned with the scripts' execution time?

And if you're trying to determine the fastest way to build a piece of a
larger process, will your measurements carry forward into that larger
process?  In other words, if Script One runs in X milliseconds all by
itself, will it also run in X milliseconds when it's called from a
program that's also doing other things?

> 3. Use timeit. The scripts have no side effects so repeating their
> execution the way timeit does, works for me. The only issue is that,
> as far as I know, timeit only allows statements as input parameters,
> not the whole script, like for example:
> $ python -m timeit --script script.py

> 4. Write custom code to import each script.

One of those seem like the right solution, depending on why you're
measuing what you're measuring.
___
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/ZLDV6TENWNKFHRQ5WGIZKKCWQGQTFAG4/
Code of Conduct: http://python.org/psf/codeofconduct/


[Python-ideas] Re: pathlib enhancements

2021-01-09 Thread 2QdxY4RzWzUUiLuE
On 2021-01-10 at 05:03:08 +1100,
Chris Angelico  wrote:

> On Sun, Jan 10, 2021 at 4:51 AM Stephen J. Turnbull
>  wrote:
> >
> > Joseph Martinot-Lagarde writes:
> >
> >  > One remark about this : .tar.gz files are the exception rather than
> >  > the rule, and AFAIK maybe the only one ?
> >
> > Not really.  stem.ext -> stem.ext.zzz where zzz is a compression
> > extension is a pretty common naming convention.  For me ext == 'tar'
> > is by far the most common case (74%), 'tis true, but 'patch' (10%),
> > 'txt' (6%), 'tab', 'gml', 'xml', 'svg', 'pdf', 'ps', ' dvi', 'diff',
> > 'pdb', 'cpp', 'el', and 'data' also exist somewhere under $HOME.  I'll
> > bet others show up if I search /usr, /var, and /opt.
> 
> Yep, and most of my man pages are compressed, so there's
> usr/share/man/man1/*.1.gz and friends.
> 
> I'd say the most common case with multiple extensions is indeed
> precisely two, where the first one is the type of file (or in the case
> of man pages, the section), and the second is a compression format.
> But there'll be less common cases too.

I also have a pile of whatever-x.y.z.* files, where the * is some kind
of compression extension and x.y.z is a major.minor.patch identifier.

Most of the time, my brain is big enough to spot where x.y.z ends and
the extension(s) begin(s), but throw in a version identifier like
4.3.beta, and all bets are off (unless I happen to know exactly what to
look for, in which case I wouldn't bother with a general purpose library
function that might make the wrong assumption).
___
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/WPDXKRGXDDLC4GOCFW3OIHTPHOM7KJMZ/
Code of Conduct: http://python.org/psf/codeofconduct/


[Python-ideas] Re: An option to force the path separator for the "os.path.join()" method.

2021-01-05 Thread 2QdxY4RzWzUUiLuE
On 2021-01-06 at 07:07:30 +0300,
Mikhail V  wrote:

> I'd like to have an option to force the path separator for the
> "os.path.join()" method.
> E.g. if I run the script on Windows, but I generate, say, an URL, I'd
> find it convenient
> to use the same method, but with an explicit flag to "join" with the
> forward slash (because URLs use it).
> Currently I simply use an f-string to combine  a path, like e.g.:
> 
> path = f"{root}/{dir}"
> 
> but it will insert extra "/" if there if "root" already has "/" on the end.
> But the "join" method will not, which is a pro for the method vs
> "manual" string construct.
> 
> I know there is the "pathlib" module with all conversion methods, but
> it's overkill for many
> tasks. So I'd rather like to have an option to write for example:
> 
> path = os.path.join (root, dir, sep = "posix")
> 
> So that it joins with the forward slash even if run on Windows.
> Also it seems that e.g. "os.path.split()" already supports both
> separators, so I think this addition won't bring inconsistency into
> the module and its usage.

I'm not sure whether a method in the os module should understand URLs
(are URLs part of the OS, or part of something else?), but in any case,
in your example, it would make more sense to have a "URL" separator and
not use "posix" as a simple synonym for forward slash.  IMO, using "/"
itself is clearer.

That said, AIUI, there's nothing stopping a web server from using
whatever separators it wants.  Everything after the domain name is up to
the web server to interpret; it just happens that most early web servers
ran on Unix/Posix/Linux boxes and mapped URLs fairly directly to parts
of the file system, and "/" was more natural than anything else.
___
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/5KGGSYF4NLE5MCZXS7D5F2PR6E6RLSNY/
Code of Conduct: http://python.org/psf/codeofconduct/


[Python-ideas] Re: Standard tool for iterating over recursive data structures?

2021-01-01 Thread 2QdxY4RzWzUUiLuE
On 2021-01-01 at 16:34:15 +1100,
Steven D'Aprano  wrote:

> This isn't so much an idea for Python, as a request for ideas to solve a 
> problem in Python.

[examples of recurive data snipped]

> The built-ins handle these cases okay. Likewise the copy.deepcopy
> function takes care to avoid getting stuck in a loop with recursive
> data structures.

The POSIX utilities tar and find (and I'm sure there are more) also deal
with this.

> On the other hand, when I write code to process nested data
> structures, I always worry about such recursive patterns, but actually
> doing something about it is too hard. So I just ignore the risk and
> feel guilty about it. I'm sure I'm not the only one who feels guilty
> about ignoring this problem.

Sorry about the guilt.

Know your requirements!  Specify your constraints and limitations!
Document, document, document!  But you know that stuff already.

> To say nothing of those who don't even know there's a problem to worry
> about.

*sigh*

> Is there something we can do to make it easier for people to deal with
> recursive data structures, like the list repr and deepcopy code does?
> Is there a pattern we can abstract out and provide as a tool or recipe
> for people to use in their own code?

My first thought was that all of those things (printing a list,
navigating a tree^H^H^H^H cyclic graph, deepcopying data, etc.) are the
recipes, and that every use case is different, but that's kind of a cop
out.

If I had to "abstract out" a pattern or an algorithm, it might look
something like this:

1.  initialize been_there to an empty set
2.  initialize go_here to a collection containing the root of the data
  (e.g., go_here = [root])
3.  if go_here is empty, then stop
4.  remove one element from go_here, assign it to current_node
5.  if current_node is in been_there, go back to step 3
6.  deal with current_node
7.  add current_node to been_there
8.  add each of current_node's "next node"s to go_here
9.  go back to step 3

IOW, keep track of where you've been, and don't go there again.  I
probably should say out loud that go_here should contain the id of nodes
rather than references to nodes (to avoid having to know too much about
how to determine equality amongst nodes), but I was trying to stay away
from too many Python- or implementation- specific details.

Yes, it takes additional time and space not to dump core.  No, you don't
have to do this if you're certain that your data isn't recursive (even
if your data structure is).

But that seems too obvious and (at least at this level) too simple.
It's almost right out of any graph (vertexes and edges) library that
handles non-acyclic graphs, directed or not.  So maybe it doesn't
provide for a pretty "..." at the right place in the report.  What am I
missing?
___
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/O62LCGZXLEW2N3X7QOGRS2U3EOIRGUV2/
Code of Conduct: http://python.org/psf/codeofconduct/


[Python-ideas] Re: str.isfloat()

2020-12-27 Thread 2QdxY4RzWzUUiLuE
On 2020-12-27 at 19:55:39 -0300,
"Joao S. O. Bueno"  wrote:

> I tried to make clear this should be in addition to that - But yes, I
> failed to mention in my message that I think such a function would
> mostly benefit beginners learning around with "input" and "print" - it
> is painful to suddenly have to tour the students on several other
> concepts just to get a correct user-inputed number. (OTOH, yes, for
> code on this level, one normally won't be concerned if the program
> user will be typing "1.02e2" on the `input` prompt).

OTOH, learning that translating a user-entered string to a floating
point number is not as simple as it sounds is a great lesson.  Please
don't teach beginners that handling user input (let alone floating point
arithmetic) is easy and/or foolproof.  Start with letting the program
fail when the input is invalid, teach them to isolate input validation
into its own function(s), and introduce try/except as one method of
control flow in a validation function.
___
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/GKMQV75D5PXLTC6SE2V7YFNHLKKPVN52/
Code of Conduct: http://python.org/psf/codeofconduct/


[Python-ideas] Re: built in to clear terminal

2020-12-26 Thread 2QdxY4RzWzUUiLuE
On 2020-12-27 at 13:24:34 +1100,
Steven D'Aprano  wrote:

> But the ctrl-L trick has no discoverability. It took me close to
> twenty years of using Linux before I discovered it, and I still don't
> remember to use it when I need it.

The first time a sysadmin added readline to one of our work computers,
it took me *minutes* to be stunned that my terminal window was being
cleared for no reason.  It took me longer to discover that the reason
was accidental Ctrl-L's (no doubt an off-by-one error trying to press
Ctrl-K), and way longer to figure out what piece of [software] was
intercepting that keystroke and clearning my screen.  The very first
line in my .inputrc file is as follows:

Control-L: redraw-current-line

> Beginners and casual users aren't going to know ctrl-L, or stumble
> across it through experimentation. People like me aren't going to
> remember to use it. For interactive use, os.clear is barely any
> better.

Technically, I was a professional, and I stumbled on it through fat
fingers and not knowing that readline had been installed and did
horrible things like that out of the box.  And then I disabled it as
quickly as I could figure out how.

Call me 0 (because I don't care enough to be +0 or -0) on the whole
thing, as long as it's spelled with more than one keystroke (to prevent
accidental invocation).
___
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/TPJFVV3ZI2IBCYL6DABKSQMGSQQVSYNF/
Code of Conduct: http://python.org/psf/codeofconduct/


[Python-ideas] Re: Move semantics

2020-11-27 Thread 2QdxY4RzWzUUiLuE
On 2020-11-27 at 14:32:11 +0100,
Antoine Pitrou  wrote:

> On Fri, 27 Nov 2020 07:32:17 -0500
> 2qdxy4rzwzuui...@potatochowder.com
> wrote:
> > 
> > I come from old(er) school (1980s, 1990s) embedded systems, and who
> > "owns" a particular mutable data structure and how/where it gets mutated
> > always came up long before we wrote any code.  No, I'm not claiming that
> > pre-ansi C and assembler are more productive or less runtime error prone
> > than newer languages, but is this feature only necessary because
> > "modern" software development no longer includes a design phase or
> > adequate documentation?
> 
> "Modern" software development is just like older software development
> in that regard: sometimes it includes a design phase and/or adequate
> (i.e. sufficiently precise) documentation, sometimes it doesn't.

Fair enough.  :-)

(In my case, memory was a scarce resource and we emphasized
documentation about it.)

> > Memory management implementation details is a long way from
> > executable pseudo code.  (30 years is a long time, too.)
> 
> This isn't really about memory management, though.

It reminds me of "use after free" errors.  Whenever Rust comes up, I
think of memory management.  Call me biased.  :-)

Also, in Serhiy's example,¹ if Client.send "moved" headers, then it
could also free the memory associated with that dictionary at the end
(although I realize that that may not always be the case).  Many times,
freeing memory sooner is better.

¹ 
https://mail.python.org/archives/list/python-ideas@python.org/message/VBB3XGUNTF75J6O5PSTYYRSNTRMQP74H
___
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/PJDJZECOUA4QUSYBWVOYNUDEA7KUSU26/
Code of Conduct: http://python.org/psf/codeofconduct/


[Python-ideas] Re: Move semantics

2020-11-27 Thread 2QdxY4RzWzUUiLuE
On 2020-11-27 at 10:38:06 +0200,
Serhiy Storchaka  wrote:

> 26.11.20 19:07, Guido van Rossum пише:
> > This reminds me of something in C++. Does it exist in other languages?

> Indeed, this is a term from C++. In older C++ you could pass argument
> by value, which makes a copy, and by reference, which is equivalent to
> passing a pointer by value plus syntax sugar. Passing by value may be
> inefficient if you need to copy more than several bytes. Passing by
> reference has other problems. It was a source of errors, so passing
> object created on stack by non-constant reference was forbidden. If
> you need to modify argument passed by constant reference in the
> function you need to create a copy, even if the object is never used
> after passing to the function (like in foo(bar()), the returned value
> of bar() cannot be used outside of foo(), so it could be allow to
> modify it). To resolve this problem the move semantic was introduced.
> 
> > Do you have a more realistic example where this would catch an
> > important type error?
> 
> I seen and used the following example (with variations) multiple times:
> 
> class Client:
> def send(self, msg, token, headers=None):
> if headers is None:
> headers = {}
> # headers = headers.copy()
> headers["Authorization"] = f"Bearer {token}"
> headers["Content-Type"] = "text/plain"
> headers["X-Hash"] = md5sum(msg.encode())
> with self.request('POST', self.url, headers=headers,
> data=msg) as resp:
> ...
> 
> client.send('Hello!', mytoken, headers={'X-Type': 'Spam'})
> 
> The function sets some standard headers, but you can pass also
> additional headers. If you only pass a just created dictionary, the
> function can modify it in-place because its value is not used outside.
> But if you create the dict once and use it in other places, modifying
> it inside the function is a non-desired effect. You need to make a
> copy in the function just because you don't know how it will be used
> in the user code. If you document that the argument cannot be used
> after calling the function and add some marks for static type
> checking, you could avoid copying.
> 
> Personally I think Python has a little need in such feature. Copied
> dicts and lists are usually small, and it adds not much overhead in
> comparison with other overhead that Python does have. And if you need
> to pass and modify a large collection, documenting this should be
> enough.

For an opposing point of view, why not write that method as follows:

class Client:
def send(self, msg, token, additional_headers=None):
headers = {"Authorization" : f"Bearer {token}",
   "Content-Type" : "text/plain",
   "X-Hash" : md5sum(msg.encode()),
   **(additional_headers or {})}
...

Then I only modify a just created dictionary and never some dictionary
of questionable origin and/or future.  Obviously, there's a difference
in behavior if additional_headers contains Authorization or X-Hash or
Content-Type, but I can't say which behavior is correct without more
context, and I can't say which is more efficient (in time or in space)
without knowing how often additional_headers is not None or how big it
usually is.

I come from old(er) school (1980s, 1990s) embedded systems, and who
"owns" a particular mutable data structure and how/where it gets mutated
always came up long before we wrote any code.  No, I'm not claiming that
pre-ansi C and assembler are more productive or less runtime error prone
than newer languages, but is this feature only necessary because
"modern" software development no longer includes a design phase or
adequate documentation?  I understand the advantages of automated
systems (the compiler and/or static analyzer) over manual ones (code
review, documentation, writing unit tests), but ISTM that if you're
writing code and don't know whether or not you can mutate a given
dictionary, or you're calling a function and don't know whether or not
that function might mutate that dictionary, then the battle is already
lost.

Memory management implementation details is a long way from executable
pseudo code.  (30 years is a long time, 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/O5W3WB2RVQ222CYTKNBVL7ZLFM6BP24H/
Code of Conduct: http://python.org/psf/codeofconduct/


[Python-ideas] Re: PEP 634-636: Mapping patterns and extra keys

2020-11-15 Thread 2QdxY4RzWzUUiLuE
On 2020-11-15 at 19:11:15 +1100,
Steven D'Aprano  wrote:

> On Sat, Nov 14, 2020 at 10:17:34PM -0800, Guido van Rossum wrote:
> 
> > It’s a usability issue; mappings are used quite differently than sequences.
> > Compare to class patterns rather than sequence patterns.
> 
> I'm keeping an open mind on this question, but I think David is right
> to raise it. I think that most people are going to see this as dict
> matching as "ignoring errors by default" and going against the Zen of
> Python, and I expect that we'll be answering questions about it for
> years to come.
> 
> "Why did my match statement match the wrong case?"
> 
> Naively, I too would expect that dicts should only match if the keys 
> match with no left overs, and I would like to see the choice to ignore 
> left overs justified in the PEP.
> 
> It would be good if the PEP gave a survey of the practical experience of 
> other languages with pattern matching:
> 
> - are there languages which require an exact match, with no left over 
>   keys? what issues, if any, do users have with that choice?
> 
> - which languages ignore extra keys? do users of those languages 
>   consider this feature a bug, a wart, or a feature?

In Erlang, "mappings" tend to be generalized collections of (key, value)
pairs in which the keys are not nailed down at design time, or the keys
evolve over time (think about adding a new field to an existing
message).  Pattern matching ignores extra keys, so that old code can
continue to handle the messages it knows how to handle and simply ignore
data it doesn't know about (yes, you have to think carefully about
extending messages in this way, but it has worked well over decades).
This is definitely a feature.

Also in Erlang, "records" are very similar to Python's named tuples.
Pattern matching on records also ignores extra keys, so that I can match
records that meet certain criteria and not have to list every attribute
in every pattern.

IMO, ignoring extra keys allows for extensibility when you don't always
have control over which versions of which code is actually running
(which is the case in the typical distributed system).  Not ignoring
extra keys may work better inside a monolithic application where all the
data comes from within or is already parsed/decoded.

IMO, this is going to come down to your use case (I'm *shocked*).

If I receive HTML/XML/JSON/TCP/whatever messages, and I want to use
pattern matching to decode or dispatch on the message type (e.g., login,
logout, attack, connect), then *not* having to write **rest on every
pattern reduces clutter.

But if I have to handle 2D points separately from 3D points, then a more
strict matching (i.e., not ignoring extra keys) relieves me of having to
think about which case is more or less specific, and may be easier for
beginners to use.  (IMO, making things easier for beginners is only a
means to an end.  If making things easier for beginners makes things
harder for experts, then don't do it.  But I'm not in charge around
here.)

As an analogy, when you write a command line utility, do you accept or
reject extraneous command line arguments?  Is "spam --version ham eggs"
the same as "spam --version"?  I'm going to guess that it depends on
your personality and your background and not anything else inside the
utility (note that your choice of command line parser also depends on
your personality and your backround...).  IOW, the answer to the
question of ignoring extra keys is going to aggravate half the users and
half the use cases no matter what.
___
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/B6BPSIH42FVCXUVGX37RGJZAM2ONYGDI/
Code of Conduct: http://python.org/psf/codeofconduct/


[Python-ideas] Re: execute function on iterator items without changing or consuming iterator

2020-10-25 Thread 2QdxY4RzWzUUiLuE
On 2020-10-25 at 16:34:14 +,
George Harding  wrote:

> some_iter = map(lambda x: x if print(x) else x, some_iter)
> 
> The tuple has a ~50% overhead, the case statement ~15%, compared to the
> generator.

def print_first(x):
print(x)
return x
new_iter = map(print_first, some_iter)

No extranous tuple, no extranous case stament.  Newlines are cheap these
days.  The call to print, however, is possibly unbounded in time and
space.

If you really want to go overboard, put something like the following
peeker function into your personal toolbox (untested):

def peeker(function):
def peeker(x):
function(x)
return x
return peeker

And use it like this:

new_iter = map(peeker(print), some_iter)
___
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/RG2ZQD5NNU2BKVTC2AZGSQNVZA2CV2UJ/
Code of Conduct: http://python.org/psf/codeofconduct/


[Python-ideas] Re: TextIOWrapper support for null-terminated lines

2020-10-24 Thread 2QdxY4RzWzUUiLuE
On 2020-10-24 at 12:29:01 -0400,
Brian Allen Vanderburg II via Python-ideas  wrote:

> ... Find can output it's filenames in null-terminated lines since it
> is possible to have newlines in a filename(yuck) ...

Spaces in filenames are just as bad, and much more common:

$ touch 'foo bar'
$ find . -name 'foo bar'
./foo bar
$ find . -name 'foo bar' -print | xargs ls -l
ls: cannot access './foo': No such file or directory
ls: cannot access 'bar': No such file or directory
$ find . -name 'foo bar' -print0 | xargs -0 ls -l
-rw-r--r-- 1 dan dan 0 Oct 24 13:31 './foo bar'
$ rm 'foo bar'
___
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/F5UX5CL7YQIHEX3MP5R4GUVHIXCS5VQP/
Code of Conduct: http://python.org/psf/codeofconduct/


[Python-ideas] Re: Call a function at invocation

2020-10-22 Thread 2QdxY4RzWzUUiLuE
On 2020-10-22 at 20:04:14 -0400,
Michael Smith  wrote:

> 1. Being able to call two different functions from the same module. (AND)
> 2. Being able to call some functions that exist today without modification
> or rearrangement. (AND)
> 3. Being able to invoke these things from python without installing a
> module from pip.
> 
> There are solutions that do some of these, but nothing that does them all.
> I think it's surprising that the python makers have found worthwhile three
> different solutions for invoking modules, but this list so far has seen
> little value in invoking a function.

The following module meets your three criteria:

%% begin Python code
def f():
print("This is f.")

def g():
print("This is g.")

h = 'hello'

i = lambda x: print(f"Hello, {x}.")

if __name__ == '__main__':
import sys

try:
function_name, *arguments = sys.argv[1:]
except (IndexError, ValueError):
print('missing function name')
sys.exit(1)

function = sys.modules[__name__].__dict__.get(function_name)
if not function or not callable(function):
print('cannot find or cannot call', function_name)
sys.exit(1)

function(*arguments)
%% end Python code

It's not polished, and it only handles positional string parameters, but
it should be fairly self-explanatory.  The __name__ == '__main__' idiom
allows the module to be imported by other modules without incident.

IMO, at best, it might be the beginning of a recipe somewhere rather
than being included in the standard library.  I agree with David Mertz
that as soon as it gets more complex, every application is going to want
something a little different.

> It would definitely be more empowering to be able to describe the
> command line args to such an invocation using the args to the
> function.

Such enhancements are left as an exercise to the interested reader.

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


[Python-ideas] Re: Regular Expression | re - Support String List Input Type List[str]

2020-09-28 Thread 2QdxY4RzWzUUiLuE
On 2020-09-28 at 23:10:24 -,
Giang Le  wrote:

> I would like to propose an idea for the regular expression module
> re.search(Pattern, Input) to support List[str] input type.

> So it will return a matched object list if the input is a string
> list. Otherwise, it will return a normal matched object, if the input
> is a normal string

How would that change be better than a new function:

def regex_search_list(regex, pattern, list_of_inputs):
[regex.search(pattern, input) for input in list_of_inputs]

(or possibly an equivalent method of regexen)?
___
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/QSOAHKIKTJMYEWT24L6NTYIXSFLPT5LP/
Code of Conduct: http://python.org/psf/codeofconduct/


[Python-ideas] Re: Suggestion: annotated exceptions

2020-09-25 Thread 2QdxY4RzWzUUiLuE
On 2020-09-25 at 13:44:36 +0100,
Samuel Colvin  wrote:

> 2. We should have some easy way to say "let this error propagate",
> rust uses very nice question mark at the end of a line syntax, python
> could use something similar one day, until then a magic comment,
> wrapper function or context function could be used.

In Python, the way to say "let this error propagate" is not to say
anything at all.  y = f(x) says (and very concisely, I might add) "if f
raises an exception, or propagates some exception from some other place,
then let that exception propagate."
___
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/25E6NBXYXZF5A5UGCXOOG6QZZ5NXH365/
Code of Conduct: http://python.org/psf/codeofconduct/


[Python-ideas] Re: Minor contributions to PEPs (Was: PEP 637 - support for indexing with keyword arguments)

2020-09-23 Thread 2QdxY4RzWzUUiLuE
On 2020-09-23 at 23:28:11 +0100,
Henk-Jaap Wagenaar  wrote:

> >>> a[3]   # returns the fourth element of a
> 
> has the comment unfinished. I guess it should say list or something
> similar.]

Yes, I agree:  it looks like it's broken, but it's okay.  a[3] returns
the fourth element of a sequence named "a."  If the sequence were named
something_descriptive, then something_descriptive[3] returns the fourth
element of a sequence named "something_descriptive."
___
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/Z5JPXAIDPBMTNREXDNEX54N7J3PZ7OLJ/
Code of Conduct: http://python.org/psf/codeofconduct/


[Python-ideas] Re: Curious : Why staticmethod if classmethods can do everything a static method can?

2020-09-12 Thread 2QdxY4RzWzUUiLuE
On 2020-09-12 at 14:07:57 +1000,
Cameron Simpson  wrote:

> Dan, I should preface this by saying I don't substantially disagree
> with you, I just work differently and want to show how and why.

> The beauty here is that you have the same pattern of
> classname.transcribe_value(value) to use whatever binary format you
> want.  And that's a static method because it doesn't need a class or
> instance for context - it just transcribes the data.

> > IMO, m.f has less cognitive load than m.X.f, at their definitions
> > and at call sites.  Full disclosure:  I consider most of Object
> > Oriented Programming to be extraneous cognitive noise.
> 
> Whereas I use OOP a lot. Hugely.

Maybe what I needed early on was a good example of a large, well
designed OO piece of software to use as a role model.  But the large
non-OO systems seemed to be much better (in any number of ways, and
please don't mistake me for implying that all non-OO systems are good)
than the large OO ones.  My habits and opinions are certainly shaped
from my experience.

Namespaces are one honking great idea.  I¹ have modules, you¹ have
classes.  We¹ build software.  Vive la différence!  :-)

> > In other languages (*cough* Java *cough*), there are no functions
> > outside of classes, and static methods fill that role.
> 
> Aye. I agree that is an example where static methods exist for
> language definition reasons instead of functionality. OTOH, the
> language design is deliberately like that to force encapsulation as a
> universal approach, which has its own benefits in terms of side effect
> limitation and code grouping, so there's an ulterior purpose there.

Encapsulation is a good thing, OO or otherwise.  Unless, of course, the
code is behind an HTTP server and I can't see it from the outside.

¹ in the generic sense of the pronoun

-- 
“Whoever undertakes to set himself up as a
judge of Truth and Knowledge is shipwrecked
by the laughter of the gods.” – Albert Einstein
Dan Sommers, http://www.tombstonezero.net/dan
___
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/AGAZ6OEKE2TSNEMSMNCSCSS3EA5G3HIQ/
Code of Conduct: http://python.org/psf/codeofconduct/


[Python-ideas] Re: Curious : Why staticmethod if classmethods can do everything a static method can?

2020-09-11 Thread 2QdxY4RzWzUUiLuE
On 2020-09-12 at 09:57:10 +1000,
Cameron Simpson  wrote:

> So, consider:
> 
> @classmethod
> def func(cls, foo):
> print(foo)
> 
> A linter will warn you that "cls" is unused. With a static method:
> 
> @staticmethod
> def func(foo):
> print(foo)
> 
> a linter will be happy.
> 
> Think of @classmethod and @staticmethod as ways to write "clean" 
> functions with no extraneous cognitive noise.

I concur with all of Cameron's technical details and explanations.

But no extraneous cognitive noise?  By definition, methods appear inside
a class definition, and then I have to process the @staticmethod
decorator.  Effectively, the decorator "cancels" the class method status
of the function.  I can accomplish the same thing with clean
module-level function, modulo the specific namespace in which the
function is created.

So, in a module m:

class X:
@staticmethod
def f(x):
print(x)

and

def f(x):
print(x)

m.X.f and m.f are interchangeable.  IMO, m.f has less cognitive load
than m.X.f, at their definitions and at call sites.  Full disclosure:  I
consider most of Object Oriented Programming to be extraneous cognitive
noise.

In other languages (*cough* Java *cough*), there are no functions
outside of classes, and static methods fill that role.
___
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/3PEG35ADEQIEMXLKBCDGBFSM2IO5NS4V/
Code of Conduct: http://python.org/psf/codeofconduct/


[Python-ideas] Re: argparse.py in version 3.8.2 Action=Custom ActionClass needs an option to have methods

2020-09-10 Thread 2QdxY4RzWzUUiLuE
On 2020-09-10 at 11:45:37 -,
rangap...@gmail.com wrote:

> Got the argparse() in version 3.8.2 and above the action=CusotmClass
> can have a user defined custom subclass and override the functionality
> in the def __init__() method. Along with this can we also have a built
> in custom method/methods that I can define under this custom Class, so
> that instead of calling the Action itself I have the option of calling
> the Action.Method() during the add_argument defintition.

Why do you want that?  What, exactly, could you do (or do better) with
another method that you can't do with another class's __init__?
___
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/XYHLMUASGUC3BAGHUKL5B5XQSHLGJU3L/
Code of Conduct: http://python.org/psf/codeofconduct/


[Python-ideas] Re: What about having a .get(index, default) method for arrays like we have for dicts?

2020-08-28 Thread 2QdxY4RzWzUUiLuE
On 2020-08-28 at 08:41:04 -0400,
Regarding "[Python-ideas] Re: What about having a .get(index, default) method 
for arrays like we have for dicts?,"
Richard Damon  wrote:

> On 8/28/20 8:24 AM, David Mertz wrote:
> >
> > As a side note, I don't really get why everyone else thinks a
> > try/except is the most natural approach while a ternary seems more
> > obvious to me for this situation.  But it kinda connects to me liking
> > list.get() better, I think... since "not enough items" doesn't seem as
> > *exceptional* to me as it apparently does to some others.
> 
> try/except is specifically looking for the error in question, index out
> of bounds. The ternary requires restating in other words the bounds limit.
> 
> For instance, for a list of N items, the allowable subscripts are -N to
> N-1, and the sample ternary is only checking for the upper bound, not
> the lower, so fails an too small of an index (maybe you know you are
> only using positive indexes?) Missing this won't happen with try/except.

Without more context, I've lost the forest for the trees.  There are
multiple ways to do this, and the "best" way likely depends on the
context and not the readability, writability, maintainability, or
expressivity of that exact line of code.

Where did the index come from?  How/when/where was the list constructed?
Could this "problem" have been recognized and/or addressed sooner?
What, exactly, are the conditions that cause the index being out of
bounds at this point in the logic, and what are the semantics now that
it's happened?  Given the preceding logic, is an index that's too small
(i.e. mathematically less than the opposite of the lenght of the list)
even possible?

I didn't find either of the examples (one using an if/else ternary and
one using a hypothetical list.get method) particulary easy to read or
particularly indicative of an obvious use case.  And at that point,
re-writing one [presumably correct] line of code into another won't make
or break anything.
___
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/BG2P6BCSDDANXU2XR4XU75O2AOLRVHM5/
Code of Conduct: http://python.org/psf/codeofconduct/


[Python-ideas] Re: use type hints and slices to specify a valid numerical range, example: `Angle = int[0:361]`

2020-08-08 Thread 2QdxY4RzWzUUiLuE
On 2020-08-08 at 18:53:36 -0400,
David Mertz  wrote:

> ... my discovery was that "LLVM figures out Gauss' simplification and
> does it in constant time no matter the N.  After that I looked at the
> LLVM bytecode to see, "Yup, it does."  The optimizer is pretty smart
> about variations in writing the code in some slightly different ways,
> but I don't know exactly what it would take to fool it into missing
> the optimization.

I was trying to learn something about 80X86 (where X might have been the
empty string) assembly language by examing the output from Microsoft's C
compiler.  It made the same optimization, thus thwarting that particular
effort, and that was probably 35 years ago now.  For small N, it's
really just constant folding, loop unrolling, and peephole
optimizations; these days, "small N" might be a billion or 2**32.

The point isn't that it't not suprising, of course, but that it's not
something new.
___
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/J6YDNJTMWNWXDVR5JPM4WSOVGK6YRMHE/
Code of Conduct: http://python.org/psf/codeofconduct/


[Python-ideas] Re: Changing item dunder method signatures to utilize positional arguments (open thread)

2020-08-05 Thread 2QdxY4RzWzUUiLuE
On 2020-08-04 at 10:58:51 -0400,
Todd  wrote:

> My main issue with this is that, in my opinion, dunders are not
> something a beginner should be messing with anyway.  By the time
> someone is experienced enough to start working on this, they are also
> experienced enough to understand that special cases like this exist
> for historical reasons.

Ouch.

Who am I to tell beginners what they should and shouldn't be messing
with, and in what order?  IMNSHO, history (let alone understanding it)
comes *way* after writing a few dunders, even if you don't count
__init__ as a dunder.

Special cases aren't special enough to break the rules.
___
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/VVXICTWV2EXQOHZTQ5KVADXG5ACR3CDA/
Code of Conduct: http://python.org/psf/codeofconduct/


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

2020-07-29 Thread 2QdxY4RzWzUUiLuE
On 2020-07-29 at 07:09:05 -0700,
Guido van Rossum  wrote:

> I honestly and strongly believe that we should do nothing here. Python
> thrives because it is relatively simple. Adding new syntax to deal
> with looping special cases makes it less simple, and encourages a bad
> coding style (nested loops, multiple breaks...).

I was about to go off on another Get Off My Lawn rant, so thank you for
putting this so succintly and so politely.  :-)

If I end up with more than one flag controlling my search loop, then
it's time to break (pun intended) the logic into smaller/simpler pieces
rather than to look for a more complicated language construct.
___
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/V66EY5LEXXTBVYB55NQJXSQNTXFXBVC5/
Code of Conduct: http://python.org/psf/codeofconduct/


[Python-ideas] Re: Thoughts about implementing object-compare in unittest package?

2020-07-29 Thread 2QdxY4RzWzUUiLuE
On 2020-07-29 at 14:26:25 +0900,
"Stephen J. Turnbull"  wrote:

> 2qdxy4rzwzuui...@potatochowder.com writes:
> 
>  > in order to foil suck attacks.
> 
> Typo of the Year candidate!  (It was a typo, right?)

Call it a Freudian slip of the fingers.
___
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/GS6TDRETAPG2WRLMNDQFZORSYC2OID2A/
Code of Conduct: http://python.org/psf/codeofconduct/


[Python-ideas] Re: Thoughts about implementing object-compare in unittest package?

2020-07-28 Thread 2QdxY4RzWzUUiLuE
On 2020-07-28 at 15:58:58 -0700,
Christopher Barker  wrote:

> But a dict always has a LOT fewer buckets than possible hash values,
> so clashes within a bucket are not so rare, so equality needs to be
> checked always -- which is what I was missing.

> And while it wouldn't break anything, having a bunch of non-equal
> objects produce the same hash wouldn't break anything, it would break
> the O(1) performance of dicts.

> Have I got that right?

Yes.

Breaking O(1) performance was actually the root of possible Denial of
Service attacks:  if an attacker knows the algorithms, that attacker
could specifically create keys (e.g., user names) whose hash values are
the same, and then searching a dict degenerates to O(N), and then your
server falls to its knees.  At some point, Python added some
randomization to the way dictionaries work in order to foil suck
attacks.
___
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/TJCGVDGZWP4LXG44P4Z34BPMZRI3ODY3/
Code of Conduct: http://python.org/psf/codeofconduct/


[Python-ideas] Re: default parameter in fuctions to clean up flow

2020-07-28 Thread 2QdxY4RzWzUUiLuE
On 2020-07-28 at 11:04:25 -0300,
"Joao S. O. Bueno"  wrote:

> Anyway, that is feasible via a decorator.
> Since it can't be done the wya you are proposing as is, since
> having a function as a default argument is valid Python
> (and the function is not called) - and
> having new syntax for this would be more cumbersome
> than using  a decorator, I think that closes the gap.
> 
> If such a decorator would be useful enough to cut it into the
> stlib, is another question though - I'd probably find it occasionally
>  useful myself, but even so, I am +0 on this -
> it is not like
> 
> ```
> if parameter is sentinel:
> parameter = factory()
> ```
> would be too much to type.
> 
> On a second thought - proper documenting and giving visibility
> to a decorator like this could make it be used in patterns like
> ```
> @factoryargs
> def myfunction(a, b, c=list):
> pass
> ```
> and we could see a drop in the newcomers to Python
> putting a `[]` as default argument.

That's great, until I have something like this:

@factoryargs
def myfunction(a, b, c=list, d=3.4):
pass

Is c a factory?  Is d a factory?

> Ok - I just convinced myself - I am +1 for such a decorator now.

I don't mean to be a wet blanket, but what's wrong with a helper
function?

def time_diff_from_now(target_time):
return time_diff(target_time, datetime.datetime.now())

def time_diff(target_time, curr_time):
return curr_time - target_time

No decorators, no new syntax, explicit at the calling sites.

> On Mon, 27 Jul 2020 at 20:42, Richard Damon 
> wrote:
> 
> > On 7/27/20 10:01 AM, Peter Moore wrote:
> > > I have had a long standing unanswered question on on stackoverflow: is
> > it possible to pass a function to a default parameter so that you could do
> > in essence things like this.
> > >
> > > def time_diff(target_time,  curr_time= lambda : datetime.now() ):
> > > return curr_time - target_time
> > >
> > > this would be an syntactical improvement over this style where you have
> > if statement to initialize a missing parameter.
> > >
> > > def time_diff(target_time, curr_time=None):
> > >if curr_time == None:
> > >   curr_time = datetime.datetime.now()
> > >return  curr_time - target_time
> > I will point out that you CAN pass a function as the default value of a
> > function parameter, and it means that the parameter will be bound to the
> > function itself, so it becomes a callable (so doesn't help you in your
> > case). But this does become an impediment to trying to define it this
> > way, you need somehow to distinguish between the function itself being
> > the default value, or some magically invocation of the function at each
> > call.
> >
> > --
> > Richard Damon
> > ___
> > 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/64ZTCJWJO74KD2EFUOSICOPT6XTSBO2R/
> > 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/EGFSGULHXBRT2HNEDRN4GJ36DQUSR3RX/
> Code of Conduct: http://python.org/psf/codeofconduct/


-- 
“Whoever undertakes to set himself up as a
judge of Truth and Knowledge is shipwrecked
by the laughter of the gods.” – Albert Einstein
Dan Sommers, http://www.tombstonezero.net/dan
___
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/NUFVFDFI7QY67QVFIFS4Y7CRGEGCWRBF/
Code of Conduct: http://python.org/psf/codeofconduct/


[Python-ideas] Re: Faster object representation for UIs

2020-07-24 Thread 2QdxY4RzWzUUiLuE
On 2020-07-24 at 15:10:46 -,
Gábor Bernát  wrote:

> ... Sometimes users have many really large objects, and when debugger
> is trying to show them in Variables View (=show their string
> representation) it can takes a lot of time. We do some tricks, but
> they not always work. It would be really-really cool to have parameter
> in repr, which defines max number of symbols we want to evaluate
> during repr for this object.

> Maybe repr is not the best here, because that should be interpreter
> meaningful, but instead the __str__ method that's better for
> this. Maybe we could pass in an optional limit argument to these
> methods, so that the user can decide what to print depending on how
> many characters he has left?

> Any takes, better ideas how we could help this problem?

Use the pretty printer/formatter.¹

Start with a small depth and let the user adjust it.

¹ https://docs.python.org/3/library/pprint.html
___
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/PTYLW3NVCVWJIGXKN5DQQBAWHEKQ23Z3/
Code of Conduct: http://python.org/psf/codeofconduct/


[Python-ideas] Re: Add builtin function for min(max())

2020-07-04 Thread 2QdxY4RzWzUUiLuE
On 2020-07-05 at 12:18:54 +0900,
"Stephen J. Turnbull"  wrote:

> Which suggests the question: Is there a commonly used equivalent for
> complex numbers?

How would that work?  Complex numbers are unordered, but I suspect that
you know that.

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


[Python-ideas] Re: Add builtin function for min(max())

2020-07-04 Thread 2QdxY4RzWzUUiLuE
On 2020-07-04 at 20:33:36 +0100,
Regarding "[Python-ideas] Re: Add builtin function for min(max()),"
Henk-Jaap Wagenaar  wrote:

> On Sat, 4 Jul 2020 at 19:58, Christopher Barker  wrote:
> 
> > Hmm.
> >
> >
> > Since NaN is neither greater than nor less that anything, it seems the
> > only correct answer to any
> > Min,max,clamp involving a NaN is NaN.
> >
> >
> Simplifying the signature, in Python we have:
> 
> def min(*iterable):
> iterator = iter(iterable)
> minimum = next(iterable)
> for item in iterator:
> if item < minimum:
> minimum = item
> return minimum
> 
> Due to this, min(0, float('nan')) == 0 and same for max. I would hence
> expect clamp to behave similarly.

Yuck:  We also have min(float('nan'), 0) == float('nan').

I'm not sure what I'd expect a hypothetical clamp function to do.
Someone with actual use cases will have more insight.
___
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/K4STFFKEJG7RTF2UTGWI3ILZ3UVQMOPO/
Code of Conduct: http://python.org/psf/codeofconduct/


Re: [Python-ideas] Why is design-by-contracts not widely

2018-09-28 Thread 2qdxy4rzwzuuilue



On 9/28/18 12:45 PM, Steven D'Aprano wrote:

On Tue, Sep 25, 2018 at 09:59:53PM +1000, Hugh Fisher wrote:


C and Python (currently) are known as simple languages.


o_O

That's a usage of "simple" I haven't come across before. Especially in
the case of C, which is a minefield of *intentionally* underspecified
behaviour which makes it near to impossible for the developer to tell
what a piece of syntactically legal C code will actually do in practice.


s/C/Python/

s/underspecified/dynamic/

;-)


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