RE: Which more Pythonic - self.__class__ or type(self)?

2023-03-04 Thread avi.e.gross
>>> I think you are over-thinking this, Avi :)

Is overthinking the pythonic way or did I develop such a habit from some
other language?

More seriously, I find in myself that I generally do not overthink. I
overtalk and sort of overwrite, so for now, I think I will drop out of this
possibly non-pythonic topic and go read another book or a few hundred so
when it comes up again ...

-Original Message-
From: Python-list  On
Behalf Of Thomas Passin
Sent: Saturday, March 4, 2023 5:04 PM
To: python-list@python.org
Subject: Re: Which more Pythonic - self.__class__ or type(self)?

On 3/4/2023 4:18 PM, avi.e.gr...@gmail.com wrote:
> I don't know, Thomas. For some simple programs, there is some evolutionary
> benefit by starting with what you know and gradually growing from there.
He
> first time you need to do something that seems to need a loop in python,
> there are loops to choose from.
> 
> But as noted in a recent discussion, things are NOT NECESSARILY the same
> even with something that simple. Did your previous languages retain
> something like the loop variable outside the loop? What are your new
scoping
> rules? Do you really want to keep using global variables, and so on.
> 
> And, another biggie is people who just don't seem aware of what comes
easily
> in the new language. I have seen people from primitive environments set up
> programs with multiple arrays they process the hard way instead of using
> some forms of structure like a named tuple or class arranged in lists or
use
> a multidimensional numpy/pandas kind of data structure.
> 
> So ignoring the word pythonic as too specific, is there a way to say that
> something is the way your current language supports more naturally?
> 
> Yes, there are sort of fingerprints in how people write. Take the python
> concept of truthy and how some people will still typically add a test for
> equality with True. That may not be pythonic to some but is there much
harm
> in being explicit so anyone reading the code better understands what it
doe?
> 
> I have to wonder what others make of my code as my style is likely to be
> considered closer to "eclectic" as I came to python late and found an
> expanding language with way too many ways to do anything and can choose.
But
> I claim that too is pythonic!

I think you are over-thinking this, Avi :)

> 
> -Original Message-
> From: Python-list 
On
> Behalf Of Thomas Passin
> Sent: Saturday, March 4, 2023 1:09 PM
> To: python-list@python.org
> Subject: Re: Which more Pythonic - self.__class__ or type(self)?
> 
> On 3/4/2023 2:47 AM, Peter J. Holzer wrote:
>> Even before Python existed there was the adage "a real programmer
>> can write FORTRAN in any language", indicating that idiomatic usage of a
>> language is not governed by syntax and library alone, but there is a
>> cultural element: People writing code in a specific language also read
>> code by other people in that language, so they start imitating each
>> other, just like speakers of natural languages imitate each other.
>> Someone coming from another language will often write code which is
>> correct but un-idiomatic, and you can often guess which language they
>> come from (they are "writing FORTRAN in Python").
> 
> What Peter didn't say is that this statement is usually used in a
> disparaging sense.  It tends to imply that a person can write (or is
> writing) awkward or inappropriate code anywhere.
> 

-- 
https://mail.python.org/mailman/listinfo/python-list

-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Which more Pythonic - self.__class__ or type(self)?

2023-03-04 Thread Weatherby,Gerard
Nope. No consensus.

I’d use self.__class__ . Seems more explicit and direct to me.

From: Python-list  on 
behalf of Ian Pilcher 
Date: Thursday, March 2, 2023 at 4:17 PM
To: python-list@python.org 
Subject: Which more Pythonic - self.__class__ or type(self)?
*** Attention: This is an external email. Use caution responding, opening 
attachments or clicking on links. ***

Seems like an FAQ, and I've found a few things on StackOverflow that
discuss the technical differences in edge cases, but I haven't found
anything that talks about which form is considered to be more Pythonic
in those situations where there's no functional difference.

Is there any consensus?

--

Google  Where SkyNet meets Idiocracy

--
https://urldefense.com/v3/__https://mail.python.org/mailman/listinfo/python-list__;!!Cn_UX_p3!iK8xBvLrRYfAR0KdkDmK-VwyL0ZZUjFJZ9Tj4j-IBz3_B1M0iQFFE3dV-f4bV41DQwnFL_wC2xWRni-0pMUqAw$<https://urldefense.com/v3/__https:/mail.python.org/mailman/listinfo/python-list__;!!Cn_UX_p3!iK8xBvLrRYfAR0KdkDmK-VwyL0ZZUjFJZ9Tj4j-IBz3_B1M0iQFFE3dV-f4bV41DQwnFL_wC2xWRni-0pMUqAw$>
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Which more Pythonic - self.__class__ or type(self)?

2023-03-04 Thread Thomas Passin

On 3/4/2023 4:18 PM, avi.e.gr...@gmail.com wrote:

I don't know, Thomas. For some simple programs, there is some evolutionary
benefit by starting with what you know and gradually growing from there. He
first time you need to do something that seems to need a loop in python,
there are loops to choose from.

But as noted in a recent discussion, things are NOT NECESSARILY the same
even with something that simple. Did your previous languages retain
something like the loop variable outside the loop? What are your new scoping
rules? Do you really want to keep using global variables, and so on.

And, another biggie is people who just don't seem aware of what comes easily
in the new language. I have seen people from primitive environments set up
programs with multiple arrays they process the hard way instead of using
some forms of structure like a named tuple or class arranged in lists or use
a multidimensional numpy/pandas kind of data structure.

So ignoring the word pythonic as too specific, is there a way to say that
something is the way your current language supports more naturally?

Yes, there are sort of fingerprints in how people write. Take the python
concept of truthy and how some people will still typically add a test for
equality with True. That may not be pythonic to some but is there much harm
in being explicit so anyone reading the code better understands what it doe?

I have to wonder what others make of my code as my style is likely to be
considered closer to "eclectic" as I came to python late and found an
expanding language with way too many ways to do anything and can choose. But
I claim that too is pythonic!


I think you are over-thinking this, Avi :)



-Original Message-
From: Python-list  On
Behalf Of Thomas Passin
Sent: Saturday, March 4, 2023 1:09 PM
To: python-list@python.org
Subject: Re: Which more Pythonic - self.__class__ or type(self)?

On 3/4/2023 2:47 AM, Peter J. Holzer wrote:

Even before Python existed there was the adage "a real programmer
can write FORTRAN in any language", indicating that idiomatic usage of a
language is not governed by syntax and library alone, but there is a
cultural element: People writing code in a specific language also read
code by other people in that language, so they start imitating each
other, just like speakers of natural languages imitate each other.
Someone coming from another language will often write code which is
correct but un-idiomatic, and you can often guess which language they
come from (they are "writing FORTRAN in Python").


What Peter didn't say is that this statement is usually used in a
disparaging sense.  It tends to imply that a person can write (or is
writing) awkward or inappropriate code anywhere.



--
https://mail.python.org/mailman/listinfo/python-list


RE: RE: Which more Pythonic - self.__class__ or type(self)?

2023-03-04 Thread avi.e.gross
Alan,

I got divorced from the C++ crowd decades ago when I left Bell Labs. You are 
making me glad I did!

I do accept your suggestion that you can be idiomatic if you follow the common 
methods of whatever language you use. That will take you quite far as long as 
you are not a total slave to it.

But I note some idioms catch on and some are imposed and some become almost 
moot. I am not sure which aspects of C++ have changed drastically and may go 
re-study the modern version as I was a very early adoptee within AT and saw 
changes even back then. 

But I consider something like the half dozen or so major print variants in 
python and wonder how much longer some of them will be seen as worth using, let 
alone idiomatic. Something like an fstring may dominate for many purposes.

I know in R, that I used to use some convoluted methods to assemble output that 
I often now ignore once a "glue" package gave me something similar to fstring 
abilities where all kinds of variables and calculations can now be embedded 
withing a string to be dynamically evaluated in your current environment. Some 
of the documents I write now similarly embed parts of programs and also have an 
inline ability to evaluate small amounts of code in one of many languages  that 
inserts directly into the text as it is being typeset.

So I see moving targets where what was formerly at or near the state of the 
art, becomes passé. So much of my early work rapidly became trivial or 
irrelevant or never caught on or became lost in an environment I no longer 
used. To keep going forward often involves leaving things behind.

Some new features in Python will be interesting to watch. I mentioned the match 
statement. I was using a similar construct in a JVM language called SCALA ages 
ago.  There it was a sort of core part of the language and often replaced 
constructs normally used by other languages such as many simple or nested IF 
statements. I am sure someone will point out where they borrowed parts from or 
who did it better, but what I am saying is that I want to see if it becomes an 
exotic addition to Python in a way that loosely melds, or if it becomes the 
PYTHONIC way ...



-Original Message-
From: Alan Gauld  
Sent: Saturday, March 4, 2023 1:38 PM
To: avi.e.gr...@gmail.com; python-list@python.org
Subject: Re: RE: Which more Pythonic - self.__class__ or type(self)?

On 04/03/2023 17:38, avi.e.gr...@gmail.com wrote:
> 
> Of course each language has commonly used idioms 
> 

That's the point, the correct term is probably "idiomatic"
rather than "pythonic" but it is a defacto standard that
idiomatic Python has become known as Pythonic. I don't
think that's a problem. And at least we aren't in the C++
situation where almost everything that was idiomatic up
until 1999 is now deemed an anti-pattern and they have
standard library modules to try and guide you to use the
"correct" idioms!

But being Pythonic is still a much more loose term and
the community less stressed about it than their C++
cousins where it has almost reached a religious fervour!

-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos



-- 
https://mail.python.org/mailman/listinfo/python-list


RE: Which more Pythonic - self.__class__ or type(self)?

2023-03-04 Thread avi.e.gross
Great idea, DN!

A whole series of books can be written such as:

- Python for virgin dummies who never programmed before.
- Python for former BASIC programmers
- Python for former LISP programmers with a forked tongue
- Python for former Ada Programmers
- Python for ...
- Python for those who find a dozen former languages are simply not enough.
- Python for people who really want to mainly  use the modules like pandas
or sklearn ...
- Pythonic upgrades to the methods used in former inferior languages ...
- How to speak with a Pythonese accent and lose you old accent based on your
former native language(s).

I am sure some books along these lines have already been written!

Who wants to collaborate?

-Original Message-
From: Python-list  On
Behalf Of dn via Python-list
Sent: Saturday, March 4, 2023 1:26 PM
To: python-list@python.org
Subject: Re: Which more Pythonic - self.__class__ or type(self)?

On 04/03/2023 20.47, Peter J. Holzer wrote:
> On 2023-03-03 13:51:11 -0500, avi.e.gr...@gmail.com wrote:

...
> No. Even before Python existed there was the adage "a real programmer
> can write FORTRAN in any language", indicating that idiomatic usage of a
> language is not governed by syntax and library alone, but there is a
> cultural element: People writing code in a specific language also read
> code by other people in that language, so they start imitating each
> other, just like speakers of natural languages imitate each other.
> Someone coming from another language will often write code which is
> correct but un-idiomatic, and you can often guess which language they
> come from (they are "writing FORTRAN in Python"). Also quite similar to
> natural languages where you can guess the native language of an L2
> speaker by their accent and phrasing.

With ph agree I do...

or do you want that in a DO-loop with a FORMAT?

-- 
Regards,
=dn
-- 
https://mail.python.org/mailman/listinfo/python-list

-- 
https://mail.python.org/mailman/listinfo/python-list


RE: Which more Pythonic - self.__class__ or type(self)?

2023-03-04 Thread avi.e.gross
I don't know, Thomas. For some simple programs, there is some evolutionary
benefit by starting with what you know and gradually growing from there. He
first time you need to do something that seems to need a loop in python,
there are loops to choose from. 

But as noted in a recent discussion, things are NOT NECESSARILY the same
even with something that simple. Did your previous languages retain
something like the loop variable outside the loop? What are your new scoping
rules? Do you really want to keep using global variables, and so on.

And, another biggie is people who just don't seem aware of what comes easily
in the new language. I have seen people from primitive environments set up
programs with multiple arrays they process the hard way instead of using
some forms of structure like a named tuple or class arranged in lists or use
a multidimensional numpy/pandas kind of data structure.

So ignoring the word pythonic as too specific, is there a way to say that
something is the way your current language supports more naturally? 

Yes, there are sort of fingerprints in how people write. Take the python
concept of truthy and how some people will still typically add a test for
equality with True. That may not be pythonic to some but is there much harm
in being explicit so anyone reading the code better understands what it doe?

I have to wonder what others make of my code as my style is likely to be
considered closer to "eclectic" as I came to python late and found an
expanding language with way too many ways to do anything and can choose. But
I claim that too is pythonic!

-Original Message-
From: Python-list  On
Behalf Of Thomas Passin
Sent: Saturday, March 4, 2023 1:09 PM
To: python-list@python.org
Subject: Re: Which more Pythonic - self.__class__ or type(self)?

On 3/4/2023 2:47 AM, Peter J. Holzer wrote:
> Even before Python existed there was the adage "a real programmer
> can write FORTRAN in any language", indicating that idiomatic usage of a
> language is not governed by syntax and library alone, but there is a
> cultural element: People writing code in a specific language also read
> code by other people in that language, so they start imitating each
> other, just like speakers of natural languages imitate each other.
> Someone coming from another language will often write code which is
> correct but un-idiomatic, and you can often guess which language they
> come from (they are "writing FORTRAN in Python").

What Peter didn't say is that this statement is usually used in a 
disparaging sense.  It tends to imply that a person can write (or is 
writing) awkward or inappropriate code anywhere.

-- 
https://mail.python.org/mailman/listinfo/python-list

-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Which more Pythonic - self.__class__ or type(self)?

2023-03-04 Thread Peter J. Holzer
On 2023-03-04 12:38:22 -0500, avi.e.gr...@gmail.com wrote:
> Of course each language has commonly used idioms as C with pointer
> arithmetic and code like *p++=*q++ but my point is that although I live near
> a  seaway and from where C originated, I am not aware of words like "c-way"
> or "scenic" as compared to the way people keep saying "pythonic".

Oh, you're talking about the term, not the concept? 

You may have something there. I remember lots of discussions about
"idiomatic C" or "idiomatic Perl", but not about "C-nic" (nice pun, btw)
or "Perlish" code. The Python community may be unique in having invented
an adjective for that.

hp

-- 
   _  | Peter J. Holzer| Story must make more sense than reality.
|_|_) ||
| |   | h...@hjp.at |-- Charles Stross, "Creative writing
__/   | http://www.hjp.at/ |   challenge!"


signature.asc
Description: PGP signature
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: RE: Which more Pythonic - self.__class__ or type(self)?

2023-03-04 Thread Alan Gauld
On 04/03/2023 17:38, avi.e.gr...@gmail.com wrote:
> 
> Of course each language has commonly used idioms 
> 

That's the point, the correct term is probably "idiomatic"
rather than "pythonic" but it is a defacto standard that
idiomatic Python has become known as Pythonic. I don't
think that's a problem. And at least we aren't in the C++
situation where almost everything that was idiomatic up
until 1999 is now deemed an anti-pattern and they have
standard library modules to try and guide you to use the
"correct" idioms!

But being Pythonic is still a much more loose term and
the community less stressed about it than their C++
cousins where it has almost reached a religious fervour!

-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos


-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Which more Pythonic - self.__class__ or type(self)?

2023-03-04 Thread dn via Python-list

On 04/03/2023 20.47, Peter J. Holzer wrote:

On 2023-03-03 13:51:11 -0500, avi.e.gr...@gmail.com wrote:


...

No. Even before Python existed there was the adage "a real programmer
can write FORTRAN in any language", indicating that idiomatic usage of a
language is not governed by syntax and library alone, but there is a
cultural element: People writing code in a specific language also read
code by other people in that language, so they start imitating each
other, just like speakers of natural languages imitate each other.
Someone coming from another language will often write code which is
correct but un-idiomatic, and you can often guess which language they
come from (they are "writing FORTRAN in Python"). Also quite similar to
natural languages where you can guess the native language of an L2
speaker by their accent and phrasing.


With ph agree I do...

or do you want that in a DO-loop with a FORMAT?

--
Regards,
=dn
--
https://mail.python.org/mailman/listinfo/python-list


Re: Which more Pythonic - self.__class__ or type(self)?

2023-03-04 Thread Thomas Passin

On 3/4/2023 2:47 AM, Peter J. Holzer wrote:

Even before Python existed there was the adage "a real programmer
can write FORTRAN in any language", indicating that idiomatic usage of a
language is not governed by syntax and library alone, but there is a
cultural element: People writing code in a specific language also read
code by other people in that language, so they start imitating each
other, just like speakers of natural languages imitate each other.
Someone coming from another language will often write code which is
correct but un-idiomatic, and you can often guess which language they
come from (they are "writing FORTRAN in Python").


What Peter didn't say is that this statement is usually used in a 
disparaging sense.  It tends to imply that a person can write (or is 
writing) awkward or inappropriate code anywhere.


--
https://mail.python.org/mailman/listinfo/python-list


RE: Which more Pythonic - self.__class__ or type(self)?

2023-03-04 Thread avi.e.gross
Peter,

Of course each language has commonly used idioms as C with pointer
arithmetic and code like *p++=*q++ but my point is that although I live near
a  seaway and from where C originated, I am not aware of words like "c-way"
or "scenic" as compared to the way people keep saying "pythonic".

Yes, languages develop idioms and frankly, many are replaced with time. And,
yes, I am sure I can write FORTRAN style  in any language as I used to teach
it, but WATFOR?

If the question is to show a dozen solutions for a problem written in VALID
python and ask a panel of seasoned python programmers which they would
prefer, then sometimes there is a more pythonic solution by that definition.
Give the same test to newbies who each came from a different language
background and are just getting started, and I am not sure I care how they
vote!

I suggest that given a dozen such choices, several may be reasonable choices
and in some cases, I suggest the non-pythonic choice is the right one such
as when you expect someone to port your code to other languages and you need
to keep it simple.

I am simply saying that for ME, some questions are not as simple as others.
I am more interested in whether others can read and understand my code, and
it runs without problems, and maybe even is slightly efficient, than whether
someone deems it pythonic.


-Original Message-
From: Python-list  On
Behalf Of Peter J. Holzer
Sent: Saturday, March 4, 2023 2:48 AM
To: python-list@python.org
Subject: Re: Which more Pythonic - self.__class__ or type(self)?

On 2023-03-03 13:51:11 -0500, avi.e.gr...@gmail.com wrote:
> I do not buy into any concept about something being pythonic or not.
> 
> Python has grown too vast and innovated quite a  bit, but also borrowed
from
> others and vice versa.
> 
> There generally is no universally pythonic way nor should there be. Is
there
> a C way

Oh, yes. Definitely.

> and then a C++ way and an R way or JavaScript

JavaScript has a quite distinctive style. C++ is a big language (maybe
too big for a single person to grok completely) so there might be
several "dialects". I haven't seen enough R code to form an opinion.

> or does only python a language with a philosophy of what is the
> pythonic way?

No. Even before Python existed there was the adage "a real programmer
can write FORTRAN in any language", indicating that idiomatic usage of a
language is not governed by syntax and library alone, but there is a
cultural element: People writing code in a specific language also read
code by other people in that language, so they start imitating each
other, just like speakers of natural languages imitate each other.
Someone coming from another language will often write code which is
correct but un-idiomatic, and you can often guess which language they
come from (they are "writing FORTRAN in Python"). Also quite similar to
natural languages where you can guess the native language of an L2
speaker by their accent and phrasing.

hp

-- 
   _  | Peter J. Holzer| Story must make more sense than reality.
|_|_) ||
| |   | h...@hjp.at |-- Charles Stross, "Creative writing
__/   | http://www.hjp.at/ |   challenge!"

-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Which more Pythonic - self.__class__ or type(self)?

2023-03-03 Thread Peter J. Holzer
On 2023-03-03 13:51:11 -0500, avi.e.gr...@gmail.com wrote:
> I do not buy into any concept about something being pythonic or not.
> 
> Python has grown too vast and innovated quite a  bit, but also borrowed from
> others and vice versa.
> 
> There generally is no universally pythonic way nor should there be. Is there
> a C way

Oh, yes. Definitely.

> and then a C++ way and an R way or JavaScript

JavaScript has a quite distinctive style. C++ is a big language (maybe
too big for a single person to grok completely) so there might be
several "dialects". I haven't seen enough R code to form an opinion.

> or does only python a language with a philosophy of what is the
> pythonic way?

No. Even before Python existed there was the adage "a real programmer
can write FORTRAN in any language", indicating that idiomatic usage of a
language is not governed by syntax and library alone, but there is a
cultural element: People writing code in a specific language also read
code by other people in that language, so they start imitating each
other, just like speakers of natural languages imitate each other.
Someone coming from another language will often write code which is
correct but un-idiomatic, and you can often guess which language they
come from (they are "writing FORTRAN in Python"). Also quite similar to
natural languages where you can guess the native language of an L2
speaker by their accent and phrasing.

hp

-- 
   _  | Peter J. Holzer| Story must make more sense than reality.
|_|_) ||
| |   | h...@hjp.at |-- Charles Stross, "Creative writing
__/   | http://www.hjp.at/ |   challenge!"


signature.asc
Description: PGP signature
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Which more Pythonic - self.__class__ or type(self)?

2023-03-03 Thread Greg Ewing via Python-list

On 4/03/23 7:51 am, avi.e.gr...@gmail.com wrote:


I leave you with the question of the day. Was Voldemort pythonic?


Well, he was fluent in Parseltongue, which is not a good sign.

I hope not, otherwise we'll have to rename Python to "The Language
That Shall Not Be Named" and watch out for horcruxes during code
reviews.

I'll note that he was fluent in Parseltongue, which is not a good
sign.

--
Greg
--
https://mail.python.org/mailman/listinfo/python-list


RE: Which more Pythonic - self.__class__ or type(self)?

2023-03-03 Thread avi.e.gross


Alan,

I do not buy into any concept about something being pythonic or not.

Python has grown too vast and innovated quite a  bit, but also borrowed from
others and vice versa.

There generally is no universally pythonic way nor should there be. Is there
a C way and then a C++ way and an R way or JavaScript or does only python a
language with a philosophy of what is the pythonic way?

My vague impression was that the pythonic way was somewhat of a contrast to
the way a programmer did it before coming to python. So some would argue
that although python allows loops, that some things are more naturally done
in python using a list comprehension.

Really?

I suggest that NOW for some people, it is way more natural to import modules
like numpy and pandas and use their tools using a more vectorized approach.
Is that the new pythonic in some situations?

I can also argue that if you were a contestant on Jeopardy and were in a
category for computer languages and were shown some computer code  and asked
to name that language in 4 lines, then the most pythonic would not be one
saying type(var) but the one showing a dunder method! I mean what makes some
languages special is often the underlying details! On the surface, many look
fairly similar.

Some problems not only can be solved many ways in python, but by using
combinations of different programming paradigms. It can be argued by some
that the pythonic way is to use some forms of object-oriented programming
and by others pushing for a more functional approach. Some seem to continue
pushing for efficiency and others relish at using up CPU cycles and prefer
other considerations such as what is easier for the programmer or that is
more self-documenting.

My answer remains, in this case, like yours. The dunder methods are
generally meant to be implementation details mostly visible when creating
new classes or perhaps adjusting an object. They largely implement otherwise
invisible protocols by providing the hooks the protocols invoke, and do it
in a somewhat reserved name space. If the user is writing code that just
uses existing classes, generally no dunderheads should be seen. I think
using them is not only not pythonic, but risks breaking code if some changes
to python are made.  As one example, the iteration protocol now has new
dunder methods added to be used for asynchronous and calling the __iter__()
type methods will not work well and you now need to know to call the new
ones. Or, don't call them at all and use the regular functions provided.

Some things may be clearly more in the spirit of the language and sometimes
who cares. Consider the debate that since python allows you to fail and
catch an exception, why bother using if statements such as checking for
no-zero before dividing. I never understood that. Plan A works. Now you can
also chose plan B. They both work. But has anyone asked some dumb questions
about the data the code is working on? What if you have data full of zeroes
or NA or Inf or other things make a division problematic. What is the cost
of testing for something or a group of things every time versus setting up a
try/catch every time? What about lots of nesting of these things. What can
humans read better or make adjustments to?

In my mind, if the bad thing you want to avoid is rare and the testing is
costly, perhaps the exception method is best. I mean if you are working with
large numbers where primes are not common, then having to test if it is a
prime can be costly while catching a failure may be less so.

But consider how some people act as if pythonic means you should not care
about efficiency! LOL!

I leave you with the question of the day. Was Voldemort pythonic?

Avi


-Original Message-
From: Python-list  On
Behalf Of Alan Gauld
Sent: Friday, March 3, 2023 4:43 AM
To: python-list@python.org
Subject: Re: Which more Pythonic - self.__class__ or type(self)?

On 02/03/2023 20:54, Ian Pilcher wrote:
> Seems like an FAQ, and I've found a few things on StackOverflow that
> discuss the technical differences in edge cases, but I haven't found
> anything that talks about which form is considered to be more Pythonic
> in those situations where there's no functional difference.

I think avoiding dunder methods is generally considered more Pythonic.

But in this specific case using isinstance() is almost always
the better option. Testing for a specific class is likely to break
down in the face of subclasses. And in Python testing for static types
should rarely be necessary since Python uses duck typing
and limiting things to a hard type seriously restricts your code.

-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos


-- 
https://mail.python.org/mailman/listinfo/python-list

-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Which more Pythonic - self.__class__ or type(self)?

2023-03-03 Thread Ethan Furman

On 3/3/23 03:32, Chris Angelico wrote:
> On Fri, 3 Mar 2023 at 20:44, Alan Gauld wrote:
>> On 02/03/2023 20:54, Ian Pilcher wrote:

>>> Seems like an FAQ, and I've found a few things on StackOverflow that
>>> discuss the technical differences in edge cases, but I haven't found
>>> anything that talks about which form is considered to be more Pythonic
>>> in those situations where there's no functional difference.
>>
>> I think avoiding dunder methods is generally considered more Pythonic.

Outside of writing dunder methods, I tend to agree.

>> But in this specific case using isinstance() is almost always
>> the better option.

True.  IIRC, the only time I haven't used `isinstance` is in `Enum`, where a particular object has to be exactly a tuple 
(not a namedtuple, for example) to work correctly.


> Using isinstance is very different from querying the type of an object
> though. They're used for different purposes. And obj.__class__ and
> type(obj) are different too, which is why the OP specifically narrowed
> this down to the situations where you know they're the same.

When writing classes and subclasses, I use `obj.__class__`, `isinstance` otherwise, and rarely `type(obj)` (and then 
mostly with `tuple`s, as they're special).


~Ethan~
--
https://mail.python.org/mailman/listinfo/python-list


Re: Which more Pythonic - self.__class__ or type(self)?

2023-03-03 Thread Chris Angelico
On Fri, 3 Mar 2023 at 20:44, Alan Gauld  wrote:
>
> On 02/03/2023 20:54, Ian Pilcher wrote:
> > Seems like an FAQ, and I've found a few things on StackOverflow that
> > discuss the technical differences in edge cases, but I haven't found
> > anything that talks about which form is considered to be more Pythonic
> > in those situations where there's no functional difference.
>
> I think avoiding dunder methods is generally considered more Pythonic.
>
> But in this specific case using isinstance() is almost always
> the better option. Testing for a specific class is likely to break
> down in the face of subclasses. And in Python testing for static types
> should rarely be necessary since Python uses duck typing
> and limiting things to a hard type seriously restricts your code.
>

Using isinstance is very different from querying the type of an object
though. They're used for different purposes. And obj.__class__ and
type(obj) are different too, which is why the OP specifically narrowed
this down to the situations where you know they're the same.

Personally, I'd probably use type(obj) if the distinction doesn't
matter, but that's nothing more than personal preference.

ChrisA
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Which more Pythonic - self.__class__ or type(self)?

2023-03-03 Thread Alan Gauld
On 02/03/2023 20:54, Ian Pilcher wrote:
> Seems like an FAQ, and I've found a few things on StackOverflow that
> discuss the technical differences in edge cases, but I haven't found
> anything that talks about which form is considered to be more Pythonic
> in those situations where there's no functional difference.

I think avoiding dunder methods is generally considered more Pythonic.

But in this specific case using isinstance() is almost always
the better option. Testing for a specific class is likely to break
down in the face of subclasses. And in Python testing for static types
should rarely be necessary since Python uses duck typing
and limiting things to a hard type seriously restricts your code.

-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos


-- 
https://mail.python.org/mailman/listinfo/python-list


RE: Which more Pythonic - self.__class__ or type(self)?

2023-03-02 Thread avi.e.gross
My understanding is that python created functions like type() and len() as a
general purpose way to get information and ALSO set up a protocol that
classes can follow by creating dunder methods. I think the most pythonic
things is to avoid directly calling the dunder methods with a few exceptions
that mainly happen when you are building or extending classes. I mean some
dunder methods are then called directly to avoid getting into infinite loops
that would be triggered.

And note in many cases, the protocol is more complex. Is a length built-in?
If not, can the object be iterated and you count the results? Calling the
function len() may get you more info as it can leverage such things. And it
means you can sometimes leave out some methods and your code still works.

Be warned that type() is a very special function in python and when called
with more arguments, does many relatively beautiful but unrelated things. It
has a special role in the class or type hierarchy. But used with a single
argument, it harmlessly return a result you want.


-Original Message-
From: Python-list  On
Behalf Of Thomas Passin
Sent: Thursday, March 2, 2023 6:43 PM
To: python-list@python.org
Subject: Re: Which more Pythonic - self.__class__ or type(self)?

On 3/2/2023 5:53 PM, Greg Ewing via Python-list wrote:
> On 3/03/23 9:54 am, Ian Pilcher wrote:
>> I haven't found
>> anything that talks about which form is considered to be more Pythonic
>> in those situations where there's no functional difference.
> 
> In such cases I'd probably go for type(x), because it looks less
> ugly.
> 
> x.__class__ *might* be slightly more efficient, as it avoids a
> global lookup and a function call. But as always, measurement
> would be required to be sure.

Except that we don't know if "efficiency" - whatever that might mean 
here - matters at all.

-- 
https://mail.python.org/mailman/listinfo/python-list

-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Which more Pythonic - self.__class__ or type(self)?

2023-03-02 Thread Thomas Passin

On 3/2/2023 5:53 PM, Greg Ewing via Python-list wrote:

On 3/03/23 9:54 am, Ian Pilcher wrote:

I haven't found
anything that talks about which form is considered to be more Pythonic
in those situations where there's no functional difference.


In such cases I'd probably go for type(x), because it looks less
ugly.

x.__class__ *might* be slightly more efficient, as it avoids a
global lookup and a function call. But as always, measurement
would be required to be sure.


Except that we don't know if "efficiency" - whatever that might mean 
here - matters at all.


--
https://mail.python.org/mailman/listinfo/python-list


Re: Which more Pythonic - self.__class__ or type(self)?

2023-03-02 Thread Greg Ewing via Python-list

On 3/03/23 9:54 am, Ian Pilcher wrote:

I haven't found
anything that talks about which form is considered to be more Pythonic
in those situations where there's no functional difference.


In such cases I'd probably go for type(x), because it looks less
ugly.

x.__class__ *might* be slightly more efficient, as it avoids a
global lookup and a function call. But as always, measurement
would be required to be sure.

--
Greg
--
https://mail.python.org/mailman/listinfo/python-list


Re: Which more Pythonic - self.__class__ or type(self)?

2023-03-02 Thread Thomas Passin

On 3/2/2023 3:54 PM, Ian Pilcher wrote:

Seems like an FAQ, and I've found a few things on StackOverflow that
discuss the technical differences in edge cases, but I haven't found
anything that talks about which form is considered to be more Pythonic
in those situations where there's no functional difference.

Is there any consensus?


For what purpose do you want to get it?

--
https://mail.python.org/mailman/listinfo/python-list


Which more Pythonic - self.__class__ or type(self)?

2023-03-02 Thread Ian Pilcher

Seems like an FAQ, and I've found a few things on StackOverflow that
discuss the technical differences in edge cases, but I haven't found
anything that talks about which form is considered to be more Pythonic
in those situations where there's no functional difference.

Is there any consensus?

--

Google  Where SkyNet meets Idiocracy

--
https://mail.python.org/mailman/listinfo/python-list


[Python-announce] Lona: a simple pythonic framework to write responsive web apps in full Python

2022-12-06 Thread Florian Scherf
Web: https://lona-web.org/1.x/
Github: https://github.com/lona-web-org/lona/


What is Lona?
=

Lona is a web application framework, designed to write responsive web apps in
full Python.

Web is a solved problem in Python since ages, but traditionally Python handles
only the server side. If you want to have client side interaction like click
events or you want update content live, you have to write an additional
Javascript application.

Lona handles the server side and the client side, and provides a simple,
pythonic API to write self contained views.

Lona is very easy to use. You can write a whole web app, using only one simple
Python script.

https://lona-web.org/1.x/demos/


Get involved!
=

I released 1.10.5 yesterday. Lona is pretty stable and well tested right now,
but a major release is right around the corner. Helping hands, feedback and
new ideas in any form are very welcome.


Best regards,
Florian Scherf 
___
Python-announce-list mailing list -- python-announce-list@python.org
To unsubscribe send an email to python-announce-list-le...@python.org
https://mail.python.org/mailman3/lists/python-announce-list.python.org/
Member address: arch...@mail-archive.com


Pythonic way to run the asyncio loop forever in python 3.10

2022-10-06 Thread David Jander


Hello,

It is highly likely this has been discussed before, but I haven't been able to
find the answer to my question, so if anyone knows, please send me to the
right place. Thanks.

I am migrating a lot of python software to 3.10, which has deprecated calling
asyncio.get_event_loop() from outside the loop. While doing so, I have bumped
against some common (I think) use-cases which seem to have no elegant solution
anymore. At least I can't find one that seems "pythonic" or "correct".

Problem: Before 3.10, asyncio.get_event_loop() was a convenient way to manage
the loop singleton. In single-threaded applications, normally you want only a
single instance of an event loop. The easiest way to make sure there was only
one loop ever created, was to call asyncio.get_event_loop(). Since the only
place this is crucially important to get right is _outside_ of the loop
(because once inside the loop all damage is done already anyway), deprecating
this use-case basically seems to destroy the usefulness of that method, and
also many other methods of loop, like loop.run_forever() and
loop.run_until_complete().

Example: Suppose an application that does a bunch of (blocking and CPU
intensive) initialization, while also setting up event handlers, that may call
things like loop.add_reader() or loop.call_soon() in many different places.
Then, after all initialization is done, loop.run_forever() is called to get the
application running. Notice, that there may not even be a single coroutine
involved.

Someone else asked something similar here:

https://stackoverflow.com/questions/65684730/what-is-the-pythonic-way-of-running-an-asyncio-event-loop-forever

Unfortunately all proposed answers look like dirty hacks.

In concrete, how do I do this nicely?

async def main():
loop = asyncio.get_running_loop()
...
loop.add_reader(...)
...
loop.call_later(...)
...
... etc...

# HACK: Now wait forever to keep the loop running
await asyncio.Future()

if __name__ == "__main__":
asyncio.run(main())


It can't be seriously the intention that people do these kind of things,
right?

This example application might not even use coroutines at all, and be entirely
event driven. Yet an initial coroutine is now required. No way to run the loop
without one. The worst thing is that all the initialization and blocking code
cannot be easily mixed with loop setup anymore, because loop setup before
starting the loop has essentially been killed by python developers. Please
correct me if I am wrong about any of this. What am I missing here?

Unfortunately the world is now seemingly filled with horrible and sometimes
broken workarounds for this change introduced in 3.10:

https://github.com/aio-libs/aiohttp/blob/master/aiohttp/web.py#L434

https://github.com/tornadoweb/tornado/blob/master/demos/tcpecho/server.py#L36

etc...

Where is the discussion about this, and where are the proposed solutions?

Python 3.11 seems to mitigate this problem by introducing the asyncio.Runner()
context-manager. But for the time being for 3.10, I see no good solution.

Best regards,

-- 
David Jander
-- 
https://mail.python.org/mailman/listinfo/python-list


[issue493628] import not pythonic in 2.1.1

2022-04-10 Thread admin


Change by admin :


--
github: None -> 35749

___
Python tracker 

___
___
Python-bugs-list mailing list
Unsubscribe: 
https://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com



[issue47130] mro and super don't feel so pythonic

2022-03-26 Thread Ken Jin


Ken Jin  added the comment:

Hi @mamliteria, this is the bug tracker for CPython. I understand that you have 
suggestions to improve super(), but feature suggestions usually go on the 
python-ideas mailing list [1]. So you might want to post on there instead.

If you're interested, the MRO creation algorithm uses C3 linearization[2] so 
the output is predictable.

Also maybe the 2-argument form of super() will help. It should cover most cases 
that you propose with __as_parent__.

[1] https://mail.python.org/mailman3/lists/python-ideas.python.org/
[2] https://en.wikipedia.org/wiki/C3_linearization

--
nosy: +kj
resolution:  -> not a bug
stage:  -> resolved
status: open -> closed

___
Python tracker 

___
___
Python-bugs-list mailing list
Unsubscribe: 
https://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com



[issue47130] mro and super don't feel so pythonic

2022-03-26 Thread malmiteria


New submission from malmiteria :

Hi,

Before anything, i made a github repository about this topic here : 
https://github.com/malmiteria/super-alternative-to-super

The core of what i wanna discuss here is that i don't think mro and super 
(mainly because it relies on mro) are very pythonic. Mainly that some behaviors 
of the mro are too implicit, and are silencing what really should be errors.



Let me explain :
in case of multiple inheritence, resolving a child method from it's parent 
isn't an obvious task, and mro comes as a solution to that. However, i don't 
understand why we don't let the programmer solve it. I think this is similar to 
a merge conflict, and not letting the programmer resolve the conflict feels 
like silencing an error. This is especially infuriating when you realise that 
mro doesn't solve all possible scenarios, and then, simply refuses the 
opportunity to solve it to the programmer.
Then, super relying on mro gives off some weird behaviors, mainly, it's 
possible for a child definition to affect what a call to super means in it's 
parent. This feels like a side effect (which is the 'too implicit' thing i 
refer to).
I also don't understand why we can't simply pass the parent targeted as 
argument to super, instead of having no argument, or having to pass the current 
class and instances as argument :
super(child) is a proxy to parent, when super(parent) would make more sense to 
be the proxy to parent, in my mind.

I dive in more depths about those topics in the readme of the github repository 
i linked at the top of this comment.



what i propose is a solution that would follow those rules:

The mro alternative, which i called explicit method resolution aka EMR (which 
is probably not a good name since i apply it, as mro, to all class attributes), 
follow those rules :
 1) Straightforward case : the class definition has the method / attribute : 
this is the one EMR should resolve to
 2) Not found : the method / attribute can't be resolved in the class itself, 
or by any of it's parents, then it should raise an AttributeError
 3) Only on parent : the method / attribute can't be resolved in the class 
itself, and can only be resolved by one of it's parents, this is the one EMR 
should resolve to
 4) Multiple parent : the method / attribute can't be resolved in the class 
itself, and can be resolved by at least 2 of it's parents, then an 
ExplicitResolutionRequired error should be raised
 5) Transimittin errors : the method / attribute can't be resolved in the class 
itself, and one parent at least raises an ExplicitResolutionRequired error, 
then it should raise an ExplicitResolutionRequired error
 6) (optional?) Single source : when multiple parent can resolve a method from 
a single source (in case of diamond shape inheritence), the 
ExplicitResolutionRequired  is not needed

The super alternative, which i called __as_parent__ should follow those rules :
 1) reliability : the target __as_parent__ points to should not depend on 
anything other than the argument passed to it
 2) expliciteness : in case of multiple inheritence, the parent targetted 
should be passed as an argument to the __as_parent__ method.
 3) impliciteness : in case of simple inheritence, it is not needed to specify 
the parent targeted (since there can only be one, and it make it closer to the 
actual behavior of super in most cases)
 4) ancestors as targets : should be able to target ancestors, either direct or 
not (which is needed in case two grandparent define a method that a single 
parent share, there would be no other way to solve the 
ExplicitResolutionRequired otherwise)



this solution has a few advantages in my mind :
 - the current mro and super are more tightly coupled than the emr and 
__as_parent__ i propose here
 - the __as_parent__ is more reliable than super in its behavior, and should 
lead to an easier learning curve
 - the emr i propose as a replacement to mro allows for some inheritence tree 
mro doesn't allow.
 - the __as_parent__ method being able to target specific parent allows for 
different methods to visit the parents in different order easily, which today 
would be harder, since the parent visiting order is tightly coupled to the 
class definition
 - with emr, in case of problematic resolution, an error is raised to tell you 
about the problem, and ask you for explicit resolution, the current solution 
doesn't, which can lead to surprises closer to production environment.



A few possible downsides :
 - the transition would be a pain to deal with
 - the current mro allows for dependencies injection in the inheritence tree. I 
believe this feature should be untied from super and mro, but it would require 
some work.
 - the current super and mro are old enough to have been faced with issues and 
having been updated to solve those issues down the line. Any alternative would 
have to face those issues again and new ones down the line
 - any coexistence between those two

[issue42069] Make filecmp more pythonic

2020-10-18 Thread Raymond Hettinger


Raymond Hettinger  added the comment:

In general, we don't accept patches like this:

* It risks breaks (in fact the tests are failing.
* We're not apply Black's quoting preferences to existing files.
* We're not yet adding type annotations through out.
* The PR introduces multiple new dependencies on other modules.
  This tends to slow down load time and complicate maintenance.
* There are subtle changes to the logic and API because
  of the dataclasses, cached_property, and lru_cache.
* We want to avoid code churn because it reduces stability
  and because it complicates maintenance (making it harder to
  apply fixes across versions).

Thank you for the suggestion, but we'll decline.

--
nosy: +rhettinger
resolution:  -> rejected
stage: patch review -> resolved
status: open -> closed

___
Python tracker 

___
___
Python-bugs-list mailing list
Unsubscribe: 
https://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com



[issue42069] Make filecmp more pythonic

2020-10-18 Thread Alex


Change by Alex :


--
keywords: +patch
pull_requests: +21712
stage:  -> patch review
pull_request: https://github.com/python/cpython/pull/22750

___
Python tracker 

___
___
Python-bugs-list mailing list
Unsubscribe: 
https://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com



[issue42069] Make filecmp more pythonic

2020-10-18 Thread Alex


New submission from Alex :

Cleanup the filecmp file add typing and make it more pythonic

--
components: Library (Lib)
messages: 378877
nosy: alex.briskin
priority: normal
severity: normal
status: open
title: Make filecmp more pythonic
versions: Python 3.9

___
Python tracker 
<https://bugs.python.org/issue42069>
___
___
Python-bugs-list mailing list
Unsubscribe: 
https://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com



Re: Pythonic style

2020-09-23 Thread Stavros Macrakis
Thanks, Chris, for the useful comments. Comments in line (with snipping of
unnecessary content):


> > some more variants which *don't* use tuple unpacking, on the theory
> that the coding patterns may be useful in
> > other cases where unpacking doesn't apply.
>
> When doesn't it apply? Can you elaborate on this? It might be easier
> to advise on Pythonic style when the specific requirements are known.
>

No specific requirement. These are *finger exercises* intended to isolate
one issue for discussion rather than be useful in themselves.


> > ...but there are ways to avoid the verbose exception handling.
> In Python, exception handling IS the way to do these things.


Good to know. Since *try* statements are at least 4 lines long, I was
trying for something more concise. And maybe somewhere in the back of my
mind, I have the anti-Pythonic principle that exceptions should be reserved
for errors. I'll try to suppress that. I remember one (very old) paper
<http://web.cecs.pdx.edu/~black/publications/Black%20D.%20Phil%20Thesis.pdf>
arguing that exceptions were a bad idea in general... but I have
implemented and used exceptions in many languages, both before and after
that paper!


> > _uniq = []
> > def firstg(iterable):
> > it = iter(iterable)
> > val0 = next(it,_uniq)
> > val1 = next(it,_uniq)
> > if val0 is not _uniq and val1 is _uniq:
> > return val0
> > else:
> > raise ValueError("first1: arg not exactly 1 long")
> >
> > But I don't know if the *_uniq* technique is considered Pythonic.
>
> It is when it's needed, but a more common way to write this would be
> to have the sentinel be local to the function (since it doesn't need
> to be an argument):
>

What do you mean by an argument?

Is it not considered Pythonic for constants to be calculated once at the
module or class level rather than be recalculated every time a function is
entered?

def firstg_variant(iterable):
> it = iter(iterable)
> sentinel = object()
> first = next(it, sentinel)
> if first is sentinel:
> raise ValueError("empty iterable")
> second = next(it, sentinel)
> if second is not sentinel:
> raise ValueError("too many values")
> return first
>
> But getting a return value and immediately checking it is far better
> spelled "try/except" here. (Note, BTW, that I made a subtle change to
> the logic here: this version doesn't call next() a second time if the
> first one returned the sentinel. This avoids problems with broken
> iterators that raise StopException and then keep going.)
>

Yes, I hadn't thought of that. I was trying to avoid repeating the *raise*
 statement.

Thanks again for the helpful comments. They give me a better idea of good
Python style.

 -s
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Pythonic style

2020-09-22 Thread Chris Angelico
On Wed, Sep 23, 2020 at 3:52 AM Stavros Macrakis  wrote:
>
> Thanks to everyone for the comments, especially Tim Chase for the simple
> and elegant tuple unpacking solution, and Léo El Amri for the detailed
> comments on the variants. Below are some more variants which *don't *use
> tuple unpacking, on the theory that the coding patterns may be useful in
> other cases where unpacking doesn't apply.

When doesn't it apply? Can you elaborate on this? It might be easier
to advise on Pythonic style when the specific requirements are known.

> For me, one of the interesting lessons from all these finger exercises is
> that *for* and unpacking hide a lot of messiness, both the initial *iter* call
> and the exception handling. I don't see any way to eliminate the *iter*,
> but there are ways to avoid the verbose exception handling.

In Python, exception handling IS the way to do these things. Having a
two-part return value rather than using an exception is an unusual
idiom in Python (although it's well known in other languages; I
believe JavaScript does iterators this way, for one).

> Using the second arg to *next*, we get what is arguably a more elegant
> solution:
>
>
> _uniq = []
> def firstg(iterable):
> it = iter(iterable)
> val0 = next(it,_uniq)
> val1 = next(it,_uniq)
> if val0 is not _uniq and val1 is _uniq:
> return val0
> else:
> raise ValueError("first1: arg not exactly 1 long")
>
> But I don't know if the *_uniq* technique is considered Pythonic.

It is when it's needed, but a more common way to write this would be
to have the sentinel be local to the function (since it doesn't need
to be an argument):

def firstg_variant(iterable):
it = iter(iterable)
sentinel = object()
first = next(it, sentinel)
if first is sentinel:
raise ValueError("empty iterable")
second = next(it, sentinel)
if second is not sentinel:
raise ValueError("too many values")
return first

But getting a return value and immediately checking it is far better
spelled "try/except" here. (Note, BTW, that I made a subtle change to
the logic here: this version doesn't call next() a second time if the
first one returned the sentinel. This avoids problems with broken
iterators that raise StopException and then keep going.)

> If *next* were instead defined to return a flag (rather than raising an
> exception), the code becomes cleaner and clearer, something like this:
>
>
> def firsth(iterable):
>   it = iter(iterable)
>   (val0, good0) = next2(it)
>   (val1, good1) = next2(it)  # val1 is dummy
>   if good0 and not good1:
> return val0
>   else:
> raise ValueError("first1: arg not exactly 1 long")
>

IMO this isn't any better than the previous one. You still need a
sentinel, but now you use True and False instead of a special object.
It isn't *terrible*, but it's no advantage either.

ChrisA
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Pythonic style

2020-09-22 Thread Stavros Macrakis
Thanks to everyone for the comments, especially Tim Chase for the simple
and elegant tuple unpacking solution, and Léo El Amri for the detailed
comments on the variants. Below are some more variants which *don't *use
tuple unpacking, on the theory that the coding patterns may be useful in
other cases where unpacking doesn't apply.

For me, one of the interesting lessons from all these finger exercises is
that *for* and unpacking hide a lot of messiness, both the initial *iter* call
and the exception handling. I don't see any way to eliminate the *iter*,
but there are ways to avoid the verbose exception handling.

Using the second arg to *next*, we get what is arguably a more elegant
solution:


_uniq = []
def firstg(iterable):
it = iter(iterable)
val0 = next(it,_uniq)
val1 = next(it,_uniq)
if val0 is not _uniq and val1 is _uniq:
return val0
else:
raise ValueError("first1: arg not exactly 1 long")


But I don't know if the *_uniq* technique is considered Pythonic.

If *next* were instead defined to return a flag (rather than raising an
exception), the code becomes cleaner and clearer, something like this:


def firsth(iterable):
  it = iter(iterable)
  (val0, good0) = next2(it)
  (val1, good1) = next2(it)  # val1 is dummy
  if good0 and not good1:
return val0
  else:
raise ValueError("first1: arg not exactly 1 long")

# returns (value, validp)

# validp is False if no more values

def next2(iterable):
  try:
val = next(iterable)
  except StopIteration:
return (None, False)
  return (val, True)


(To be clear, I'm *not *suggesting that *next2* replace *next*!)

Thoughts?

 -s
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Pythonic style

2020-09-21 Thread Stavros Macrakis
Thanks, Tim! I didn't realize that you could write (x,) on the LHS!
Very nice, very Pythonic!

  -s

On Mon, Sep 21, 2020 at 9:15 AM Tim Chase 
wrote:

> On 2020-09-20 18:34, Stavros Macrakis wrote:
> > Consider a simple function which returns the first element of an
> > iterable if it has exactly one element, and throws an exception
> > otherwise. It should work even if the iterable doesn't terminate.
> > I've written this function in multiple ways, all of which feel a
> > bit clumsy.
> >
> > I'd be interested to hear thoughts on which of these solutions is
> > most Pythonic in style. And of course if there is a more elegant
> > way to solve this, I'm all ears! I'm probably missing something
> > obvious!
>
> You can use tuple unpacking assignment and Python will take care of
> the rest for you:
>
>   >>> x, = tuple() # no elements
>   Traceback (most recent call last):
> File "", line 1, in 
>   ValueError: not enough values to unpack (expected 1, got 0)
>   >>> x, = (1, )  # one element
>   >>> x, = itertools.repeat("hello") # 2 to infinite elements
>   Traceback (most recent call last):
> File "", line 1, in 
>   ValueError: too many values to unpack (expected 1)
>
> so you can do
>
>   def fn(iterable):
> x, = iterable
> return x
>
> The trailing comma can be hard to spot, so I usually draw a little
> extra attention to it with either
>
>   (x, ) = iterable
>
> or
>
>   x, = iterable # unpack one value
>
> I'm not sure it qualifies as Pythonic, but it uses Pythonic features
> like tuple unpacking and the code is a lot more concise.
>
> -tim
>
>
>
>
>
>
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Pythonic style

2020-09-21 Thread Terry Reedy

On 9/20/2020 6:34 PM, Stavros Macrakis wrote:

I'm trying to improve my Python style.

Consider a simple function which returns the first element of an iterable
if it has exactly one element, and throws an exception otherwise. It should
work even if the iterable doesn't terminate. I've written this function in
multiple ways, all of which feel a bit clumsy.


The 'obvious' thing to me was the double try-except StopIteration.  It 
is clear, and clarity is 'pythonic'.



--
Terry Jan Reedy

--
https://mail.python.org/mailman/listinfo/python-list


Re: Pythonic style

2020-09-21 Thread Frank Millman

On 2020-09-21 3:46 PM, Chris Angelico wrote:

On Mon, Sep 21, 2020 at 11:37 PM Tim Chase
 wrote:


On 2020-09-20 18:34, Stavros Macrakis wrote:

Consider a simple function which returns the first element of an
iterable if it has exactly one element, and throws an exception
otherwise. It should work even if the iterable doesn't terminate.
I've written this function in multiple ways, all of which feel a
bit clumsy.

I'd be interested to hear thoughts on which of these solutions is
most Pythonic in style. And of course if there is a more elegant
way to solve this, I'm all ears! I'm probably missing something
obvious!


You can use tuple unpacking assignment and Python will take care of
the rest for you:

   >>> x, = tuple() # no elements
   Traceback (most recent call last):
 File "", line 1, in 
   ValueError: not enough values to unpack (expected 1, got 0)
   >>> x, = (1, )  # one element
   >>> x, = itertools.repeat("hello") # 2 to infinite elements
   Traceback (most recent call last):
 File "", line 1, in 
   ValueError: too many values to unpack (expected 1)

so you can do

   def fn(iterable):
 x, = iterable
 return x

The trailing comma can be hard to spot, so I usually draw a little
extra attention to it with either

   (x, ) = iterable

or

   x, = iterable # unpack one value

I'm not sure it qualifies as Pythonic, but it uses Pythonic features
like tuple unpacking and the code is a lot more concise.


Or:

[x] = iterable

I'd definitely recommend using unpacking as the most obvious way to do
this. Among other advantages, it gives different messages for the "too
many" and "too few" cases.



I used something similar years ago, but I made the mistake of relying on 
the error message in my logic, to distinguish between 'too few' and 'too 
many'. Guess what happened - Python changed the wording of the messages, 
and my logic failed.


After messing about with some alternatives, I ended up with the OP's 
first option (with some added comments), and have stuck with it ever 
since. It is not pretty, but it is readable and unambiguous.


Frank Millman

--
https://mail.python.org/mailman/listinfo/python-list


Re: Pythonic style

2020-09-21 Thread Tim Chase
On 2020-09-21 09:48, Stavros Macrakis wrote:
>>   def fn(iterable):
>> x, = iterable
>> return x
>
> Thanks, Tim! I didn't realize that you could write (x,) on the LHS!
> Very nice, very Pythonic!

It also expands nicely for other cases, so you want the 3-and-only-3
first values with errors for too many or too few?

  x, y, z = iterable
  x, y, z = (1, 2, 3)

The (x,) version is just the single case.  And it's fast—a single
Python UNPACK_SEQUENCE opcode

  >>> dis.dis(fn)
  2   0 LOAD_FAST0 (i)
  2 UNPACK_SEQUENCE  1
  4 STORE_FAST   1 (x)

  3   6 LOAD_FAST1 (x)
  8 RETURN_VALUE

Though now I'm wondering if there's a way to skip the
STORE_FAST/LOAD_FAST instructions and create a function that
generates the opcode sequence

  UNPACK_SEQUENCE 1
  RETURN_VALUE

:-)

(totally tangential ramblings)

-tkc







-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Pythonic style

2020-09-21 Thread Léo El Amri via Python-list
On 21/09/2020 15:15, Tim Chase wrote:
> You can use tuple unpacking assignment and Python will take care of
> the rest for you:
> 
> so you can do
> 
>   def fn(iterable):
> x, = iterable
> return x
> 
> I'm not sure it qualifies as Pythonic, but it uses Pythonic features
> like tuple unpacking and the code is a lot more concise.

I guess you just beat the topic. I think it is Pythonic and I'd be
surprised if someone came with something more Pythonic.

FI: The behavior of this assignation is detailed here:
https://docs.python.org/3/reference/simple_stmts.html#assignment-statements
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Pythonic style

2020-09-21 Thread Chris Angelico
On Mon, Sep 21, 2020 at 11:37 PM Tim Chase
 wrote:
>
> On 2020-09-20 18:34, Stavros Macrakis wrote:
> > Consider a simple function which returns the first element of an
> > iterable if it has exactly one element, and throws an exception
> > otherwise. It should work even if the iterable doesn't terminate.
> > I've written this function in multiple ways, all of which feel a
> > bit clumsy.
> >
> > I'd be interested to hear thoughts on which of these solutions is
> > most Pythonic in style. And of course if there is a more elegant
> > way to solve this, I'm all ears! I'm probably missing something
> > obvious!
>
> You can use tuple unpacking assignment and Python will take care of
> the rest for you:
>
>   >>> x, = tuple() # no elements
>   Traceback (most recent call last):
> File "", line 1, in 
>   ValueError: not enough values to unpack (expected 1, got 0)
>   >>> x, = (1, )  # one element
>   >>> x, = itertools.repeat("hello") # 2 to infinite elements
>   Traceback (most recent call last):
> File "", line 1, in 
>   ValueError: too many values to unpack (expected 1)
>
> so you can do
>
>   def fn(iterable):
> x, = iterable
> return x
>
> The trailing comma can be hard to spot, so I usually draw a little
> extra attention to it with either
>
>   (x, ) = iterable
>
> or
>
>   x, = iterable # unpack one value
>
> I'm not sure it qualifies as Pythonic, but it uses Pythonic features
> like tuple unpacking and the code is a lot more concise.

Or:

[x] = iterable

I'd definitely recommend using unpacking as the most obvious way to do
this. Among other advantages, it gives different messages for the "too
many" and "too few" cases.

ChrisA
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Pythonic style

2020-09-21 Thread Tim Chase
On 2020-09-20 18:34, Stavros Macrakis wrote:
> Consider a simple function which returns the first element of an
> iterable if it has exactly one element, and throws an exception
> otherwise. It should work even if the iterable doesn't terminate.
> I've written this function in multiple ways, all of which feel a
> bit clumsy.
> 
> I'd be interested to hear thoughts on which of these solutions is
> most Pythonic in style. And of course if there is a more elegant
> way to solve this, I'm all ears! I'm probably missing something
> obvious!

You can use tuple unpacking assignment and Python will take care of
the rest for you:

  >>> x, = tuple() # no elements
  Traceback (most recent call last):
File "", line 1, in 
  ValueError: not enough values to unpack (expected 1, got 0)
  >>> x, = (1, )  # one element
  >>> x, = itertools.repeat("hello") # 2 to infinite elements
  Traceback (most recent call last):
File "", line 1, in 
  ValueError: too many values to unpack (expected 1)

so you can do

  def fn(iterable):
x, = iterable
return x

The trailing comma can be hard to spot, so I usually draw a little
extra attention to it with either

  (x, ) = iterable

or

  x, = iterable # unpack one value

I'm not sure it qualifies as Pythonic, but it uses Pythonic features
like tuple unpacking and the code is a lot more concise.

-tim





-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Pythonic style

2020-09-21 Thread Léo El Amri via Python-list
On 21/09/2020 00:34, Stavros Macrakis wrote:
> I'm trying to improve my Python style.
> 
> Consider a simple function which returns the first element of an iterable
> if it has exactly one element, and throws an exception otherwise. It should
> work even if the iterable doesn't terminate. I've written this function in
> multiple ways, all of which feel a bit clumsy.
> 
> I'd be interested to hear thoughts on which of these solutions is most
> Pythonic in style. And of course if there is a more elegant way to solve
> this, I'm all ears! I'm probably missing something obvious!

Hello Stavros,

As there is no formal definition nor consensus on what is Pythonic and
what isn't, this reply will be very subjective.



My opinion on your code suggestions is the following:

> 1 def firstf(iterable):
> 2 n = -1
> 3 for n,i in enumerate(iterable):
> 4 if n>0:
> 5 raise ValueError("first1: arg not exactly 1 long")
> 6 if n==0:
> 7 return i
> 8 else:
> 9 raise ValueError("first1: arg not exactly 1 long")

firstf isn't Pythonic:

1. We are checking twice for the same thing at line 4 (n>0)
   and 6 (n==0).

2. We are using enumarate(), from which we ignore the second element
   it yields in its tuple

> 1 def firstd(iterable):
> 2 it = iter(iterable)
> 3 try:
> 4 val = next(it)
> 5 except StopIteration:
> 6 raise ValueError("first1: arg not exactly 1 long")
> 7 for i in it:
> 8 raise ValueError("first1: arg not exactly 1 long")
> 9 return val

firstd isn't Pythonic. While the usage of a for statement in place of a
try..except saves two lines, it is at the expense of showing a clear
intent: When I see a for statement, I expect a "complex" operation on
the iterable items (which we are ignoring here).

>  1 def firsta(iterable):
>  2 it = iter(iterable)
>  3 try:
>  4 val = next(it)
>  5 except StopIteration:
>  6 raise ValueError("first1: arg not exactly 1 long")
>  7 try:
>  8 next(it)
>  9 except StopIteration:
> 10 return val
> 11 raise ValueError("first1: arg not exactly 1 long")

>  1 def firstb(iterable):
>  2 it = iter(iterable)
>  3 try:
>  4 val = next(it)
>  5 except StopIteration:
>  6 raise ValueError("first1: arg not exactly 1 long")
>  7 try:
>  8 next(it)
>  9 except StopIteration:
> 10 return val
> 11 else:
> 12 raise ValueError("first1: arg not exactly 1 long")

>  1 def firstc(iterable):
>  2 it = iter(iterable)
>  3 try:
>  4 val = next(it)
>  5 except StopIteration:
>  6 raise ValueError("first1: arg not exactly 1 long")
>  7 try:
>  8 next(it)
>  9 raise ValueError("first1: arg not exactly 1 long")
> 10 except StopIteration:
> 11 return val

firsta, firstb and firstc are equally Pythonic. I have a preference for
firsta, which is more concise and have a better "reading flow".

>  1 def firste(iterable):
>  2 it = iter(iterable)
>  3 try:
>  4 good = False
>  5 val = next(it)
>  6 good = True
>  7 val = next(it)
>  8 good = False
>  9 raise StopIteration   # or raise ValueError
> 10 except StopIteration:
> 11     if good:
> 12 return val
> 13 else:
> 14 raise ValueError("first1: arg not exactly 1 long")

firste might be Pythonic although it's very "C-ish". I can grasp the
intent and there is no repetition. I wouldn't write the assignation at
line 7, though.



Mixing firsta and firste would make something more Pythonic:

def firstg(iterable):
it = iter(iterable)
try:
val = next(it)
try:
next(it)
except StopIteration:
return val
except StopIteration:
pass
raise ValueError("first: arg not exactly 1 long")

1. The code isn't repetitive (The "raise ValueError" is written
   only once)

2. The intent is a bit harder to grasp than for firsta or firste, but
   the code is shorter than firste

3. The try..catch nesting is considered a bad practice, but the code
   here is simple enough so it shouldn't trigger a strong aversion
   reading it



- Léo
-- 
https://mail.python.org/mailman/listinfo/python-list


Pythonic style

2020-09-21 Thread Stavros Macrakis
I'm trying to improve my Python style.

Consider a simple function which returns the first element of an iterable
if it has exactly one element, and throws an exception otherwise. It should
work even if the iterable doesn't terminate. I've written this function in
multiple ways, all of which feel a bit clumsy.

I'd be interested to hear thoughts on which of these solutions is most
Pythonic in style. And of course if there is a more elegant way to solve
this, I'm all ears! I'm probably missing something obvious!

Thanks,

  -s

def firsta(iterable):
it = iter(iterable)
try:
val = next(it)
except StopIteration:
raise ValueError("first1: arg not exactly 1 long")
try:
next(it)
except StopIteration:
return val
raise ValueError("first1: arg not exactly 1 long")

def firstb(iterable):
it = iter(iterable)
try:
val = next(it)
except StopIteration:
raise ValueError("first1: arg not exactly 1 long")
try:
next(it)
except StopIteration:
return val
else:
raise ValueError("first1: arg not exactly 1 long")

def firstc(iterable):
it = iter(iterable)
try:
val = next(it)
except StopIteration:
raise ValueError("first1: arg not exactly 1 long")
try:
next(it)
raise ValueError("first1: arg not exactly 1 long")
except StopIteration:
return val

def firstd(iterable):
it = iter(iterable)
try:
val = next(it)
except StopIteration:
raise ValueError("first1: arg not exactly 1 long")
for i in it:
raise ValueError("first1: arg not exactly 1 long")
return val

def firste(iterable):
it = iter(iterable)
try:
good = False
val = next(it)
good = True
val = next(it)
good = False
raise StopIteration   # or raise ValueError
except StopIteration:
if good:
return val
else:
raise ValueError("first1: arg not exactly 1 long")

def firstf(iterable):
n = -1
for n,i in enumerate(iterable):
if n>0:
raise ValueError("first1: arg not exactly 1 long")
if n==0:
return i
else:
raise ValueError("first1: arg not exactly 1 long")
-- 
https://mail.python.org/mailman/listinfo/python-list


[issue41077] Make Cookiejar a bit more pythonic

2020-06-22 Thread Rémi Lapeyre

Rémi Lapeyre  added the comment:

Hi Srinivas, as I said on the PR, cosmetic changes are usually not accepted. 
You can have a look at the other opened bug reports to find issues you can work 
on and at the Python Dev Guide (https://devguide.python.org/) for help to get 
started hacking Python!

--
nosy: +remi.lapeyre

___
Python tracker 

___
___
Python-bugs-list mailing list
Unsubscribe: 
https://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com



[issue41077] Make Cookiejar a bit more pythonic

2020-06-22 Thread శ్రీనివాస్ రెడ్డి తాటిపర్తి

Change by Srinivas  Reddy Thatiparthy(శ్రీనివాస్ రెడ్డి తాటిపర్తి) 
:


--
resolution:  -> wont fix
stage: patch review -> resolved
status: open -> closed

___
Python tracker 

___
___
Python-bugs-list mailing list
Unsubscribe: 
https://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com



[issue41077] Make Cookiejar a bit more pythonic

2020-06-22 Thread శ్రీనివాస్ రెడ్డి తాటిపర్తి

Srinivas  Reddy Thatiparthy(శ్రీనివాస్ రెడ్డి తాటిపర్తి) 
 added the comment:

I am not sure this PR will be accepted. If you are a core dev, and thinks this 
is not Okay, please feel free close this issue.

--
keywords: +patch
message_count: 1.0 -> 2.0
pull_requests: +20226
stage:  -> patch review
versions: +Python 3.10
pull_request: https://github.com/python/cpython/pull/20872

___
Python tracker 

___
___
Python-bugs-list mailing list
Unsubscribe: 
https://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com



[issue41077] Make Cookiejar a bit more pythonic

2020-06-22 Thread శ్రీనివాస్ రెడ్డి తాటిపర్తి

New submission from Srinivas  Reddy Thatiparthy(శ్రీనివాస్ రెడ్డి తాటిపర్తి) 
:

Title says it all.

--
messages: 372087
nosy: thatiparthy
priority: normal
severity: normal
status: open
title: Make Cookiejar a  bit more pythonic

___
Python tracker 
<https://bugs.python.org/issue41077>
___
___
Python-bugs-list mailing list
Unsubscribe: 
https://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com



Re: What about idea of making a "Pythonic Lisp"...i.e. a Lisp that more closely resembles the syntax of Python?

2019-09-19 Thread Chris Angelico
On Fri, Sep 20, 2019 at 5:16 AM Cecil Westerhof  wrote:
>
> Paul Rubin  writes:
>
> > Python 3.7.3 (default, Apr  3 2019, 05:39:12)
> > Type "help", "copyright", "credits" or "license" for more information.
> > >>> a = range(10)
> > >>> b = reversed(a)
> > >>> sum(a) == sum(b)
> > True
> > >>> sum(b) == sum(a)
> > False
>
> Why does this happen?
>
> By the way, when you change the last statement to:
> sum(a) == sum(b)
>
> you also get False.

>>> sum(range(10)) == sum(reversed(range(10)))
True

If you actually want a reversed range, use slice notation instead of
the reversed() function, which is more parallel to iter().

>>> a = range(10)
>>> b = a[::-1]
>>> sum(a) == sum(b)
True
>>> sum(b) == sum(a)
True

Now you actually have a range that runs the other direction, instead
of an iterator that runs through the range backwards.

ChrisA
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: What about idea of making a "Pythonic Lisp"...i.e. a Lisp that more closely resembles the syntax of Python?

2019-09-19 Thread Cecil Westerhof
Paul Rubin  writes:

> Python 3.7.3 (default, Apr  3 2019, 05:39:12)
> Type "help", "copyright", "credits" or "license" for more information.
> >>> a = range(10)
> >>> b = reversed(a)
> >>> sum(a) == sum(b)
> True
> >>> sum(b) == sum(a)
> False

Why does this happen?

By the way, when you change the last statement to:
sum(a) == sum(b)

you also get False.

-- 
Cecil Westerhof
Senior Software Engineer
LinkedIn: http://www.linkedin.com/in/cecilwesterhof
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: What about idea of making a "Pythonic Lisp"...i.e. a Lisp that more closely resembles the syntax of Python?

2019-09-15 Thread Morten W. Petersen
goto main;

Blogging at http://blogologue.com
Tweeting at https://twitter.com/blogologue
On Instagram https://instagram.com/morphexx

søn. 15. sep. 2019, 03.07 skrev Christian Seberino :

> Python is my goto main language.  However, sometimes I'm tempted to
> play with a Lisp like language just for fun.
>
> Clojure looks pretty solid but its syntax is different than Python's.
>
> Since Lisp's make it so easy to modify the language, what about the idea
> of developing a few macros to make a modified Clojure dialect that
> more closely matched Python keywords and so was more comfy for Pythonistas?
>
> Chris
> --
> https://mail.python.org/mailman/listinfo/python-list
>
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: What about idea of making a "Pythonic Lisp"...i.e. a Lisp that more closely resembles the syntax of Python?

2019-09-15 Thread Michael Torrie
On 9/15/19 9:10 AM, Christian Seberino wrote:
> Say if I may ask a tangential question...I've always wondered whether it 
> would be not too hard to compile Python source code to a Lisp like source 
> code?  How hard would it be to say compile Python source to Clojure source?

I'm sure a compiler could take a non-dynamic subset of Python and
transpile it into another language. Or you could implement an
interpreter in Clojure.

A project called Nuitka turns Python code into a compiled binary. I'm
not quite sure how it works since the dynamic parts of Python have to be
interpreted at runtime still.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: What about idea of making a "Pythonic Lisp"...i.e. a Lisp that more closely resembles the syntax of Python?

2019-09-15 Thread Luciano Ramalho
Take a look at this, Christian:

https://github.com/lihaoyi/macropy

Best,

Luciano

On Sun, Sep 15, 2019 at 12:17 PM Christian Seberino  wrote:
>
>
> > I had to read this twice.  It confused the hell out of me.
>
> Lol.  Certainly didn't mean to be confusing!  Hy bring Lisp to Python.  I was
> more interested in making a Lisp that had trivial similarities to Python like 
> using some of the same keywords.
>
> A related interested of mine is converting Python source code to Clojure 
> source.  Imagine instead compiling Python source to an intermediate Lisp 
> flavor that was closer to Python.  Then, later converting that "Pythonic 
> Lisp" to Clojure later.  That "Pythonic Lisp" is what I was thinking about.
>
> Cheers,
>
> Chris
>
> --
> https://mail.python.org/mailman/listinfo/python-list



-- 
Luciano Ramalho
|  Author of Fluent Python (O'Reilly, 2015)
| http://shop.oreilly.com/product/0636920032519.do
|  Technical Principal at ThoughtWorks
|  Twitter: @ramalhoorg
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: What about idea of making a "Pythonic Lisp"...i.e. a Lisp that more closely resembles the syntax of Python?

2019-09-15 Thread Christian Seberino
> Python vs Clojure's syntax difference is superficial compared to their
> other differences, like the Clojure's immutable data structures and
> having to deal with the JVM.

Well there's ClojureScript to run this hypothetical Pythonic Lisp in the 
browser.

> I also don't think it's really practical
> to Pythonize Lisp syntax using macros as opposed to using Lisp as a
> compiler backend for something with a non-Lisp syntax.

Say if I may ask a tangential question...I've always wondered whether it would 
be not too hard to compile Python source code to a Lisp like source code?  How 
hard would it be to say compile Python source to Clojure source?

cs
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: What about idea of making a "Pythonic Lisp"...i.e. a Lisp that more closely resembles the syntax of Python?

2019-09-15 Thread Christian Seberino


> I had to read this twice.  It confused the hell out of me.

Lol.  Certainly didn't mean to be confusing!  Hy bring Lisp to Python.  I was
more interested in making a Lisp that had trivial similarities to Python like 
using some of the same keywords.

A related interested of mine is converting Python source code to Clojure 
source.  Imagine instead compiling Python source to an intermediate Lisp flavor 
that was closer to Python.  Then, later converting that "Pythonic Lisp" to 
Clojure later.  That "Pythonic Lisp" is what I was thinking about.

Cheers,

Chris

-- 
https://mail.python.org/mailman/listinfo/python-list


Re: What about idea of making a "Pythonic Lisp"...i.e. a Lisp that more closely resembles the syntax of Python?

2019-09-15 Thread Michael Torrie
On 9/14/19 8:19 PM, Louis Valence wrote:
> I had to read this twice.  It confused the hell out of me.  Anyhow, I
> suppose you should take a look at
> 
>   https://github.com/hylang/hy

Yup that's probably exactly the opposite of what the OP was asking
about.  Neat, though.


-- 
https://mail.python.org/mailman/listinfo/python-list


Re: What about idea of making a "Pythonic Lisp"...i.e. a Lisp that more closely resembles the syntax of Python?

2019-09-14 Thread Louis Valence
Christian Seberino  writes:

> Python is my goto main language.  However, sometimes I'm tempted to
> play with a Lisp like language just for fun.
>
> Clojure looks pretty solid but its syntax is different than Python's.
>
> Since Lisp's make it so easy to modify the language, what about the idea
> of developing a few macros to make a modified Clojure dialect that
> more closely matched Python keywords and so was more comfy for Pythonistas?

I had to read this twice.  It confused the hell out of me.  Anyhow, I
suppose you should take a look at

  https://github.com/hylang/hy

Enjoy!
-- 
https://mail.python.org/mailman/listinfo/python-list


What about idea of making a "Pythonic Lisp"...i.e. a Lisp that more closely resembles the syntax of Python?

2019-09-14 Thread Christian Seberino
Python is my goto main language.  However, sometimes I'm tempted to
play with a Lisp like language just for fun.

Clojure looks pretty solid but its syntax is different than Python's.

Since Lisp's make it so easy to modify the language, what about the idea
of developing a few macros to make a modified Clojure dialect that
more closely matched Python keywords and so was more comfy for Pythonistas?

Chris
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Pythonic custom multi-line parsers

2019-07-10 Thread Rob Gaddi

On 7/10/19 10:50 AM, Johannes Bauer wrote:

Hi list,

I'm looking for ideas as to a pretty, Pythonic solution for a specific
problem that I am solving over and over but where I'm never happy about
the solution in the end. It always works, but never is pretty. So see
this as an open-ended brainstorming question.

Here's the task: There's a custom file format. Each line can be parsed
individually and, given the current context, the meaning of each
individual line is always clearly distinguishable. I'll give an easy
example to demonstrate:


moo = koo
bar = foo
foo :=
abc
def
baz = abc

Let's say the root context knows only two regexes and give them names:

keyvalue: \w+ = \w+
start-multiblock: \w+ :=

The keyvalue is contained in itself, when the line is successfully
parsed all the information is present. The start-multiblock however
gives us only part of the puzzle, namely the name of the following
block. In the multiblock context, there's different regexes that can
happen (actually only one):

multiblock-item: \s\w+

Now obviously whe the block is finished, there's no delimiter. It's
implicit by the multiblock-item regex not matching and therefore we
backtrack to the previous parser (root parser) and can successfully
parse the last line baz = abc.

Especially consider that even though this is a simple example, generally
you'll have multiple contexts, many more regexes and especially nesting
inside these contexts.

Without having to use a parser generator (for those the examples I deal
with are usually too much overhead) what I usually end up doing is
building a state machine by hand. I.e., I memorize the context, match
those and upon no match manually delegate the input data to backtracked
matchers.

This results in AWFULLY ugly code. I'm wondering what your ideas are to
solve this neatly in a Pythonic fashion without having to rely on
third-party dependencies.

Cheers,
Joe



That's pretty much what I do.  I generally make the parser a class and each 
state a method.  Every line the parser takes out of the file it passes to 
self.statefn, which processes the line in the current context and updates 
self.statefn to a different method if necessary.


--
Rob Gaddi, Highland Technology -- www.highlandtechnology.com
Email address domain is currently out of order.  See above to fix.
--
https://mail.python.org/mailman/listinfo/python-list


Pythonic custom multi-line parsers

2019-07-10 Thread Johannes Bauer
Hi list,

I'm looking for ideas as to a pretty, Pythonic solution for a specific
problem that I am solving over and over but where I'm never happy about
the solution in the end. It always works, but never is pretty. So see
this as an open-ended brainstorming question.

Here's the task: There's a custom file format. Each line can be parsed
individually and, given the current context, the meaning of each
individual line is always clearly distinguishable. I'll give an easy
example to demonstrate:


moo = koo
bar = foo
foo :=
   abc
   def
baz = abc

Let's say the root context knows only two regexes and give them names:

keyvalue: \w+ = \w+
start-multiblock: \w+ :=

The keyvalue is contained in itself, when the line is successfully
parsed all the information is present. The start-multiblock however
gives us only part of the puzzle, namely the name of the following
block. In the multiblock context, there's different regexes that can
happen (actually only one):

multiblock-item: \s\w+

Now obviously whe the block is finished, there's no delimiter. It's
implicit by the multiblock-item regex not matching and therefore we
backtrack to the previous parser (root parser) and can successfully
parse the last line baz = abc.

Especially consider that even though this is a simple example, generally
you'll have multiple contexts, many more regexes and especially nesting
inside these contexts.

Without having to use a parser generator (for those the examples I deal
with are usually too much overhead) what I usually end up doing is
building a state machine by hand. I.e., I memorize the context, match
those and upon no match manually delegate the input data to backtracked
matchers.

This results in AWFULLY ugly code. I'm wondering what your ideas are to
solve this neatly in a Pythonic fashion without having to rely on
third-party dependencies.

Cheers,
Joe
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Most "pythonic" syntax to use for an API client library

2019-05-14 Thread Dotan Cohen
I highly recommend going with the last approach. With the last
approach you can pass around objects in proper OOP fashion. This will
be familiar to most contributors to your project and most devs that
you hire.

foo = api.customers(1)

if bar==baz:
foo.update(Name='Leroy')
else:
foo.delete()


On Mon, Apr 29, 2019 at 4:43 AM Jonathan Leroy - Inikup via
Python-list  wrote:
>
> Hi all,
>
> I'm writing a client library for a REST API. The API endpoints looks like 
> this:
> /customers
> /customers/1
> /customers/1/update
> /customers/1/delete
>
> Which of the following syntax do you expect an API client library to
> use, and why?
>
> 1/
> api.customers_list()
> api.customers_info(1)
> api.customers_update(1, name='Bob')
> api.customers_delete(1)
>
> 2/
> api.customers.list()
> api.customers.info(1)
> api.customers.update(1, name='Bob')
> api.customers.delete(1)
>
> 3/
> api.customers.list()
> api.customers(1).info()
> api.customers(1).update(name='Bob')
> api.customers(1).delete()
>
> ...any other?
>
> #3 seems to be more "pretty" to me, but I did not find any "official"
> recommendation online.
>
> Thanks.
>
> --
> Jonathan.
> --
> https://mail.python.org/mailman/listinfo/python-list



-- 
Dotan Cohen

http://gibberish.co.il
http://what-is-what.com
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Most "pythonic" syntax to use for an API client library

2019-05-14 Thread Jonathan Leroy - Inikup via Python-list
Le dim. 28 avr. 2019 à 20:58, Jonathan Leroy - Inikup
 a écrit :
> Which of the following syntax do you expect an API client library to
> use, and why?

Thank you all for your feedbacks!
I will go with #2.


Le lun. 29 avr. 2019 à 05:43, DL Neil  a écrit :
> Doesn't the framework you are using have its own preference?

I'm using no framework, only pure Python.

-- 
Jonathan Leroy
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Most "pythonic" syntax to use for an API client library

2019-04-30 Thread Thomas Jollans
On 30/04/2019 09.52, Peter Otten wrote:
> Thomas Jollans wrote:
> 
>> On 29/04/2019 09.18, Peter Otten wrote:
>>> Jonathan Leroy - Inikup via Python-list wrote:
>>> alice.name = "Bob"  # __setattr__
>>>
>>> del customers[42]  # __delitem__
>>
>> do you want this sort of thing to update the upstream database directly?
> 
> I thought so. However, you have to answer this question no matter which of 
> the suggested APIs you choose.

True, but with a .update(key=value, ...) method (which takes multiple
kwargs) you don't have the potential issue of more requests than
necessary if you're updating multiple fields.

> 
>> Maybe there should be a commit() method on every object. Maybe not.
> 
> I originally had
> 
> db = api.connect(...)
> customers = db.customers
> 
> but then decided this was out of scope for the question. It would however 
> allow
> 
> with db:
> ...  # modify db
> # implicit commit, or rollback on exception
> 
>> I imagine it would be best if the data is cached locally (i.e. alice =
>> customers[1] does a query, print(alice.name) does not). In this case you
>> probably want the local/database separation to be consistent for both
>> getting and setting things.
> 
> That looks like a lot of work, with the potential to introduce additional 
> inconsistencies. But there's probably prior art.
> 
> How do ORMs like SQLObject handle this?

It's been a while, but I'm pretty sure the Django ORM at least has
caching everywhere.

>  
>>> del customers[alice]
>>
>> Are you sure about this?
> 
> On a scale from one to ten? Yes ;)
> 
 #3 seems to be more "pretty" to me, but I did not find any "official"
 recommendation online.
>>
>> I'd like #3 if it had square brackets after .customers. Of the
>> suggestions as they are I prefer #2.
> 
> 

-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Most "pythonic" syntax to use for an API client library

2019-04-30 Thread Peter Otten
Thomas Jollans wrote:

> On 29/04/2019 09.18, Peter Otten wrote:
>> Jonathan Leroy - Inikup via Python-list wrote:
>> 
>>> Hi all,
>>>
>>> I'm writing a client library for a REST API. The API endpoints looks
>>> like this: /customers
>>> /customers/1
>>> /customers/1/update
>>> /customers/1/delete
>>>
>>> Which of the following syntax do you expect an API client library to
>>> use, and why?
>>>
>>> 1/
>>> api.customers_list()
>>> api.customers_info(1)
>>> api.customers_update(1, name='Bob')
>>> api.customers_delete(1)
>>>
>>> 2/
>>> api.customers.list()
>>> api.customers.info(1)
>>> api.customers.update(1, name='Bob')
>>> api.customers.delete(1)
>>>
>>> 3/
>>> api.customers.list()
>>> api.customers(1).info()
>>> api.customers(1).update(name='Bob')
>>> api.customers(1).delete()
>>>
>>> ...any other?
>> 
>> How about mimicking (to some extent) an existing interface, like a list,
>> dict, or set:
>> 
>> customers = api.customers
>> 
>> list(customers)  # __iter__
>> 
>> alice = customers[1]  # __getitem__
>> 
>> print(alice)  # __str__
> 
> This was my first thought seeing the third option as well, but...
> 
>> 
>> alice.name = "Bob"  # __setattr__
>> 
>> del customers[42]  # __delitem__
> 
> do you want this sort of thing to update the upstream database directly?

I thought so. However, you have to answer this question no matter which of 
the suggested APIs you choose.

> Maybe there should be a commit() method on every object. Maybe not.

I originally had

db = api.connect(...)
customers = db.customers

but then decided this was out of scope for the question. It would however 
allow

with db:
...  # modify db
# implicit commit, or rollback on exception

> I imagine it would be best if the data is cached locally (i.e. alice =
> customers[1] does a query, print(alice.name) does not). In this case you
> probably want the local/database separation to be consistent for both
> getting and setting things.

That looks like a lot of work, with the potential to introduce additional 
inconsistencies. But there's probably prior art.

How do ORMs like SQLObject handle this?
 
>> del customers[alice]
> 
> Are you sure about this?

On a scale from one to ten? Yes ;)

>>> #3 seems to be more "pretty" to me, but I did not find any "official"
>>> recommendation online.
> 
> I'd like #3 if it had square brackets after .customers. Of the
> suggestions as they are I prefer #2.


-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Most "pythonic" syntax to use for an API client library

2019-04-29 Thread Thomas Jollans
On 29/04/2019 09.18, Peter Otten wrote:
> Jonathan Leroy - Inikup via Python-list wrote:
> 
>> Hi all,
>>
>> I'm writing a client library for a REST API. The API endpoints looks like
>> this: /customers
>> /customers/1
>> /customers/1/update
>> /customers/1/delete
>>
>> Which of the following syntax do you expect an API client library to
>> use, and why?
>>
>> 1/
>> api.customers_list()
>> api.customers_info(1)
>> api.customers_update(1, name='Bob')
>> api.customers_delete(1)
>>
>> 2/
>> api.customers.list()
>> api.customers.info(1)
>> api.customers.update(1, name='Bob')
>> api.customers.delete(1)
>>
>> 3/
>> api.customers.list()
>> api.customers(1).info()
>> api.customers(1).update(name='Bob')
>> api.customers(1).delete()
>>
>> ...any other?
> 
> How about mimicking (to some extent) an existing interface, like a list, 
> dict, or set:
> 
> customers = api.customers
> 
> list(customers)  # __iter__
> 
> alice = customers[1]  # __getitem__
> 
> print(alice)  # __str__

This was my first thought seeing the third option as well, but...

> 
> alice.name = "Bob"  # __setattr__
> 
> del customers[42]  # __delitem__

do you want this sort of thing to update the upstream database directly?
Maybe there should be a commit() method on every object. Maybe not.

I imagine it would be best if the data is cached locally (i.e. alice =
customers[1] does a query, print(alice.name) does not). In this case you
probably want the local/database separation to be consistent for both
getting and setting things.

> del customers[alice]

Are you sure about this?

> 
>> #3 seems to be more "pretty" to me, but I did not find any "official"
>> recommendation online.

I'd like #3 if it had square brackets after .customers. Of the
suggestions as they are I prefer #2.

-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Most "pythonic" syntax to use for an API client library

2019-04-29 Thread Peter Otten
Jonathan Leroy - Inikup via Python-list wrote:

> Hi all,
> 
> I'm writing a client library for a REST API. The API endpoints looks like
> this: /customers
> /customers/1
> /customers/1/update
> /customers/1/delete
> 
> Which of the following syntax do you expect an API client library to
> use, and why?
> 
> 1/
> api.customers_list()
> api.customers_info(1)
> api.customers_update(1, name='Bob')
> api.customers_delete(1)
> 
> 2/
> api.customers.list()
> api.customers.info(1)
> api.customers.update(1, name='Bob')
> api.customers.delete(1)
> 
> 3/
> api.customers.list()
> api.customers(1).info()
> api.customers(1).update(name='Bob')
> api.customers(1).delete()
> 
> ...any other?

How about mimicking (to some extent) an existing interface, like a list, 
dict, or set:

customers = api.customers

list(customers)  # __iter__

alice = customers[1]  # __getitem__

print(alice)  # __str__

alice.name = "Bob"  # __setattr__

del customers[42]  # __delitem__
del customers[alice]

> #3 seems to be more "pretty" to me, but I did not find any "official"
> recommendation online.
> 
> Thanks.
> 
> --
> Jonathan.


-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Most "pythonic" syntax to use for an API client library

2019-04-29 Thread Albert-Jan Roskam



On 29 Apr 2019 07:18, DL Neil  wrote:

On 29/04/19 4:52 PM, Chris Angelico wrote:
> On Mon, Apr 29, 2019 at 2:43 PM DL Neil  
> wrote:
>>
>> On 29/04/19 3:55 PM, Chris Angelico wrote:
>>> On Mon, Apr 29, 2019 at 1:43 PM DL Neil  
>>> wrote:
 Well, seeing you ask: a more HTTP-ish approach *might* be:

 api.update.customer( 1, name='Bob' )

 ie
 api.verb.subject( adjectives and adverbs )

 Thus:
 api_label/intro/ID.what_we're_going_to_do.who/what_we'll_do_it_to(
 customerID, support_data)

 Yet, it doesn't really *look right* does it?
 (and someone might complain about mixing the 'different' 
 variable-values...)

>>>
>>> The point here is not to make an HTTP-like interface, but a
>>> Python-like interface :)
>>

I recently used Python properties (getter, setter, deleter) for GET, POST/PUT, 
DELETE, respectively. I didn't need any other http methods.


-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Most "pythonic" syntax to use for an API client library

2019-04-28 Thread DL Neil

On 29/04/19 4:52 PM, Chris Angelico wrote:

On Mon, Apr 29, 2019 at 2:43 PM DL Neil  wrote:


On 29/04/19 3:55 PM, Chris Angelico wrote:

On Mon, Apr 29, 2019 at 1:43 PM DL Neil  wrote:

Well, seeing you ask: a more HTTP-ish approach *might* be:

api.update.customer( 1, name='Bob' )

ie
api.verb.subject( adjectives and adverbs )

Thus:
api_label/intro/ID.what_we're_going_to_do.who/what_we'll_do_it_to(
customerID, support_data)

Yet, it doesn't really *look right* does it?
(and someone might complain about mixing the 'different' variable-values...)



The point here is not to make an HTTP-like interface, but a
Python-like interface :)


OK, I'll bite...

...shouldn't the Python-like interface reflect what it is wrapping?


It should. But if you just want an HTTP-like interface, you don't
really need much of a wrapper. All you need is a hyperthin wrapper
around the requests library - something like:

api.post("customer", {...})
api.get("customer", 1)
api.patch("customer", 1, {...})

And that's fine if what you want is HTTP. But if you want something a
bit more Pythonic, you want something that more adequately represents
the underlying concepts, not the intermediate transport layer. In this
case, the concepts are customers (and, presumably, other types of
queryable information), and the things you can do with them (get info,
update info, enumerate, create).

There may be some useful inspiration to be gained from looking at database ORMs.



Yes. I certainly read "thin" into the OP - see also your own comment 
earlier re: "metaprogramming model", which presumed a likelihood of 'more'.


Once bring ORMs, etc, into the equation, then (and depending upon the 
selected tool), recommend maintaining a consistency* to avoid future 
reader-confusion/cognitive-load.


* "hobgoblins" of the world unite!

(having just unravelled some poor soul's vacillation about whether 'it' 
is "width" before "height" or v-v; who then doubled-down by falling into 
the 'where is this-package's Cartesian origin' confusion, aka in which 
direction does *this* y-axis flow?)

--
Regards =dn
--
https://mail.python.org/mailman/listinfo/python-list


Re: Most "pythonic" syntax to use for an API client library

2019-04-28 Thread Chris Angelico
On Mon, Apr 29, 2019 at 2:43 PM DL Neil  wrote:
>
> On 29/04/19 3:55 PM, Chris Angelico wrote:
> > On Mon, Apr 29, 2019 at 1:43 PM DL Neil  
> > wrote:
> >> Well, seeing you ask: a more HTTP-ish approach *might* be:
> >>
> >> api.update.customer( 1, name='Bob' )
> >>
> >> ie
> >> api.verb.subject( adjectives and adverbs )
> >>
> >> Thus:
> >> api_label/intro/ID.what_we're_going_to_do.who/what_we'll_do_it_to(
> >> customerID, support_data)
> >>
> >> Yet, it doesn't really *look right* does it?
> >> (and someone might complain about mixing the 'different' 
> >> variable-values...)
> >>
> >
> > The point here is not to make an HTTP-like interface, but a
> > Python-like interface :)
>
> OK, I'll bite...
>
> ...shouldn't the Python-like interface reflect what it is wrapping?

It should. But if you just want an HTTP-like interface, you don't
really need much of a wrapper. All you need is a hyperthin wrapper
around the requests library - something like:

api.post("customer", {...})
api.get("customer", 1)
api.patch("customer", 1, {...})

And that's fine if what you want is HTTP. But if you want something a
bit more Pythonic, you want something that more adequately represents
the underlying concepts, not the intermediate transport layer. In this
case, the concepts are customers (and, presumably, other types of
queryable information), and the things you can do with them (get info,
update info, enumerate, create).

There may be some useful inspiration to be gained from looking at database ORMs.

ChrisA
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Most "pythonic" syntax to use for an API client library

2019-04-28 Thread DL Neil

On 29/04/19 3:55 PM, Chris Angelico wrote:

On Mon, Apr 29, 2019 at 1:43 PM DL Neil  wrote:

Well, seeing you ask: a more HTTP-ish approach *might* be:

api.update.customer( 1, name='Bob' )

ie
api.verb.subject( adjectives and adverbs )

Thus:
api_label/intro/ID.what_we're_going_to_do.who/what_we'll_do_it_to(
customerID, support_data)

Yet, it doesn't really *look right* does it?
(and someone might complain about mixing the 'different' variable-values...)



The point here is not to make an HTTP-like interface, but a
Python-like interface :)


OK, I'll bite...

...shouldn't the Python-like interface reflect what it is wrapping?


(says he, wrestling with the Kraken and cv2. G!)
--
Regards =dn
--
https://mail.python.org/mailman/listinfo/python-list


Re: Most "pythonic" syntax to use for an API client library

2019-04-28 Thread Chris Angelico
On Mon, Apr 29, 2019 at 1:43 PM DL Neil  wrote:
> Well, seeing you ask: a more HTTP-ish approach *might* be:
>
> api.update.customer( 1, name='Bob' )
>
> ie
> api.verb.subject( adjectives and adverbs )
>
> Thus:
> api_label/intro/ID.what_we're_going_to_do.who/what_we'll_do_it_to(
> customerID, support_data)
>
> Yet, it doesn't really *look right* does it?
> (and someone might complain about mixing the 'different' variable-values...)
>

The point here is not to make an HTTP-like interface, but a
Python-like interface :)

ChrisA
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Most "pythonic" syntax to use for an API client library

2019-04-28 Thread DL Neil

On 29/04/19 6:58 AM, Jonathan Leroy - Inikup via Python-list wrote:

1/
api.customers_list()
api.customers_info(1)
api.customers_update(1, name='Bob')
api.customers_delete(1)


Dislike this because it mixes point and underscore - easy to mistake!



2/
api.customers.list()
api.customers.info(1)
api.customers.update(1, name='Bob')
api.customers.delete(1)


Prefer this because it 'fits' with module/class notations.



3/
api.customers.list()
api.customers(1).info()
api.customers(1).update(name='Bob')
api.customers(1).delete()


Hate this because it identifies the subject (customers), then requires 
customerID (I presume), then states the action, finally we add any 
adverb(s). In some respects, preference for grouping the two (most) 
variable-items.




...any other?


Well, seeing you ask: a more HTTP-ish approach *might* be:

api.update.customer( 1, name='Bob' )

ie
api.verb.subject( adjectives and adverbs )

Thus:
api_label/intro/ID.what_we're_going_to_do.who/what_we'll_do_it_to( 
customerID, support_data)


Yet, it doesn't really *look right* does it?
(and someone might complain about mixing the 'different' variable-values...)


Doesn't the framework you are using have its own preference?
--
Regards =dn
--
https://mail.python.org/mailman/listinfo/python-list


Re: Most "pythonic" syntax to use for an API client library

2019-04-28 Thread Chris Angelico
On Mon, Apr 29, 2019 at 11:44 AM Jonathan Leroy - Inikup via
Python-list  wrote:
>
> Hi all,
>
> I'm writing a client library for a REST API. The API endpoints looks like 
> this:
> /customers
> /customers/1
> /customers/1/update
> /customers/1/delete
>
> Which of the following syntax do you expect an API client library to
> use, and why?
>
> 1/
> api.customers_list()
> api.customers_info(1)
> api.customers_update(1, name='Bob')
> api.customers_delete(1)
>
> 2/
> api.customers.list()
> api.customers.info(1)
> api.customers.update(1, name='Bob')
> api.customers.delete(1)
>
> 3/
> api.customers.list()
> api.customers(1).info()
> api.customers(1).update(name='Bob')
> api.customers(1).delete()
>
> ...any other?
>
> #3 seems to be more "pretty" to me, but I did not find any "official"
> recommendation online.
>

Well, it's pretty much up to you; all three of these are reasonable.
I'd base a decision on what "api.customers(1)" would mean. Would that
actually have meaning, or would it be merely a placeholder that
remembers "whatever operation you do, do it to customer 1"? If the
latter, I would be inclined to go with option 2, as it clearly shows
that there will be exactly one API call triggered by that. Also,
option 2 lends itself well to a metaprogramming model, where you can
create a "customers" object, a "documents" object, a "transactions"
object, etc, etc, etc, all from the same class, eg via subclassing
(unless they are SO simple that they can all be completely generic).

ChrisA
-- 
https://mail.python.org/mailman/listinfo/python-list


Most "pythonic" syntax to use for an API client library

2019-04-28 Thread Jonathan Leroy - Inikup via Python-list
Hi all,

I'm writing a client library for a REST API. The API endpoints looks like this:
/customers
/customers/1
/customers/1/update
/customers/1/delete

Which of the following syntax do you expect an API client library to
use, and why?

1/
api.customers_list()
api.customers_info(1)
api.customers_update(1, name='Bob')
api.customers_delete(1)

2/
api.customers.list()
api.customers.info(1)
api.customers.update(1, name='Bob')
api.customers.delete(1)

3/
api.customers.list()
api.customers(1).info()
api.customers(1).update(name='Bob')
api.customers(1).delete()

...any other?

#3 seems to be more "pretty" to me, but I did not find any "official"
recommendation online.

Thanks.

--
Jonathan.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: more pythonic way

2019-02-16 Thread Grant Edwards
On 2019-02-16, Barry  wrote:
> On 11 Feb 2019, at 20:00, Felix Lazaro Carbonell  wrote:
>
>>> The most pythonic way is to do this:
>>> 
>>> def find_monthly_expenses(month=datetime.date.today().month,
>> year=datetime.date.today().year):
>>>...
>
> This has subtle bugs. 
> The default is calculated at import time and not at function call time.

Indeed.  That was the entire point of that posting: it was an example
of a not-uncommon misunderstanding about when intializer values are
determined.  Unfortunately the subsequent remark about initializers
not working that way has been lost in the shuffle.

> Also the defaults for month and year are not calculated at the same
> moment in time.

Yep.  The race condition between the evaluation of the two initializer
expressions is a bit more subtle than the fact that the evaluations
only happen once at compile time.

-- 
Grant


-- 
https://mail.python.org/mailman/listinfo/python-list


Re: more pythonic way

2019-02-16 Thread Barry



On 11 Feb 2019, at 20:00, Felix Lazaro Carbonell  wrote:

>> The most pythonic way is to do this:
>> 
>> def find_monthly_expenses(month=datetime.date.today().month,
> year=datetime.date.today().year):
>>...

This has subtle bugs. 
The default is calculated at import time and not at function call time.
Also the defaults for month and year are not calculated at the same moment in 
time.

Import at 23:59:59.99 on 31 december 2018 and you might get
month as 12 and year as 2019.

Run this example to see the problem:

import datetime
import time

def test_defaults(prefix, now=datetime.datetime.now()):
print( prefix, now )

test_defaults('one')
time.sleep( 1 )
test_defaults('two')
time.sleep( 1 )
test_defaults('three', datetime.datetime.now())

Which outputs:

one 2019-02-16 08:30:54.819466
two 2019-02-16 08:30:54.819466
three 2019-02-16 08:30:56.821453

Notice that the time for 'one' and 'two' is the same.
Only the overridden default chanse.

Barry

-- 
https://mail.python.org/mailman/listinfo/python-list


Re: more pythonic way

2019-02-11 Thread Jimmy Girardet
The first one is used very often. Less verbose

Le 11 févr. 2019 à 20:41, à 20:41, Felix Lazaro Carbonell 
 a écrit:
> 
>
>Hello to everyone:
>
>Could you please tell me wich way of writing this method is more
>pythonic:
>
> 
>
>..
>
>def find_monthly_expenses(month=None, year=None):
>
>month = month or datetime.date.today()
>
>..
>
> 
>
>Or it should better be:
>
>...
>
>if not month:
>
>month = datetime.date.today()
>
>..
>
> 
>
>Cheers,
>
>Felix.
>
> 
>
>-- 
>https://mail.python.org/mailman/listinfo/python-list
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: more pythonic way

2019-02-11 Thread Peter Otten
Felix Lazaro Carbonell wrote:

> Hello to everyone:

 
> Could you please tell me wich way of writing this method is more pythonic:
> def find_monthly_expenses(month=None, year=None):
> 
> month = month or datetime.date.today()

> Or it should better be:

> if not month:
> month = datetime.date.today()

Personally I would avoid a default because I'm unsure whether the current or 
the previous month is the right default. 

Also, the default month combined with a specific year doesn't make much 
sense to me, and someone who specifies find_monthly_expenses(month=6) in May 
probably wants the June of the past year...

Keep the function simple an make the arguments non-optional. If you can come 
up with a nice heuristic put it in a separate function.

-- 
https://mail.python.org/mailman/listinfo/python-list


Re: more pythonic way

2019-02-11 Thread Peter Otten
Grant Edwards wrote:

> On 2019-02-11, Felix Lazaro Carbonell  wrote:
> 
>> Could you please tell me wich way of writing this method is more
>> pythonic:
>>
>> def find_monthly_expenses(month=None, year=None):
>> month = month or datetime.date.today()
>>
>> Or it should better be:
>>
>> if not month:
>> month = datetime.date.today()
> 
> The most pythonic way is to do this:
> 
>def find_monthly_expenses(month=datetime.date.today().month,
>year=datetime.date.today().year):
>   ...
> 
> And then start a month-long argument on the mailing list about how the
> behavior of parameter default values is wrong and needs be changed.
> 
> ;)
> 

As far as arguments go I was thinking more about how this code can try and 
find the december expenses when it's only january ;)

-- 
https://mail.python.org/mailman/listinfo/python-list


Re: more pythonic way

2019-02-11 Thread Sivan Grünberg
+1 with David Raymond, it's nice to use condensed style when it leaves
things readable and logic. But if in doubt:
"Explicit is better than implicit.
Simple is better than complex."  :)

-Sivan

On Mon, Feb 11, 2019 at 10:19 PM David Raymond 
wrote:

> My non-expert vote is for
>
> if month is None:
> month = datetime.date.today().month
>
> Because you're checking for your default value, not whether the boolean
> version of what they did give you is True or False. It's explicit, it's not
> reliant on any __bool__() function implementations or overrides, etc.
>
>
> -Original Message-
> From: Python-list [mailto:python-list-bounces+david.raymond=
> tomtom@python.org] On Behalf Of Felix Lazaro Carbonell
> Sent: Monday, February 11, 2019 2:30 PM
> To: python-list@python.org
> Subject: more pythonic way
>
>
>
> Hello to everyone:
>
> Could you please tell me wich way of writing this method is more pythonic:
>
>
>
> ..
>
> def find_monthly_expenses(month=None, year=None):
>
> month = month or datetime.date.today()
>
> ..
>
>
>
> Or it should better be:
>
> ...
>
> if not month:
>
> month = datetime.date.today()
>
> ..
>
>
>
> Cheers,
>
> Felix.
>
>
>
> --
> https://mail.python.org/mailman/listinfo/python-list
> --
> https://mail.python.org/mailman/listinfo/python-list
>


-- 
Sivan Greenberg
Co founder & CTO
Vitakka Consulting
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: more pythonic way

2019-02-11 Thread Terry Reedy

On 2/11/2019 2:46 PM, Felix Lazaro Carbonell wrote:


 def find_monthly_expenses(month=None, year=None):
 month = month or datetime.date.today().month

Or it should better be:



 if not month:
 month = datetime.date.today().month


As a 20+ year veteran, I would be fine either way.

--
Terry Jan Reedy

--
https://mail.python.org/mailman/listinfo/python-list


RE: more pythonic way

2019-02-11 Thread David Raymond
My non-expert vote is for

if month is None:
month = datetime.date.today().month

Because you're checking for your default value, not whether the boolean version 
of what they did give you is True or False. It's explicit, it's not reliant on 
any __bool__() function implementations or overrides, etc.


-Original Message-
From: Python-list 
[mailto:python-list-bounces+david.raymond=tomtom@python.org] On Behalf Of 
Felix Lazaro Carbonell
Sent: Monday, February 11, 2019 2:30 PM
To: python-list@python.org
Subject: more pythonic way

 

Hello to everyone:

Could you please tell me wich way of writing this method is more pythonic:

 

..

def find_monthly_expenses(month=None, year=None):

month = month or datetime.date.today()

..

 

Or it should better be:

...

if not month:

month = datetime.date.today()

..

 

Cheers,

Felix.

 

-- 
https://mail.python.org/mailman/listinfo/python-list
-- 
https://mail.python.org/mailman/listinfo/python-list


RE: more pythonic way

2019-02-11 Thread Felix Lazaro Carbonell



-Mensaje original-
De: Python-list [mailto:python-list-bounces+felix=epepm.cupet...@python.org]
En nombre de Grant Edwards
Enviado el: lunes, 11 de febrero de 2019 02:46 p.m.
Para: python-list@python.org
Asunto: Re: more pythonic way

On 2019-02-11, Felix Lazaro Carbonell  wrote:

> Could you please tell me wich way of writing this method is more pythonic:
>
> def find_monthly_expenses(month=None, year=None):
> month = month or datetime.date.today()
>
> Or it should better be:
>
> if not month:
> month = datetime.date.today()

>The most pythonic way is to do this:
>
>   def find_monthly_expenses(month=datetime.date.today().month,
year=datetime.date.today().year):
>  ...
>
>And then start a month-long argument on the mailing list about how the
behavior of parameter default values is wrong and needs be changed.
>
>;)
>
>-- 
>Grant Edwards   grant.b.edwardsYow! I always have fun
>  at   because I'm out of my
>  gmail.commind!!!
>
>--

Thanks Grant:

 but now I think I should have mentioned that this is a method in a Django
model, and default arguments are evaluated once when the method is defined,
not each time the method is called.
So, your way, wil yield the date when Django was started and not the date in
wich this method is called, and the date I intend to get is the one when the
method is called. I think that I shouldn't call datetime.date.today() as a
default value for the method's parameters.

Cheers,
Felix.

-- 
https://mail.python.org/mailman/listinfo/python-list


RE: more pythonic way

2019-02-11 Thread Felix Lazaro Carbonell
Sorry I meant 
 

..

def find_monthly_expenses(month=None, year=None):

month = month or datetime.date.today().month

..
 

Or it should better be:

...

if not month:

month = datetime.date.today().month

..
 

Cheers,

Felix.

 
-- 
https://mail.python.org/mailman/listinfo/python-list

-- 
https://mail.python.org/mailman/listinfo/python-list


Re: more pythonic way

2019-02-11 Thread Grant Edwards
On 2019-02-11, Felix Lazaro Carbonell  wrote:

> Could you please tell me wich way of writing this method is more pythonic:
>
> def find_monthly_expenses(month=None, year=None):
> month = month or datetime.date.today()
>
> Or it should better be:
>
> if not month:
> month = datetime.date.today()

The most pythonic way is to do this:

   def find_monthly_expenses(month=datetime.date.today().month, 
year=datetime.date.today().year):
  ...

And then start a month-long argument on the mailing list about how the
behavior of parameter default values is wrong and needs be changed.

;)

-- 
Grant Edwards   grant.b.edwardsYow! I always have fun
  at   because I'm out of my
  gmail.commind!!!

-- 
https://mail.python.org/mailman/listinfo/python-list


more pythonic way

2019-02-11 Thread Felix Lazaro Carbonell
 

Hello to everyone:

Could you please tell me wich way of writing this method is more pythonic:

 

..

def find_monthly_expenses(month=None, year=None):

month = month or datetime.date.today()

..

 

Or it should better be:

...

if not month:

month = datetime.date.today()

..

 

Cheers,

Felix.

 

-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Pythonic Y2K

2019-01-18 Thread Rich Shepard

On Fri, 18 Jan 2019, Gene Heskett wrote:


I had one client, a hedge fund, that I fixed literally 1000's of Y2K
issues for. When Y2K came and there were no problems, the owner said
to me "You made such a big deal about the Y2K thing, and nothing
happened." --



I would quite cheerfully have bought a ticket to watch and hear your
reply, Larry.


My response would have been, "That's because of all the time and effort I
devoted to fixing all the issues that would have put you out of business.
Perhaps a bonus is due me?"

This is a common situation for all consultants, including environmental
scientists such as I am. Clients don't know how to fix the problems they
face, nor have that capability in-house, so they need external assistance.
This lack of knowledge means they don't understand why the project took so
long nor recognize the effort put in by the consultant.

People tend to take for granted when things work smoothly but notice when
there are glitches. Ask any major conference or annual meeting director
about this. :-) A similar situation is faced by those of us who are expected
to "prove" a negative.

Carpe weekend, all,

Rich
--
https://mail.python.org/mailman/listinfo/python-list


Re: Pythonic Y2K

2019-01-18 Thread Gene Heskett
On Friday 18 January 2019 16:55:28 Avi Gross wrote:

> Larry,
>
> I keep hearing similar things about the Flu Vaccine. It only works 40%
> of the time or whatever. But most of the people that get the flu get a
> different strain they were not vaccinated against!
>
> There are hundreds of strains out there and by protecting the herd
> against just a few, others will flourish. So was it worth it?
>
> Your argument would be that your work found lots of things related to
> Y2000 that could have been a problem and therefore never got a chance
> to show. I wonder if anyone did a case study and found an organization
> that refused to budge and changed nothing, not even other products
> that were changed like the OS? If such organizations had zero
> problems, that would be interesting. If they had problems and rapidly
> had their software changed or fixed, that would be another and we
> could ask if the relative cost and consequence made such an approach
> cheaper.
>
> But in reality, I suspect that many of the vendors supplying products
> made the change for all their clients. I bet Oracle might have offered
> some combination of new and improved products to replace old ones or
> tools that could be used to say read in a database in one format and
> write it out again with wider date fields.
>
> The vast difference some allude to is realistic. Y2K swept the globe
> in about 24 hours. No easy way to avoid it for many applications.
> Someone running python 2.X on their own machines may be able to
> continue living in their bubble for quite a while. If you sell or
> share a product with python frozen into an app, it makes no
> difference. But asking some clients to maintain multiple copies of
> python set up so one app keeps running as all others use the newer
> one, may not remain a great solution indefinitely.
>
> Has anyone considered something that may be at the edges. How well do
> cooperating programs work together? I mean if program one processes
> and saves some data structures using something like pickle, and
> program two is supposed to read the pickle back in and continue
> processing, then you may get anomalies of many kinds if they use
> different pythons. Similarly, processes that start up other scripts
> and communicate with them, may need to start newer programs that use
> the 3.X or beyond version as no back-ported version exists. The bubble
> may enlarge and may eventually burst.
>
> -Original Message-----
> From: Python-list
>  On Behalf Of
> Larry Martell
> Sent: Friday, January 18, 2019 10:47 AM
> To: Python 
> Subject: Re: Pythonic Y2K
>
> On Fri, Jan 18, 2019 at 10:43 AM Michael Torrie  
wrote:
> > On 01/16/2019 12:02 PM, Avi Gross wrote:
> > > I recall the days before the year 2000 with the Y2K scare when
> > > people worried that legacy software might stop working or do
> > > horrible things once the clock turned. It may even have been scary
> > > enough for some companies to rewrite key applications and even
> > > switch
>
> from languages like COBOL.
>
> > Of course it wasn't just a scare.  The date rollover problem was
> > very real. It's interesting that now we call it the Y2K "scare" and
> > since most things came through that okay we often suppose that the
> > people who were warning about this impending problem were simply
> > being alarmist and prophets of doom.  We often deride them.  But the
> > fact is, people did take these prophets of doom seriously and there
> > was a massive, even heroic effort, to fix a lot of these critical
> > backend systems so that disaster was avoided (just barely).  I'm not
> > talking about PCs rolling over to 00.  I'm talking about banking
> > software, mission critical control software.  It certainly was scary
> > enough for a lot of companies to spend a lot of money rewriting key
> > software. The problem wasn't with COBOL necessarily.
>
> I had one client, a hedge fund, that I fixed literally 1000's of Y2K
> issues for. When Y2K came and there were no problems, the owner said
> to me "You made such a big deal about the Y2K thing, and nothing
> happened." --

I would quite cheerfully have bought a ticket to watch and hear your 
reply, Larry.

Or better yet, silently reached into your briefcase and brought out an 
invoice, listing what and where you patched, and what you would normally 
charge to find and fix each one individually when the gun went off for 
real 36 hours back and his fund was losing 1% an hour.  Sometimes the 
truth shuts them up but theres usually some yelling involved.

> https://mail.python.org/mailman/listinfo/python-list


Cheers, Gene Heskett
-- 
"There are four boxes to be used in defense of liberty:
 soap, ballot, jury, and ammo. Please use in that order."
-Ed Howdershelt (Author)
Genes Web page <http://geneslinuxbox.net:6309/gene>

-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Pythonic Y2K

2019-01-18 Thread Larry Martell
On Fri, Jan 18, 2019 at 4:56 PM Avi Gross  wrote:
>
> Larry,
>
> I keep hearing similar things about the Flu Vaccine. It only works 40% of
> the time or whatever. But most of the people that get the flu get a
> different strain they were not vaccinated against!

That seems like a complete non-sequitur. What does that have to do with Y2K?

But I will tell you something: I've never had a flu vaccine in my life
and I've never had the flu.

And I will tell you something else: I have proof that worrying works -
99% of the things I worry about never happen, so it must work.

And please stop top posting.

> There are hundreds of strains out there and by protecting the herd against
> just a few, others will flourish. So was it worth it?
>
> Your argument would be that your work found lots of things related to Y2000
> that could have been a problem and therefore never got a chance to show. I
> wonder if anyone did a case study and found an organization that refused to
> budge and changed nothing, not even other products that were changed like
> the OS? If such organizations had zero problems, that would be interesting.
> If they had problems and rapidly had their software changed or fixed, that
> would be another and we could ask if the relative cost and consequence made
> such an approach cheaper.
>
> But in reality, I suspect that many of the vendors supplying products made
> the change for all their clients. I bet Oracle might have offered some
> combination of new and improved products to replace old ones or tools that
> could be used to say read in a database in one format and write it out again
> with wider date fields.
>
> The vast difference some allude to is realistic. Y2K swept the globe in
> about 24 hours. No easy way to avoid it for many applications. Someone
> running python 2.X on their own machines may be able to continue living in
> their bubble for quite a while. If you sell or share a product with python
> frozen into an app, it makes no difference. But asking some clients to
> maintain multiple copies of python set up so one app keeps running as all
> others use the newer one, may not remain a great solution indefinitely.
>
> Has anyone considered something that may be at the edges. How well do
> cooperating programs work together? I mean if program one processes and
> saves some data structures using something like pickle, and program two is
> supposed to read the pickle back in and continue processing, then you may
> get anomalies of many kinds if they use different pythons. Similarly,
> processes that start up other scripts and communicate with them, may need to
> start newer programs that use the 3.X or beyond version as no back-ported
> version exists. The bubble may enlarge and may eventually burst.
>
> -Original Message-
> From: Python-list  On
> Behalf Of Larry Martell
> Sent: Friday, January 18, 2019 10:47 AM
> To: Python 
> Subject: Re: Pythonic Y2K
>
> On Fri, Jan 18, 2019 at 10:43 AM Michael Torrie  wrote:
> >
> > On 01/16/2019 12:02 PM, Avi Gross wrote:
> > > I recall the days before the year 2000 with the Y2K scare when
> > > people worried that legacy software might stop working or do
> > > horrible things once the clock turned. It may even have been scary
> > > enough for some companies to rewrite key applications and even switch
> from languages like COBOL.
> >
> > Of course it wasn't just a scare.  The date rollover problem was very
> > real. It's interesting that now we call it the Y2K "scare" and since
> > most things came through that okay we often suppose that the people
> > who were warning about this impending problem were simply being
> > alarmist and prophets of doom.  We often deride them.  But the fact
> > is, people did take these prophets of doom seriously and there was a
> > massive, even heroic effort, to fix a lot of these critical backend
> > systems so that disaster was avoided (just barely).  I'm not talking
> > about PCs rolling over to 00.  I'm talking about banking software,
> > mission critical control software.  It certainly was scary enough for
> > a lot of companies to spend a lot of money rewriting key software.
> > The problem wasn't with COBOL necessarily.
>
> I had one client, a hedge fund, that I fixed literally 1000's of Y2K issues
> for. When Y2K came and there were no problems, the owner said to me "You
> made such a big deal about the Y2K thing, and nothing happened."
-- 
https://mail.python.org/mailman/listinfo/python-list


RE: Pythonic Y2K

2019-01-18 Thread Avi Gross
Larry,

I keep hearing similar things about the Flu Vaccine. It only works 40% of
the time or whatever. But most of the people that get the flu get a
different strain they were not vaccinated against!

There are hundreds of strains out there and by protecting the herd against
just a few, others will flourish. So was it worth it?

Your argument would be that your work found lots of things related to Y2000
that could have been a problem and therefore never got a chance to show. I
wonder if anyone did a case study and found an organization that refused to
budge and changed nothing, not even other products that were changed like
the OS? If such organizations had zero problems, that would be interesting.
If they had problems and rapidly had their software changed or fixed, that
would be another and we could ask if the relative cost and consequence made
such an approach cheaper.

But in reality, I suspect that many of the vendors supplying products made
the change for all their clients. I bet Oracle might have offered some
combination of new and improved products to replace old ones or tools that
could be used to say read in a database in one format and write it out again
with wider date fields. 

The vast difference some allude to is realistic. Y2K swept the globe in
about 24 hours. No easy way to avoid it for many applications. Someone
running python 2.X on their own machines may be able to continue living in
their bubble for quite a while. If you sell or share a product with python
frozen into an app, it makes no difference. But asking some clients to
maintain multiple copies of python set up so one app keeps running as all
others use the newer one, may not remain a great solution indefinitely. 

Has anyone considered something that may be at the edges. How well do
cooperating programs work together? I mean if program one processes and
saves some data structures using something like pickle, and program two is
supposed to read the pickle back in and continue processing, then you may
get anomalies of many kinds if they use different pythons. Similarly,
processes that start up other scripts and communicate with them, may need to
start newer programs that use the 3.X or beyond version as no back-ported
version exists. The bubble may enlarge and may eventually burst.

-Original Message-
From: Python-list  On
Behalf Of Larry Martell
Sent: Friday, January 18, 2019 10:47 AM
To: Python 
Subject: Re: Pythonic Y2K

On Fri, Jan 18, 2019 at 10:43 AM Michael Torrie  wrote:
>
> On 01/16/2019 12:02 PM, Avi Gross wrote:
> > I recall the days before the year 2000 with the Y2K scare when 
> > people worried that legacy software might stop working or do 
> > horrible things once the clock turned. It may even have been scary 
> > enough for some companies to rewrite key applications and even switch
from languages like COBOL.
>
> Of course it wasn't just a scare.  The date rollover problem was very 
> real. It's interesting that now we call it the Y2K "scare" and since 
> most things came through that okay we often suppose that the people 
> who were warning about this impending problem were simply being 
> alarmist and prophets of doom.  We often deride them.  But the fact 
> is, people did take these prophets of doom seriously and there was a 
> massive, even heroic effort, to fix a lot of these critical backend 
> systems so that disaster was avoided (just barely).  I'm not talking 
> about PCs rolling over to 00.  I'm talking about banking software, 
> mission critical control software.  It certainly was scary enough for 
> a lot of companies to spend a lot of money rewriting key software.  
> The problem wasn't with COBOL necessarily.

I had one client, a hedge fund, that I fixed literally 1000's of Y2K issues
for. When Y2K came and there were no problems, the owner said to me "You
made such a big deal about the Y2K thing, and nothing happened."
--
https://mail.python.org/mailman/listinfo/python-list

-- 
https://mail.python.org/mailman/listinfo/python-list


RE: Pythonic Y2K

2019-01-18 Thread Avi Gross
ically at run time. Blue Screen of Death
type of fail. You had to save your work regularly. Languages like python
allow you to catch exceptions and deal intelligently with them to at least
close down gracefully or even recover. Heck, many programs depend on this
and instead of cluttering their code with lots of tests, wait for the error
to happen and adjust in the rare case it does.

So how reasonable would it be to still have lots of legacy software using
languages and programmers that have no easy ways to make their programs more
robust? How would such software react if it received information say in
UNICODE?

I predict that many people and companies have ignored warnings that the 2.X
train would someday be diverted to a dead-end track. It was always far
enough off in the future. But when a LAST DATE for updates is announced,
some may sit up and take notice. It may literally take something like
Insurance Companies (or the VC types) refusing to continue supporting them
if they do not change, to get them the hint. And, over time, many companies
do go under or are bought by another and often that will cause old projects
to go away or morph. 

But there is nothing fundamentally wrong with using 2.X. As I said jokingly,
if anyone wanted to keep it and support it as a DIFFERENT language than the
more modern python, fine. 

-Original Message-
From: Python-list  On
Behalf Of Michael Torrie
Sent: Friday, January 18, 2019 10:36 AM
To: python-list@python.org
Subject: Re: Pythonic Y2K

On 01/16/2019 12:02 PM, Avi Gross wrote:
> I recall the days before the year 2000 with the Y2K scare when people 
> worried that legacy software might stop working or do horrible things 
> once the clock turned. It may even have been scary enough for some 
> companies to rewrite key applications and even switch from languages like
COBOL.

Of course it wasn't just a scare.  The date rollover problem was very real.
It's interesting that now we call it the Y2K "scare" and since most things
came through that okay we often suppose that the people who were warning
about this impending problem were simply being alarmist and prophets of
doom.  We often deride them.  But the fact is, people did take these
prophets of doom seriously and there was a massive, even heroic effort, to
fix a lot of these critical backend systems so that disaster was avoided
(just barely).  I'm not talking about PCs rolling over to 00.  I'm talking
about banking software, mission critical control software.  It certainly was
scary enough for a lot of companies to spend a lot of money rewriting key
software.  The problem wasn't with COBOL necessarily.

In the end disaster was averted (rather narrowly) thanks to the hard work of
a lot of people, and thanks to the few people who were vocal in warning of
the impending issue.

That said, I'm not sure Python 2.7's impending EOL is comparable to the Y2K
crisis.
--
https://mail.python.org/mailman/listinfo/python-list

-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Pythonic Y2K

2019-01-18 Thread mm0fmf

On 17/01/2019 02:34, Avi Gross wrote:





 but all it took was to set the clock forward on a test system and
look for anomalies.


You're new to programming or you're not very  old and certainly haven't 
run much pre-Y2k software. ;-)


Issues that needed solving:

2 digits only for the date
use of 99 or 00 in the year for "magic" purposes
software that didn't know 2000 was a leap year

One machine I had to update (all in Z80 assembler) had the date in the 
format DD-MMM-199Y, i.e. only the units year could be changed. There was 
a comment in the date code saying


; marketing say this machine will stop being sold in 1993 so there
; is no need to support anything other than 1990-1999 in the year

It was still being sold in 2002!

The reason there were so few Y2K issues was that things were fixed in 
advance. And yes, there was also lots of stupidity and hysterics from 
people who didn't know. One major change, after people started fixing 
this in issue in earnest, dates started to always include the century 
digits.


Now get off my lawn! :-)


--
https://mail.python.org/mailman/listinfo/python-list


Re: Pythonic Y2K

2019-01-18 Thread Grant Edwards
On 2019-01-18, Dennis Lee Bieber  wrote:

>   Hey... I'm still waiting for a novelization of the TRS-DOS date "bug".
> TRS-DOS directory structure only allocated 3-bits for the year.

Three bits for the year?  they didn't expect those computers to last
long, eh?

[My current Thinkpad is over 10 years old.]

-- 
Grant Edwards   grant.b.edwardsYow! BARBARA STANWYCK makes
  at   me nervous!!
  gmail.com

-- 
https://mail.python.org/mailman/listinfo/python-list


RE: Pythonic Y2K

2019-01-18 Thread David Raymond
Reminds me of a similar problem that didn't get noticed until it did actually 
hit: In 2007 the first time a group of F-22's crossed the international date 
line every computer system in the aircraft crashed, losing comms, navigation, 
avionics, and a host of other systems. Fortunately their engines, landing gear, 
and enough other systems still worked, so they were able to visually follow 
their refueling tankers back to Hawaii and land, where they had to sit for a 
couple days before Lockheed could patch their software.

If the circumstances had been a little different they could have lost a whole 
group of shiny new $150 million aircraft to a software bug and left a bunch a 
pilots floating in life rafts for a while in the middle of the Pacific.


-Original Message-
From: Python-list 
[mailto:python-list-bounces+david.raymond=tomtom@python.org] On Behalf Of 
Michael Torrie
Sent: Friday, January 18, 2019 10:36 AM
To: python-list@python.org
Subject: Re: Pythonic Y2K

On 01/16/2019 12:02 PM, Avi Gross wrote:
> I recall the days before the year 2000 with the Y2K scare when people
> worried that legacy software might stop working or do horrible things once
> the clock turned. It may even have been scary enough for some companies to
> rewrite key applications and even switch from languages like COBOL.

Of course it wasn't just a scare.  The date rollover problem was very
real. It's interesting that now we call it the Y2K "scare" and since
most things came through that okay we often suppose that the people who
were warning about this impending problem were simply being alarmist and
prophets of doom.  We often deride them.  But the fact is, people did
take these prophets of doom seriously and there was a massive, even
heroic effort, to fix a lot of these critical backend systems so that
disaster was avoided (just barely).  I'm not talking about PCs rolling
over to 00.  I'm talking about banking software, mission critical
control software.  It certainly was scary enough for a lot of companies
to spend a lot of money rewriting key software.  The problem wasn't with
COBOL necessarily.

In the end disaster was averted (rather narrowly) thanks to the hard
work of a lot of people, and thanks to the few people who were vocal in
warning of the impending issue.

That said, I'm not sure Python 2.7's impending EOL is comparable to the
Y2K crisis.
-- 
https://mail.python.org/mailman/listinfo/python-list
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Pythonic Y2K

2019-01-18 Thread Larry Martell
On Fri, Jan 18, 2019 at 10:43 AM Michael Torrie  wrote:
>
> On 01/16/2019 12:02 PM, Avi Gross wrote:
> > I recall the days before the year 2000 with the Y2K scare when people
> > worried that legacy software might stop working or do horrible things once
> > the clock turned. It may even have been scary enough for some companies to
> > rewrite key applications and even switch from languages like COBOL.
>
> Of course it wasn't just a scare.  The date rollover problem was very
> real. It's interesting that now we call it the Y2K "scare" and since
> most things came through that okay we often suppose that the people who
> were warning about this impending problem were simply being alarmist and
> prophets of doom.  We often deride them.  But the fact is, people did
> take these prophets of doom seriously and there was a massive, even
> heroic effort, to fix a lot of these critical backend systems so that
> disaster was avoided (just barely).  I'm not talking about PCs rolling
> over to 00.  I'm talking about banking software, mission critical
> control software.  It certainly was scary enough for a lot of companies
> to spend a lot of money rewriting key software.  The problem wasn't with
> COBOL necessarily.

I had one client, a hedge fund, that I fixed literally 1000's of Y2K
issues for. When Y2K came and there were no problems, the owner said
to me "You made such a big deal about the Y2K thing, and nothing
happened."
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Pythonic Y2K

2019-01-18 Thread Michael Torrie
On 01/16/2019 12:02 PM, Avi Gross wrote:
> I recall the days before the year 2000 with the Y2K scare when people
> worried that legacy software might stop working or do horrible things once
> the clock turned. It may even have been scary enough for some companies to
> rewrite key applications and even switch from languages like COBOL.

Of course it wasn't just a scare.  The date rollover problem was very
real. It's interesting that now we call it the Y2K "scare" and since
most things came through that okay we often suppose that the people who
were warning about this impending problem were simply being alarmist and
prophets of doom.  We often deride them.  But the fact is, people did
take these prophets of doom seriously and there was a massive, even
heroic effort, to fix a lot of these critical backend systems so that
disaster was avoided (just barely).  I'm not talking about PCs rolling
over to 00.  I'm talking about banking software, mission critical
control software.  It certainly was scary enough for a lot of companies
to spend a lot of money rewriting key software.  The problem wasn't with
COBOL necessarily.

In the end disaster was averted (rather narrowly) thanks to the hard
work of a lot of people, and thanks to the few people who were vocal in
warning of the impending issue.

That said, I'm not sure Python 2.7's impending EOL is comparable to the
Y2K crisis.
-- 
https://mail.python.org/mailman/listinfo/python-list


RE: Pythonic Y2K

2019-01-18 Thread David Raymond
Which brings up the assumption that this whole A.D. thing is gonna stick around 
for more than a few millennia and isn't just a fad. Sloppy to just use positive 
for A.D. and negative for B.C. without a discrete unit for Age. What happens 
when Sauron is defeated and the Third Age is declared? Or if we go back to "in 
the 65th year of the reign of Elizabeth, second of her name"? Or if someone 
declares a new epoch and that this is really the year 49 A.U. (Anno Unixy)?


-Original Message-
From: Python-list 
[mailto:python-list-bounces+david.raymond=tomtom@python.org] On Behalf Of 
Avi Gross
Sent: Thursday, January 17, 2019 5:46 PM
To: python-list@python.org
Subject: RE: Pythonic Y2K

Ian,

You just scared me. It is 2019 which has four digits. In less than 8,000
years we will need to take the fifth to make numbers from 10,000 to 10,999.
90,000 years later we will need a sixth digit and so on.

Do you know how many potential Y2K-like anomalies we may have between now
and year 292,277,026,596 when it may all be over? Will people evert learn
and just set aside lots of room that dates can grow into or allow varying
lengths?

Makes me wonder though why anyone in the distant future would want numbers
that long to represent that date. I suspect that long before then, some
surviving members of whatever the human race becomes will do a reset to a
new calendar such as the date the first settlers arrived in the Gamma
Quadrant.

So whatever unit they store time in, though, may still need a way to reach
back to historic times just as we do by talking about what may have happened
in 2000 B.C.


-Original Message-
From: Python-list  On
Behalf Of Ian Kelly
Sent: Thursday, January 17, 2019 2:14 PM
To: Python 
Subject: Re: Pythonic Y2K

On Wed, Jan 16, 2019 at 9:57 PM Avi Gross  wrote:
>
> The forthcoming UNIX 2038 problem will, paradoxically happen on 
> January
19. I wonder what they will do long before then. Will they just add a byte
or four or 256 and then make a date measurable in picoseconds? Or will they
start using a number format that can easily deal with 1 Million B.C. and 5
Billion A.D. just in case we escape earth before it co-locates with the
expanding sun.

The obvious solution is to stop using 32-bit Unix timestamps and start using
64-bit Unix timestamps. This change has already been made in some OSes, and
the problem will not repeat until the year 292,277,026,596, by which time it
is highly unlikely that either Unix timestamps or humankind itself will
still exist. Even if they will, that moment in time is so far out from the
present that I can't really be bothered by the possibility.

We have 19 years to take care of the problem before it happens. Hopefully
this time around we won't be trying to fix it right up until the last
minute.
--
https://mail.python.org/mailman/listinfo/python-list

-- 
https://mail.python.org/mailman/listinfo/python-list
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Pythonic Y2K

2019-01-17 Thread DL Neil

Back in the computer world, Y2K gave such managers some cover. There was a
FIRM deadline. I wonder how many used the impending arrival of the year 2000
as an excuse to perhaps clean up other parts of their act and charge it to
prevention. I mean they might suggest they rewrite some legacy COBOL or even
machine language programs into something more modern or other improvements
like getting a new database including new hardware.


Of course we did!

However, as pointed-out elsewhere, sometimes the costs of re-writing 
seemed less than those required to ameliorate any number of unknown 
issues in the legacy code. Remembering that we would also remove 
unneeded cruft, and (usually) add features needed for 'today's use'.


What were you saying about politicians 'playing' with retirement funds 
and public money? The other advantage to a re-write decision was even 
more under-hand: once agreed, that became a dev project (with a 
31Dec1999 drop-dead deadline) and was NO LONGER part of the Y2K project, 
ie no longer 'my problem'!


I recall at least one project where the users over-egged their case 
(IMHO), taking the dev option even against my advice. They failed to 
make the deadline. Let's just say, on their part, there was a lot of 
fancy-footwork during the first days of 2000...




I also wonder if jobs for some programmers declined sharply in the years
after when not only were they not desperately needed, but perhaps not needed
at all unless they developed new talents.


No, quite the opposite. What happened was that many other projects were 
put-off pending Y2K amelioration. Once we could release staff, they were 
greeted with open arms, and often far, far, greater appreciation than 
normally meets a new dev upon arrival.




Just FYI, the name Y2K always struck me as similar nonsense. They
abbreviated Year and 2000 from at least 8 characters to 3 and did it wrong
as 2K is 2048. As far as I know, nothing special will happen in 2048 and I
also have no special vision for 2020.


You don't seem to understand journalism: Never let the truth (facts) 
interfere with a 'good story'!


I was just talking with a (tech) librarian, who had asked me about "the 
Unix Millennium bug" a few weeks ago, and mentioned this thread. He 
groaned, wondering how long it will be before some hack writes a 
sensationalist book with which to greet the end of the (binary) world...



My play-time this afternoon will involve using Python to keep 
(time-code) track of when/where to superimpose components into a video 
stream...

(I should be back before 2038)

--
Regards =dn
--
https://mail.python.org/mailman/listinfo/python-list


RE: Pythonic Y2K

2019-01-17 Thread Avi Gross
Ian,

You just scared me. It is 2019 which has four digits. In less than 8,000
years we will need to take the fifth to make numbers from 10,000 to 10,999.
90,000 years later we will need a sixth digit and so on.

Do you know how many potential Y2K-like anomalies we may have between now
and year 292,277,026,596 when it may all be over? Will people evert learn
and just set aside lots of room that dates can grow into or allow varying
lengths?

Makes me wonder though why anyone in the distant future would want numbers
that long to represent that date. I suspect that long before then, some
surviving members of whatever the human race becomes will do a reset to a
new calendar such as the date the first settlers arrived in the Gamma
Quadrant.

So whatever unit they store time in, though, may still need a way to reach
back to historic times just as we do by talking about what may have happened
in 2000 B.C.


-Original Message-
From: Python-list  On
Behalf Of Ian Kelly
Sent: Thursday, January 17, 2019 2:14 PM
To: Python 
Subject: Re: Pythonic Y2K

On Wed, Jan 16, 2019 at 9:57 PM Avi Gross  wrote:
>
> The forthcoming UNIX 2038 problem will, paradoxically happen on 
> January
19. I wonder what they will do long before then. Will they just add a byte
or four or 256 and then make a date measurable in picoseconds? Or will they
start using a number format that can easily deal with 1 Million B.C. and 5
Billion A.D. just in case we escape earth before it co-locates with the
expanding sun.

The obvious solution is to stop using 32-bit Unix timestamps and start using
64-bit Unix timestamps. This change has already been made in some OSes, and
the problem will not repeat until the year 292,277,026,596, by which time it
is highly unlikely that either Unix timestamps or humankind itself will
still exist. Even if they will, that moment in time is so far out from the
present that I can't really be bothered by the possibility.

We have 19 years to take care of the problem before it happens. Hopefully
this time around we won't be trying to fix it right up until the last
minute.
--
https://mail.python.org/mailman/listinfo/python-list

-- 
https://mail.python.org/mailman/listinfo/python-list


RE: Pythonic Y2K

2019-01-17 Thread Avi Gross
Well said, Joseph.

Unfortunately, many companies are run these days with a view toward the
IMMEDIATE bottom line. I mean numbers like revenues or expenses are seen
short-term. If a project stops development on new things and spends time
redoing old things, there are expenses recorded with no revenues. Another
organization might go ahead and get up to date and a few years down the road
their projects are sailing along while the first employer keeps running into
obstacles and is not able to get new developments and so on. But often, the
manager making the decision will have taken their bonus or promotion and
perhaps moved on or retired.

Not to be political, I note many government entities, especially including
the state I live in, have gigantic pension obligations they have no easy way
to meet. Over the years in negotiations with unions they have often traded
rich promises for the future instead of immediate pay hikes. The costs may
largely be invisible and did not impact their current budgets so they could
waste money on other things such as giveaways that help them get re-elected
to ever higher office. But the costs are getting very visible now, and
especially when the stocks they invest in decline.

Back in the computer world, Y2K gave such managers some cover. There was a
FIRM deadline. I wonder how many used the impending arrival of the year 2000
as an excuse to perhaps clean up other parts of their act and charge it to
prevention. I mean they might suggest they rewrite some legacy COBOL or even
machine language programs into something more modern or other improvements
like getting a new database including new hardware.

I also wonder if jobs for some programmers declined sharply in the years
after when not only were they not desperately needed, but perhaps not needed
at all unless they developed new talents.

Just FYI, the name Y2K always struck me as similar nonsense. They
abbreviated Year and 2000 from at least 8 characters to 3 and did it wrong
as 2K is 2048. As far as I know, nothing special will happen in 2048 and I
also have no special vision for 2020.

-Original Message-
From: Python-list  On
Behalf Of Schachner, Joseph
Sent: Thursday, January 17, 2019 1:46 PM
To: Python 
Subject: RE: Pythonic Y2K

I'd like to add one more thing to your list of what companies will have to
consider:

6) The ability to hire and retain employees who will be happy to program in
an obsolete version of Python.  A version about which new books will
probably not be written.  A version which new packages will not support.  A
version which most other companies will no longer be using, so programming
only in Python 2 will place the employee at a disadvantage compared to
others who have gained experience with Python 3 if they ever have to change
employers.

--- Joseph S.

-Original Message-
From: Chris Angelico 
Sent: Wednesday, January 16, 2019 2:15 PM
To: Python 
Subject: Re: Pythonic Y2K

On Thu, Jan 17, 2019 at 6:04 AM Avi Gross  wrote:
>
> I see messages like the following where someone is still asking how to 
> do something in some version of python 2.X.
>
> I recall the days before the year 2000 with the Y2K scare when people 
> worried that legacy software might stop working or do horrible things 
> once the clock turned. It may even have been scary enough for some 
> companies to rewrite key applications and even switch from languages like
COBOL.
>
> What is happening in the python community, and especially in places 
> where broken software may be a serious problem?
>
> I assume versions of python 2.X will continue to be available for some 
> time but without any further support and without features being
back-ported.

Commercial support for Python 2 will probably continue for a while, in the
same way that support for versions older than 2.7 is still available to Red
Hat customers today (if I'm not mistaken). Otherwise, well, the software
will continue without updates or security patches until it breaks. Companies
will have to weigh up five costs against each other:

1) The cost of the status quo: the risk of critical failures or external
attacks against unsupported and unpatched software

2) The cost of migrating to Python 3

3) The cost of migrating to a completely different language

4) The cost of maintaining their own local fork of Python 2

5) The cost of using a supported commercial platform such as RHEL.

For most small to medium projects, it's probably going to come down to
#1 or #2, where #1 has the laziness bonus. For many larger companies,
#1 is an unpayable cost. Everyone has to make that choice, and remember that
"cost" doesn't just mean money (for instance, the cost of moving to Linux
might be quite considerable for a Windows shop, and even within a Linux
ecosystem, switching to Red Hat may have consequences to other programs you
might need).

ChrisA

--
https://mail.python.org/mailman/listinfo/python-list

-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Pythonic Y2K

2019-01-17 Thread Chris Angelico
On Fri, Jan 18, 2019 at 8:47 AM DL Neil  wrote:
>
> On 17/01/19 6:53 PM, Chris Angelico wrote:
> > On Thu, Jan 17, 2019 at 3:55 PM Avi Gross  wrote:
> >> The forthcoming UNIX 2038 problem will, paradoxically happen on January 19.
> >>
> >
> > Paradoxically? What do you mean by that?
>
>
> First we had to duck the Y2K problem.
> By moving everything to 64-bits, we duck the Unix Millennium problem.
>
> There you go: two ducks - a pair-o-ducks!

Well, I'm sorry Neil, but these things are well documented.

In fact, you can find information on the web, OR you can examine the
man pages in your local installation.

Wait, we're right back where we started... a pair-o-docs

> I assume the paradox involves noting that the end of the (32-bit) Unix
> epoch, does not coincide with the end of a (Gregorian) calendar year.

Ahh yes, as paradoxical as when the Mayan Y2K happened in December of
2012. Gotcha.

> Actually, aren't there three date-time problems to be ducked? Wasn't
> Python's move to having wider timestamps (+= fractions of seconds) in
> part connected with the need to modify NTP - which hits the wall a few
> years before 2038...

Oh, probably. But one of the reasons I use high level languages is so
I don't have to worry about the sizes of integers. In fact, some day,
we won't use floats to store seconds, we'll just use bignum integers
to store some number of Planck times

ChrisA
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Pythonic Y2K

2019-01-17 Thread DL Neil

On 17/01/19 6:53 PM, Chris Angelico wrote:

On Thu, Jan 17, 2019 at 3:55 PM Avi Gross  wrote:

The forthcoming UNIX 2038 problem will, paradoxically happen on January 19.



Paradoxically? What do you mean by that?



First we had to duck the Y2K problem.
By moving everything to 64-bits, we duck the Unix Millennium problem.

There you go: two ducks - a pair-o-ducks!


I assume the paradox involves noting that the end of the (32-bit) Unix 
epoch, does not coincide with the end of a (Gregorian) calendar year.



Actually, aren't there three date-time problems to be ducked? Wasn't 
Python's move to having wider timestamps (+= fractions of seconds) in 
part connected with the need to modify NTP - which hits the wall a few 
years before 2038...


--
Regards =dn
--
https://mail.python.org/mailman/listinfo/python-list


  1   2   3   4   5   6   7   8   9   10   >