RE: Top level of a recursive function

2022-12-13 Thread Schachner, Joseph (US)
Reducing repetitiveness has made this code harder to read. I had to think about 
what it is doing.  It might be slightly faster, but in my opinion it is not 
worth it.  

--- Joseph S.


Teledyne Confidential; Commercially Sensitive Business Data

-Original Message-
From: Stefan Ram  
Sent: Tuesday, December 13, 2022 10:25 AM
To: python-list@python.org
Subject: Re: Top level of a recursive function

Supersedes: 

r...@zedat.fu-berlin.de (Stefan Ram) writes:
>def rest( s ):
>return "(" + s[ 0 ] +( rest( s[1:] ) if len( s )> 1 else '' )+ ')'
>def nest( s ):
>return( s[ 0 ] if s else '' )+( rest( s[1:] )if len( s )> 1 else '' )

  Below, I have tried to reduce repetitiveness a bit.

  (PS: Now, one "if" remains; less ifs are not possible
  in the case of controlled recursion.)

def rest( s ):
return '(' + nest( s )+ ')'

def nest( s ):
return s[ :1 ]+( rest( s[ 1: ])if s[ 1: ]else '' )

fred = nest


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


RE: How to manage python shebang on mixed systems?

2022-11-07 Thread Schachner, Joseph (US)
Maybe you can't do this, but I would suggest only running on the Python 3 
systems.  Refuse to jump through hoops for the Python 2 system.  It is years 
out of date.
It is not hard to upgrade from Python 2 to Python 3.  There is a 2to3 utility, 
and after that there should be very few things you want to manually change.  
Perhaps you could encourage them to upgrade.

--- Joseph S.


Teledyne Confidential; Commercially Sensitive Business Data

-Original Message-
From: Chris Green  
Sent: Monday, November 7, 2022 4:06 AM
To: python-list@python.org
Subject: Re: How to manage python shebang on mixed systems?

Cameron Simpson  wrote:
> On 06Nov2022 20:51, jak  wrote:
> >Il 06/11/2022 11:03, Chris Green ha scritto:
> >>I have a number of python scripts that I run on a mix of systems.  I 
> >>have updated them all to run on python 3 but many will also run 
> >>quite happily with python 2.  They all have a #!/usr/bin/python3 shebang.
> 
> I usually use:
> 
> #!/usr/bin/env python3
> 
> This runs the default "python3" from my $PATH, whatever that is, 
> avoiding a hardwired path to the python3 executable.
> 
Yes, that's probably a good idea, less likely to break than mine.


> >>This works almost everywhere but there is one system where only 
> >>python 2 is available (at /usr/bin/python).
> >>
> >>I don't have python 2 on any of the systems I manage myself now so a 
> >>#!/usr/bin/python shebang will fail.
> >>
> >>Is there a neat way of handling this?  I could write a sort of 
> >>wrapper script to run via the shebang but that seems overkill to me.
> 
> It is overkill. I generally dislike batch editing scripts.
> 
> 1: do these scripts work on both python2 and python3? It seems like 
> they would need to.

Yes, they do, they're mostly very simple utility scripts for doing things like 
changing spaces to underscores in filenames and such.
Just putting 'print' parameters in brackets was all that most of them needed to 
work in python 3.


> 2: write a tiny script _named_ "python3" which invokes python 2. I 
> keep a personal "~/bin-local" directory for just such per-system 
> special commands like this.
> 3: with your pseudo "python3" script in place, make all the scripts 
> use the "#!/usr/bin/env python3" shebang suggested above.
> 
Yes, that sounds a good plan to me, thanks Cameron.

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


RE: Are Floating Point Numbers still a Can of Worms?

2022-10-24 Thread Schachner, Joseph (US)
Floating point will always be a can of worms, as long as people expect it to 
represent real numbers with more precision that float has.  Usually this is not 
an issue, but sometimes it is.  And, although this example does not exhibit 
subtractive cancellation, that is the surest way to have less precision that 
the two values you subtracted.  And if you try to add up lots of values, if 
your sum grows large enough, tiny values will not change it anymore, even if 
there are many of them  - there are simple algorithms to avoid this effect.  
But all of this is because float has limited precision.

--- Joseph S.


Teledyne Confidential; Commercially Sensitive Business Data

-Original Message-
From: Pieter van Oostrum  
Sent: Sunday, October 23, 2022 10:25 AM
To: python-list@python.org
Subject: Re: Are Floating Point Numbers still a Can of Worms?

Mostowski Collapse  writes:

> I also get:
>
> Python 3.11.0rc1 (main, Aug 8 2022, 11:30:54)
 2.718281828459045**0.8618974796837966
> 2.367649
>
> Nice try, but isn't this one the more correct?
>
> ?- X is 2.718281828459045**0.8618974796837966.
> X = 2.36764897.
>

That's probably the accuracy of the underlying C implementation of the exp 
function.

In [25]: exp(0.8618974796837966)
Out[25]: 2.367649

But even your answer can be improved:

Maxima:

(%i1) fpprec:30$

(%i2) bfloat(2.718281828459045b0)^bfloat(.8618974796837966b0);
(%o2)  2.367648983187397393143b0

but:

(%i7) bfloat(%e)^bfloat(.8618974796837966b0);
(%o7)  2.36764900085638369695b0
surprisingly closer to Python's answer.

but 2.718281828459045 isn't e. Close but no cigar.

(%i10) bfloat(2.718281828459045b0) - bfloat(%e);
(%o10)   - 2.35360287471352802147785151603b-16

Fricas:

(1) -> 2.718281828459045^0.8618974796837966 

   (1)  2.367648_98319

(2) -> exp(0.8618974796837966)

   (2)  2.367649_00086

-- 
Pieter van Oostrum 
www: http://pieter.vanoostrum.org/
PGP key: [8DAE142BE17999C4]
-- 
https://mail.python.org/mailman/listinfo/python-list


RE: A trivial question that I don't know - document a function/method

2022-10-24 Thread Schachner, Joseph (US)
I head a small software team much of whose output is Python.   I would 
gratefully accept any of the formats you show below.  My preference is #1.

--- Joseph S.


Teledyne Confidential; Commercially Sensitive Business Data

-Original Message-
From: Paulo da Silva  
Sent: Saturday, October 22, 2022 4:58 PM
To: python-list@python.org
Subject: A trivial question that I don't know - document a function/method

Hi all!

What is the correct way, if any, of documenting a function/method?

1.
def foo(a,b):
""" A description.
a: Whatever 1
b: Whatever 2
"""
...

2.
def foo(a,b):
""" A description.
a -- Whatever 1
b -- Whatever 2
"""
...

3.
def foo(a,b):
""" A description.
@param a: Whatever 1
@param b: Whatever 2
"""
...

4.
def foo(a,b):
""" A description.
:param a: Whatever 1
:param b: Whatever 2
"""
...

5.
Any other ...

Any comments/suggestions are welcome.
Thanks.
Paulo

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


RE: How to make a variable's late binding crosses the module boundary?

2022-08-30 Thread Schachner, Joseph (US)
The way we do this, is in main.py, call a "globalizer" function in each other 
file:

# call globalizers to get shortcuts as global variables
funcs.globalizer(interface, variable_dict)
util.globalizer(interface, variable_dict)
sd.globalizer(interface, variable_dict)
tests.globalizer(interface, variable_dict)
ut.globalizer(interface, variable_dict)

Obviously, you may not need a shared interface in which case you can just pass 
the variable dictionary.

In each file, you have a function:
def globalizer(interface, variables_dict):
# create global variables for this .py file for shared interface and the 
variables


This works well, making sure separate python files shared exactly the same 
things we want to be global.

 Joseph S.

Teledyne Confidential; Commercially Sensitive Business Data

-Original Message-
From: Stefan Ram  
Sent: Tuesday, August 30, 2022 1:09 AM
To: python-list@python.org
Subject: Re: How to make a variable's late binding crosses the module boundary?

dn  writes:
>Build module.py as:
>***
>CONSTANT = 1

>def func():
>pass
>***

>then in the terminal:
>***
>Python 3.9.13 (main, May 18 2022, 00:00:00) [GCC 11.3.1 20220421 (Red 
>Hat 11.3.1-2)] on linux Type "help", "copyright", "credits" or 
>"license" for more information.
 from module import func as f

  In CPython one then can also:

print( f.__globals__[ "CONSTANT" ])
import sys
module = sys.modules[ f.__globals__[ "__name__" ]] print( module.CONSTANT ) 
CONSTANT = module.CONSTANT print( CONSTANT )

  .


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


RE: Parallel(?) programming with python

2022-08-09 Thread Schachner, Joseph (US)
Why would this application *require* parallel programming?   This could be done 
in one, single thread program.   Call time to get time and save it as 
start_time.   Keep a count of the number of 6 hour intervals, initialize it to 
0.

Once a second read data an append to list.  At 6 hours after start time, call a 
function that does an FFT (see comment about scipy below) and increment the 
count of 6 hour intervals.  Call time and save new start time. Continue 
execution.

After 28 six hour intervals, save the list and then slice the list to  shorten 
it as you want.  Reset the count of 6 hour intervals to zero.

The FFT might take a second, even if you use scipy, depending on how long the 
list is (If you don’t know about numpy and scipy, look them up! You need them.  
 Your list can be an array in numpy).  
Saving and slicing the list should take less than a second.

This single thread approach avoids thinking about multiprocessing, locking and 
unlocking data structures, all that stuff that does not contribute to the goal 
of the program.

--- Joseph S.


Teledyne Confidential; Commercially Sensitive Business Data

-Original Message-
From: Andreas Croci  
Sent: Monday, August 8, 2022 6:47 AM
To: python-list@python.org
Subject: Parallel(?) programming with python

tI would like to write a program, that reads from the network a fixed amount of 
bytes and appends them to a list. This should happen once a second.

Another part of the program should take the list, as it has been filled so far, 
every 6 hours or so, and do some computations on the data (a FFT).

Every so often (say once a week) the list should be saved to a file, shorthened 
in the front by so many items, and filled further with the data coming fom the 
network. After the first saving of the whole list, only the new part (the data 
that have come since the last saving) should be appended to the file. A 
timestamp is in the data, so it's easy to say what is new and what was already 
there.

I'm not sure how to do this properly: can I write a part of a program that 
keeps doing its job (appending data to the list once every second) while 
another part computes something on the data of the same list, ignoring the new 
data being written?

Basically the question boils down to wether it is possible to have parts of a 
program (could be functions) that keep doing their job while other parts do 
something else on the same data, and what is the best way to do this.
-- 
https://mail.python.org/mailman/listinfo/python-list


RE: Python/New/Learn

2022-05-05 Thread Schachner, Joseph
Buy the book "Python 101" and do the examples.  When you're done with that buy 
the book "Python 201" and study it.  There is much more than is in both those 
books that you could learn about Python, but that's a very good way to start.

--- Joseph S.


Teledyne Confidential; Commercially Sensitive Business Data

-Original Message-
From: Patrick 0511  
Sent: Wednesday, May 4, 2022 9:36 PM
To: python-list@python.org
Subject: Python/New/Learn

Hello, I'm completely new here and don't know anything about python. Can 
someone tell me how best to start? So what things should I learn first?
-- 
https://mail.python.org/mailman/listinfo/python-list


RE: lambda issues

2022-04-20 Thread Schachner, Joseph
Re:  "...which takes a callable (the lambda here)"

Python lamdas have some severe restrictions.  In any place that takes a 
callable, if a lambda can't serve, just use def to write a function and use the 
function name.

 Joseph S.


Teledyne Confidential; Commercially Sensitive Business Data

-Original Message-
From: Python-list 
 On Behalf Of 
python-list-requ...@python.org
Sent: Wednesday, April 20, 2022 12:00 PM
To: python-list@python.org
Subject: Python-list Digest, Vol 223, Issue 20

---External Email---

Send Python-list mailing list submissions to
python-list@python.org

To subscribe or unsubscribe via the World Wide Web, visit
https://mail.python.org/mailman/listinfo/python-list
or, via email, send a message with subject or body 'help' to
python-list-requ...@python.org

You can reach the person managing the list at
python-list-ow...@python.org

When replying, please edit your Subject line so it is more specific than "Re: 
Contents of Python-list digest..."
-- 
https://mail.python.org/mailman/listinfo/python-list


RE: Functionality like local static in C

2022-04-14 Thread Schachner, Joseph
Yes, python has something like that.  In fact, two things.   

1) Generator.  Use a "yield" statement.   Every call "yields" a new value.   
The state of the function (local variables) is remembered from each previous 
call to the next.

2) In a file, declare a variable to be global.   In the function declare global 
var, so that it will not only read the global but will also write it.  That 
variable does not go away. On the next time the function is called, It will 
hold whatever value it had when the function finished previously.

 Joseph S.


Teledyne Confidential; Commercially Sensitive Business Data

-Original Message-
From: Cecil Westerhof  
Sent: Thursday, April 14, 2022 11:02 AM
To: python-list@python.org
Subject: Functionality like local static in C

In C when you declare a variable static in a function, the variable retains its 
value between function calls.
The first time the function is called it has the default value (0 for an int).
But when the function changes the value in a call (for example to 43), the next 
time the function is called the variable does not have the default value, but 
the value it had when the function returned.
Does python has something like that?

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


RE: Reportlab / platypus bug?

2022-03-14 Thread Schachner, Joseph
I realize this is Python code, but I doubt that the question is a Python 
question.  I have used Python +numpy, scipy, matplotlib for years.   I have not 
used reportlab and have no idea about the reported problem except that I will 
be very surprised if it turns out to be a Python language issue.   Is there 
possibly a better place to ask this question?


Teledyne Confidential; Commercially Sensitive Business Data

-Original Message-
From: Les  
Sent: Sunday, March 13, 2022 4:56 PM
To: python-list@python.org
Subject: Reportlab / platypus bug?

  Hello,

I have found an error, and I created a minimal working example. The minimal 
working example starts with the very first example from Platypus user guide:

from reportlab.platypus import SimpleDocTemplate, Paragraph, Spacer from 
reportlab.lib.styles import getSampleStyleSheet from reportlab.lib.pagesizes 
import A4 from reportlab.lib.units import inch

PAGE_HEIGHT = A4[1]
PAGE_WIDTH = A4[0]
styles = getSampleStyleSheet()

Title = "Hello world"
pageinfo = "platypus example"


def myFirstPage(canvas, doc):
canvas.saveState()
canvas.setFont('Times-Bold', 16)
canvas.drawCentredString(PAGE_WIDTH / 2.0, PAGE_HEIGHT - 108, Title)
canvas.setFont('Times-Roman', 9)
canvas.drawString(inch, 0.75 * inch, "First Page / %s" % pageinfo)
canvas.restoreState()


def myLaterPages(canvas, doc):
canvas.saveState()
canvas.setFont('Times-Roman', 9)
canvas.drawString(inch, 0.75 * inch, "Page %d %s" % (doc.page, pageinfo))
canvas.restoreState()


def go():
Story = [Spacer(1, 2 * inch)]
style = styles["Normal"]
for i in range(100):
bogustext = ("This is Paragraph number %s. " % i) * 20
p = Paragraph(bogustext, style)
Story.append(p)
Story.append(Spacer(1, 0.2 * inch))
doc = SimpleDocTemplate("phello.pdf")
doc.build(Story, onFirstPage=myFirstPage, onLaterPages=myLaterPages)


go()


If I change it to this (e.g. generate two identical files):

doc = SimpleDocTemplate("phello.pdf")
doc.build(Story, onFirstPage=myFirstPage, onLaterPages=myLaterPages) doc = 
SimpleDocTemplate("phello2.pdf") doc.build(Story, onFirstPage=myFirstPage, 
onLaterPages=myLaterPages)


then it builds phello.pdf correctly, but builds a totally empty phello2.pdf
(960 bytes, a single white empty page).

It is hard to explain as it is, but something even more interesting happens if 
you try to make them totally independent, and create a copy of the story as 
well:

import copy
doc = SimpleDocTemplate("phello.pdf")
doc.build(copy.copy(Story), onFirstPage=myFirstPage, onLaterPages=myLaterPages) 
doc = SimpleDocTemplate("phello2.pdf") doc.build(copy.copy(Story), 
onFirstPage=myFirstPage, onLaterPages=myLaterPages)


This will render phello.pdf correctly, and it will throw this error when 
rendering phello2.pdf:

Traceback (most recent call last):
  File "C:\Projects\test\test2.py", line 48, in 
go()
  File "C:\Projects\test\test2.py", line 45, in go
doc.build(copy.copy(Story), onFirstPage=myFirstPage,
onLaterPages=myLaterPages)
  File
"C:\Users\nagyl\.virtualenvs\test-NC9-O-tN\lib\site-packages\reportlab\platypus\doctemplate.py",
line 1314, in build
BaseDocTemplate.build(self,flowables, canvasmaker=canvasmaker)
  File "C:\Users\nagyl\.virtualenvs\
test-NC9-O-tN\lib\site-packages\reportlab\platypus\doctemplate.py", line 1079, 
in build
self.handle_flowable(flowables)
  File "C:\Users\nagyl\.virtualenvs\
test-NC9-O-tN\lib\site-packages\reportlab\platypus\doctemplate.py", line 958, 
in handle_flowable
raise LayoutError(ident)
reportlab.platypus.doctemplate.LayoutError: Flowable This is Paragraph number 6. This is Paragraph number 
6. This(439.27559055118115 x 72) too large on page 1 in frame
'normal'(439.27559055118115 x 685.8897637795277) of template 'First'

And finally, here is the "solution" that solves all problems:


def go():
def create_story():
Story = [Spacer(1, 2 * inch)]
style = styles["Normal"]
for i in range(100):
bogustext = ("This is Paragraph number %s. " % i) * 20
p = Paragraph(bogustext, style)
Story.append(p)
Story.append(Spacer(1, 0.2 * inch))
return Story

doc = SimpleDocTemplate("phello.pdf")
doc.build(create_story(), onFirstPage=myFirstPage,
onLaterPages=myLaterPages)
doc = SimpleDocTemplate("phello2.pdf")
doc.build(create_story(), onFirstPage=myFirstPage,
onLaterPages=myLaterPages)


This does not throw an error, and it renders both files correctly. But I do not 
see why this last version works, and the previous one (that uses
copy.copy) does not.

I was looking for an explanation in the user guide. I was looking for a note, 
telling me that a story can be used for document generation only once. But 
there is no such thing in the docs. Or maybe I just did not find it. Can 
somebody please explain what is happening here?

Environment details: Python 3.10.1 amd64 on Windows, 

RE: Behavior of the for-else construct

2022-03-07 Thread Schachner, Joseph
Can someone please change the topic of this thread?  No longer about for-else.


Teledyne Confidential; Commercially Sensitive Business Data

-Original Message-
From: Dennis Lee Bieber  
Sent: Sunday, March 6, 2022 1:29 PM
To: python-list@python.org
Subject: Re: Behavior of the for-else construct

On Sun, 6 Mar 2022 17:39:51 +0100, "Peter J. Holzer"  
declaimed the following:

>
>(* *) for comments was actually pretty commonly used - maybe because it 
>stands out more than { }. I don't know if I've ever seen (. .) instead 
>of [ ].
>
Or some terminals provided [ ] but not { }  

Modula-2 appears to have fixed on (* *) for comments, and only [ ] for 
indexing.

Consider the potential mayhem going from a language where { } are 
comment delimiters to one where they are block delimiters 


>C also has alternative rerpresentations for characters not in the 
>common subset of ISO-646 and EBCDIC. However, the trigraphs are 
>extremely ugly (e.g ??< ??> instead of { }). I have seen them used (on 
>an IBM/390 system with an EBCDIC variant without curly braces) and it's 
>really no fun to read that.
>
My college mainframe used EBCDIC, but the available languages did not 
include C or Pascal. We had APL, FORTRAN-IV (in full separate compilation form, 
and FLAG [FORTRAN Load and Go] which was a "all in one file, compile & run" 
used by first year students), COBOL (74?), BASIC, SNOBOL, Meta-Symbol and AP 
(both assemblers, though Meta-Symbol could, provided the proper definition 
file, generate absolute binary code for pretty much any processor), and 
something called SL-1 (Simulation Language-1, which produced FORTRAN output for 
discrete event models).

UCSD Pascal, and PDP-11 assembly were run on a pair of LSI-11 systems.
Assembly used for the operating system principles course.

I didn't encounter "real" C until getting a TRS-80 (first as integer 
LC, then Pro-MC), along with Supersoft LISP (on cassette tape!). (I had books 
for C and Ada before encountering compilers for them)


-- 
Wulfraed Dennis Lee Bieber AF6VN
wlfr...@ix.netcom.comhttp://wlfraed.microdiversity.freeddns.org/
-- 
https://mail.python.org/mailman/listinfo/python-list


RE: Behavior of the for-else construct

2022-03-03 Thread Schachner, Joseph
Useful:  On rare occasions (when a loop has a "break" in it)
Used: Yes
Know how it works:  Yes
Even is such a thing: Yes
Your suggestion:   Also useful.  Will require a different keyword.   I don't 
know what that would be. "finally" is available   Write up a feature request.

--- Joseph S.


Teledyne Confidential; Commercially Sensitive Business Data

-Original Message-
From: computermaster360  
Sent: Thursday, March 3, 2022 8:24 AM
To: python-list@python.org
Subject: Behavior of the for-else construct

I want to make a little survey here.

Do you find the for-else construct useful? Have you used it in practice? Do you 
even know how it works, or that there is such a thing in Python?

I have used it maybe once. My issue with this construct is that calling the 
second block `else` doesn't make sense; a much more sensible name would be 
`then`.

Now, imagine a parallel universe, where the for-else construct would have a 
different behavior:

for elem in iterable:
process(elem)
else:
# executed only when the iterable was initially empty
print('Nothing to process')

Wouldn't this be more natural? I think so. Also, I face this case much more 
often than having detect whether I broke out of a loop early (which is what the 
current for-else construct is for).

Now someone may argue that it's easy to check whether the iterable is empty 
beforehand. But is it really? What if it's an iterator?
Then one would have to resort to using a flag variable and set it in each 
iteration of the loop. An ugly alternative would be trying to retrieve the 
first element of the iterable separately, in a try block before the for-loop, 
to find out whether the iterable is empty. This would of course require making 
an iterator of the iterable first (since we can't be sure it is already an 
iterator), and then -- if there are any elements
-- processing
the first element separately before the for-loop, which means duplicating the 
loop body. You can see the whole thing gets really ugly really quickly...

What are your thoughts? Do you agree? Or am I just not Dutch enough...?
-- 
https://mail.python.org/mailman/listinfo/python-list


RE: Problem with concatenating two dataframes

2021-11-08 Thread Schachner, Joseph
The problem I see here is use of Pandas.   I know I have he losing opinion, but 
people who use Python to load Panadas and then only use Pandas are missing out 
on the functionality of Python.

I'll bet you could code combining this data in pure Python, into one 
dictionary. In fact I'd be shocked if you couldn't do it.

 Joseph S.


Teledyne Confidential; Commercially Sensitive Business Data

-Original Message-
From: Mahmood Naderan  
Sent: Saturday, November 6, 2021 6:01 PM
To: python-list@python.org; MRAB 
Subject: Re: Problem with concatenating two dataframes

>The second argument of pd.concat is 'axis', which defaults to 0. Try 
>using 1 instead of 0.


Unfortunately, that doesn't help...


dict[name] = pd.concat( [dict[name],values], axis=1 )



{'dummy': Value
M1  0
M2  0
M3  0, 'K1':Value  Value
0   10.0NaN
15.0NaN
2   10.0NaN
6NaN2.0
7NaN2.0
8NaN2.0, 'K2':Value
3 20
4 10
5 15}



Regards,
Mahmood



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


RE: New assignmens ...

2021-10-26 Thread Schachner, Joseph
Why force unpacking?   Why not assign a tuple?  That would look like a simple 
assignment: x := (alpha, beta, gamma)
And you could access x[0],  x[1] and x[2].

I think asking := to support x, y := alpha, beta  is a request to address an 
unnecessary, easily worked around, issue.  And as previously pointed out you 
can still just use = .

--- Joseph S.


Teledyne Confidential; Commercially Sensitive Business Data

-Original Message-
From: Chris Angelico  
Sent: Monday, October 25, 2021 6:25 PM
To: Python 
Subject: Re: New assignmens ...

On Tue, Oct 26, 2021 at 9:19 AM dn via Python-list  
wrote:
> Back on-topic, I am slightly curious:-
>
> aside from 'starting small' with an option to widen/'open-up' later, 
> is there a particular reason why 'the walrus' has not been made 
> available (could not be ...?) for use with object-attributes?

I can't think of any other reasons. But the one you cite is quite an important 
one. In order to get real-world usage examples, the feature was rolled out in 
the restricted form, because threads like this are
*exactly* how the value can be judged. So I do not in any way regret that 
assignment expressions were accepted in their current form, but also, don't be 
afraid to propose an opening up of the syntax. Be specific, and cite usage 
examples that would benefit.

TBH, I don't think there's a lot of value in multiple-assignment, since it has 
a number of annoying conflicts of syntax and few viable use-cases. But if you 
have great examples of "x.y :=" or "x[y] :=", then by all means, post on 
python-ideas to propose widening the scope.

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


RE: ANN: Dogelog Runtime, Prolog to the Moon (2021)

2021-09-14 Thread Schachner, Joseph
Opinion:   Anyone who is counting on Python for truly fast compute speed is 
probably using Python for the wrong purpose.  
Here, we use Python to control Test Equipment, to set up the equipment and ask 
for a measurement, get it, and proceed to the next measurement; and at the end 
produce a nice formatted report.  If we wrote the test script in C or Rust or 
whatever it could not run substantially faster because it is communicating with 
the test equipment, setting it up and waiting for responses, and that is where 
the vast majority of the time goes.  Especially if the measurement result 
requires averaging it can take a while.  In my opinion this is an ideal use for 
Python, not just because the speed of Python is not important, but also because 
we can easily find people who know Python, who like coding in Python, and will 
join the company to program in Python ... and stay with us.  

--- Joseph S.


Teledyne Confidential; Commercially Sensitive Business Data

-Original Message-
From: Mostowski Collapse  
Sent: Tuesday, September 14, 2021 8:56 AM
To: python-list@python.org
Subject: Re: ANN: Dogelog Runtime, Prolog to the Moon (2021)

I am testing a Prolog interpreter written in Python. So fibonacci number 
routine is written in Prolog and I am running the

fibonnaci number routine inside the
Prolog interpreter that is written in
Python. The factor 6x times faster of

GraalVM can be reproduced also for other Prolog programs running inside the 
Prolog interpreter that is written in Python.

I have a benchmark suite, where I get,
the figures are milliseconds:

TestStandardGraalVM
Total170'996 28'523

This means the factor is:

170'996 / 28'523 = 5.9950

The test harness, test cases and individual results for all test cases are 
found here:

And we could test GraalVM Python, results are from 14.09.2021, tested with 
Dogelog Runtime 0.9.5, Python Version:
https://gist.github.com/jburse/f4e774ebb15cac722238b26b1a620f84#gistcomment-3892587

Terry Reedy wrote:
> On 9/13/2021 8:46 AM, Mostowski Collapse wrote:
>> The Standard Python version of Dogelog runtime is annoyingly slow. So 
>> we gave it a try with andother Python, and it was 6x times faster.
>>
>> We could test GraalVM. We worked around the missing match in Python 
>> 3.8 by replacing it with if-then-else.
>> Performance is a little better, we find:
>>
>> /* Standard Python Version, Warm Run */
>> ?- time(fibo(23,X)).
>> % Wall 3865 ms, gc 94 ms, 71991 lips
>> X = 46368.
>>
>> /* GraalVM Python Version, Warm Warm Run */
>> ?- time(fibo(23,X)).
>> % Wall 695 ms, gc 14 ms, 400356 lips
>> X = 46368.
>>
>> See also:
>>
>> JDK 1.8 GraalVM Python is 6x faster than Standard Python
>> https://twitter.com/dogelogch/status/1437395917167112193
>>
>> JDK 1.8 GraalVM Python is 6x faster than Standard Python 
>> https://www.facebook.com/groups/dogelog
> 
> You need to test more than fibonacci to make that claim.  There is a 
> benchmark test that times around 40 different similarly small benchmarks.
> 
> 

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


RE: on floating-point numbers

2021-09-03 Thread Schachner, Joseph
Actually, Python has an fsum function meant to address this issue.

>>> math.fsum([1e14, 1, -1e14])
1.0
>>>

Wow it works.

--- Joseph S.

Teledyne Confidential; Commercially Sensitive Business Data

-Original Message-
From: Hope Rouselle  
Sent: Thursday, September 2, 2021 9:51 AM
To: python-list@python.org
Subject: on floating-point numbers

Just sharing a case of floating-point numbers.  Nothing needed to be solved or 
to be figured out.  Just bringing up conversation.

(*) An introduction to me

I don't understand floating-point numbers from the inside out, but I do know 
how to work with base 2 and scientific notation.  So the idea of expressing a 
number as 

  mantissa * base^{power}

is not foreign to me. (If that helps you to perhaps instruct me on what's going 
on here.)

(*) A presentation of the behavior

>>> import sys
>>> sys.version
'3.8.10 (tags/v3.8.10:3d8993a, May  3 2021, 11:48:03) [MSC v.1928 64 bit 
(AMD64)]'

>>> ls = [7.23, 8.41, 6.15, 2.31, 7.73, 7.77]
>>> sum(ls)
39.594

>>> ls = [8.41, 6.15, 2.31, 7.73, 7.77, 7.23]
>>> sum(ls)
39.61

All I did was to take the first number, 7.23, and move it to the last position 
in the list.  (So we have a violation of the commutativity of
addition.)

Let me try to reduce the example.  It's not so easy.  Although I could display 
the violation of commutativity by moving just a single number in the list, I 
also see that 7.23 commutes with every other number in the list.

(*) My request

I would like to just get some clarity.  I guess I need to translate all these 
numbers into base 2 and perform the addition myself to see the situation coming 
up?
-- 
https://mail.python.org/mailman/listinfo/python-list


RE: on floating-point numbers

2021-09-03 Thread Schachner, Joseph
What's really going on is that you are printing out more digits than you are 
entitled to.  39.61 :   16 decimal digits.   4e16 should require 55 
binary bits (in the mantissa) to represent, at least as I calculate it.

Double precision floating point has 52 bits in the mantissa, plus one assumed 
due to normalization.  So 53 bits.

The actual minor difference in sums that you see is because when you put the 
largest value 1st it makes a difference in the last few bits of the mantissa.

I recommend that you print out double precision values to at most 14 digits.  
Then you will never see this kind of issue.  If you don't like that suggestion, 
you can create your own floating point representation using a Python integer as 
the mantissa, so it can grow as large as you have memory to represent the 
value; and a sign and an exponent.  It would be slow, but it could have much 
more accuracy (if implemented to preserve accuracy).

By the way, this is why banks and other financial institutions use BCD (binary 
coded decimal).   They cannot tolerate sums that have fraction of a cent errors.

I should also point out another float issue: subtractive cancellation.   Try 
1e14 + 0.1  - 1e14. The result clearly should be 0.1, but it won't be.  
That's because 0.1 cannot be accurately represented in binary, and it was only 
represented in the bottom few bits.  I just tried it:   I got 0.09375   
This is not a Python issue.  This is a well known issue when using binary 
floating point.   So, when you sum a large array of data, to avoid these 
issues, you could either
1) sort the data smallest to largest ... may be helpful, but maybe not.
2) Create multiple sums of a few of the values.   Next layer: Sum a few of the 
sums.Top layer: Sum the sum of sums to get the final sum.  This is much 
more likely to work accurately than adding up all the values in one summation 
except the last, and then adding the last (which could be a relatively small 
value).  

--- Joseph S.







Teledyne Confidential; Commercially Sensitive Business Data

-Original Message-
From: Hope Rouselle  
Sent: Thursday, September 2, 2021 9:51 AM
To: python-list@python.org
Subject: on floating-point numbers

Just sharing a case of floating-point numbers.  Nothing needed to be solved or 
to be figured out.  Just bringing up conversation.

(*) An introduction to me

I don't understand floating-point numbers from the inside out, but I do know 
how to work with base 2 and scientific notation.  So the idea of expressing a 
number as 

  mantissa * base^{power}

is not foreign to me. (If that helps you to perhaps instruct me on what's going 
on here.)

(*) A presentation of the behavior

>>> import sys
>>> sys.version
'3.8.10 (tags/v3.8.10:3d8993a, May  3 2021, 11:48:03) [MSC v.1928 64 bit 
(AMD64)]'

>>> ls = [7.23, 8.41, 6.15, 2.31, 7.73, 7.77]
>>> sum(ls)
39.594

>>> ls = [8.41, 6.15, 2.31, 7.73, 7.77, 7.23]
>>> sum(ls)
39.61

All I did was to take the first number, 7.23, and move it to the last position 
in the list.  (So we have a violation of the commutativity of
addition.)

Let me try to reduce the example.  It's not so easy.  Although I could display 
the violation of commutativity by moving just a single number in the list, I 
also see that 7.23 commutes with every other number in the list.

(*) My request

I would like to just get some clarity.  I guess I need to translate all these 
numbers into base 2 and perform the addition myself to see the situation coming 
up?
-- 
https://mail.python.org/mailman/listinfo/python-list


RE: matplotlib questions

2021-08-27 Thread Schachner, Joseph
Complete documentation link (this link works) :
https://matplotlib.org/stable/contents.html

--- Joseph S.


Teledyne Confidential; Commercially Sensitive Business Data

-Original Message-
From: Steve  
Sent: Thursday, August 26, 2021 11:48 AM
To: python-list@python.org
Subject: matplotlib questions

I am trying to modify the "Bar Graph Demo" at 
https://matplotlib.org/stable/gallery/index.html,  Lines, bars, and markers but 
the more I experiment and change the code, the more messed up it becomes.  I 
have the demo code working. This is my second attempt.  I guess I accidentally 
got my first chart working but this second one, not so good.

Is there any source to help me understand how the code works and how to change 
it?
Among many others options, how do I change the font size? 
How are the labels placed on the X-axis and Y-axis?





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


RE: Defining a Python enum in a C extension - am I doing this right?

2021-07-30 Thread Schachner, Joseph
Instead of struggling to define an enum  in C that can be read in Python - I'm 
assuming you can pass strings back and forth - why not just print whatever you 
need to give to Python into a string (or maybe 2 strings) and send it to Python 
as string?   Python is a dynamic language, it can quickly build an enum  type 
from one string and instantiate enums of that type from the other string.  

In short, if you have problems creating an enum in C and passing it to Python, 
give the problems to Python! Let it create the enum.

--- Joseph S.


Teledyne Confidential; Commercially Sensitive Business Data

-Original Message-
From: Serhiy Storchaka  
Sent: Friday, July 30, 2021 4:22 AM
To: python-list@python.org
Subject: Re: Defining a Python enum in a C extension - am I doing this right?

23.07.21 11:20, Bartosz Golaszewski пише:
> I'm working on a Python C extension and I would like to expose a 
> custom enum (as in: a class inheriting from enum.Enum) that would be 
> entirely defined in C.

I think that it would be much easier to define it in Python, and then either 
import a Python module in your C code, or exec a Python code as a string.

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


Is there a conference in the US that is similar to EuroPython?

2021-07-19 Thread Schachner, Joseph
I am not going to fly to Europe for a Python conference.  But, would consider 
going if in the U.S.A.   Especially if drivable ... NYC area would be ideal.

I ask because I have seen ads for EuroPython over several years, and I don't 
remember seeing similar ads for something similar in the U.S.A.

--- Joseph S.

Teledyne Confidential; Commercially Sensitive Business Data
-- 
https://mail.python.org/mailman/listinfo/python-list


RE: learning python ...

2021-05-24 Thread Schachner, Joseph
OMG that is awful abuse of Python!  You have overloaded two Python keywords by 
making variables of that name.  As a result, float is no longer a type name, it 
is a variable name that refers to the value 6.67 !

Type(int) is int; type(float) is float, but isinstance(int,float) doesn't work 
because float is not a type in your script because you assigned float=6.67 and 
the local variable dictionary is searched first!

To fix this, make your variable name myfloat.   Change it wherever the variable 
name is wanted.  In particular, the last line should be 
print(isinstance(myfloat, float)).  The first argument is the variable, the 
second should be type name.

--- Joseph S.



Teledyne Confidential; Commercially Sensitive Business Data

-Original Message-
From: hw  
Sent: Sunday, May 23, 2021 3:34 PM
To: python-list@python.org
Subject: Re: learning python ...

On 5/23/21 7:28 PM, Peter Otten wrote:
> On 23/05/2021 06:37, hw wrote:
>>
>> Hi,
>>
>> I'm starting to learn python and have made a little example program 
>> following a tutorial[1] I'm attaching.
>>
>> Running it, I'm getting:
>>
>>
>> Traceback (most recent call last):
>>    File "[...]/hworld.py", line 18, in 
>>  print(isinstance(int, float))
>> TypeError: isinstance() arg 2 must be a type or tuple of types
>>
>>
>> I would understand to get an error message in line 5 but not in 18.  
>> Is this a bug or a feature?
> 
> It is a bug in your code (which you don't provide). Did you assign 
> some value to float, e. g.:
> 
>  >>> float = 42.0
>  >>> isinstance(int, float)
> Traceback (most recent call last):
>    File "", line 1, in 
>      isinstance(int, float)
> TypeError: isinstance() arg 2 must be a type or tuple of types
> 
> If you do not shadow the built-in you should get
> 
>  >>> isinstance(int, float)
> False
> 

Apparently the attachment was stripped from my message.  I'll put a smaller 
version directly into this message instead of an attachment:


#!/usr/bin/python

print("world!")

int = 17
print("world", int)

float = 6.670
print("world", float)

foo = 0
print(type(int))
print(type(float))
print(type(foo))

print(isinstance(foo, str))
print(isinstance(int, float))
print(isinstance(float, float))


I don't know about shadowing.  If I have defeated a whole variable type 
by naming a variable like a variable type, I would think it is a bad 
idea for python to allow this without warning.  It seems like a recipie 
for creating chaos.
-- 
https://mail.python.org/mailman/listinfo/python-list


RE: neoPython : Fastest Python Implementation: Coming Soon

2021-05-06 Thread Schachner, Joseph
"Slow" is in the eye of the beholder and depends on the job the needs to be 
done.  Where I work, we write scripts in Python that control our measuring 
instruments, make them acquire data and compute results, the Python script 
reads the results, compares results to limits, and eventually produces a lovely 
report.

In some scripts, we make the instrument acquire and save data and our Python 
script launches another program on the instrument that will read in the data 
and perform specified analysis.  That program can take a couple of minutes to 
complete.  If we have to do this for multiple runs we launch them at the same 
time and they finish at the same time, the time of one run.  So we are doing 
easy multiprocessing using Python.  

Now let's consider, if our controlling Python script were instead written in a 
highly optimized blazingly fast compiled language, how much faster could this 
script be?  It would still have to wait for the instrument to compute results; 
if running a separate analysis program it would still have to launch it 
(perhaps several of them) and wait for until they finished. I doubt the 
compiled script would finish even a second faster.

I think this kind of application is just perfect for Python.   We considered 
other (commercially supported) languages before we went with Python.  I'm very 
happy that we did.  We can find people who want to program in Python and 
already know Python.  I haven't yet seen an employee complaint about our 
scripts being written in Python, and I don't expect to.

-- Joseph S.


Teledyne Confidential; Commercially Sensitive Business Data
-- 
https://mail.python.org/mailman/listinfo/python-list


RE: .title() - annoying mistake

2021-03-19 Thread Schachner, Joseph
I agree.  If the documentation notes this issue, and the (possibly new) Python 
user has to replace the .title() with a different function that uses regular 
expression and a lambda function to work around the issue, then perhaps it's 
time for a proposal to address this.  Perhaps there needs to be an optional 
argument to .title() which if supplied should tell it do the workaround.   Or, 
perhaps better, only capitalize the first word and subsequent words that are 
preceded by a white space.  That should solve "Someone's Apostrophe" and 
"Hyphenated-expressions". Someone who looks into this should check if the 
second part of a hyphenated expression needs to be capitalized. 

--- Joseph S.   


Teledyne Confidential; Commercially Sensitive Business Data

-Original Message-
From: Abdur-Rahmaan Janhangeer  
Sent: Friday, March 19, 2021 11:02 AM
To: Paul Bryan 
Cc: Python 
Subject: Re: .title() - annoying mistake

Thanks very much!

That's annoying. You have to roll your own solution!

Kind Regards,

Abdur-Rahmaan Janhangeer
about  | blog 
 github 
Mauritius

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


RE: Python cannot count apparently

2021-02-08 Thread Schachner, Joseph
This code works:
mystr = "hello"
for ch in mystr:
print(ch, end="")

result is: hello

Note that the for loop does not use range.  Strings are iterable, that is they 
support Python's iteration protocol.  So, for ch in mystr: assigns one 
character from mystr to ch each time, each iteration gets the next character.  
To prevent each character from appearing on a separate line (in Python 3) you 
need end="".   That is, don't put in the usual end-of-line ending.

--- Joseph S.

Teledyne Confidential; Commercially Sensitive Business Data

-Original Message-
From: Michael F. Stemper  
Sent: Monday, February 8, 2021 9:19 AM
To: python-list@python.org
Subject: Re: Python cannot count apparently

On 07/02/2021 13.34, Philipp Daher wrote:
> Hello,
> 
> I recently coded this snippet of code:
> myString=„hello“
> for i in range(len(myString):
>   print(string[i])
> 
> And now for the weird part:
> 
> SOMETIMES, the output is this:
> 
> hello

Strange. When I fix the errors in what you posted:
- wrong character to start the string
- wrong variable name in the call to print()

I get[1]:


... myString="hello"
... for i in range(len(myString)):
...   print( myString[i] )
...
h
e
l
l
o
...

You must have done something to suppress the newlines after each call to 
print().

So it's quite obvious that the code you posted has very little to do with the 
code you ran. If you really want us to help, please directly copy and paste the 
exact code that you ran. We can't really help you with only guesses as to what 
you did.



[1] (leading > replaced with . to fool news clients)
--
Michael F. Stemper
Galatians 3:28
-- 
https://mail.python.org/mailman/listinfo/python-list


RE: IDE tools to debug in Python?

2021-02-05 Thread Schachner, Joseph
Indeed there are many.  One I have not seen listed here yet, that is quite 
light, starts quickly, but does have good debugging capability is PyScripter.  
Completely free, downloadable from SourceForge, 32 or 64 bit versions (must 
match your Python type).
--- Joseph S.


Teledyne Confidential; Commercially Sensitive Business Data

-Original Message-
From: Alan Gauld  
Sent: Friday, February 5, 2021 3:34 AM
To: python-list@python.org
Subject: Re: IDE tools to debug in Python?

On 27/01/2021 18:32, flaskee via Python-list wrote:
> 
> While print() is groovy and all,
> if anyone runs across a non-pdb python debugger (standalone or 
> IDE-based) please let me know.
> 

There are many. But why must it be non-pdb? That seems rather arbitrary.
Or do you really mean you want a non-command-line debugger?

One standalone option is winpdb
But most Python IDEs have basic debugging tools built in.


--
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: dict.get(key, default) evaluates default even if key exists

2020-12-18 Thread Schachner, Joseph
Yes.  In order to call D.get( ) it needs to pass two arguments.  The first is 
'a', simple.  The second is the result of a call to get_default().   So, that 
is called.  From INSIDE get_default() it prints 'Nobody expects this' but you 
should expect it,  get_default() gets executed.   Following that it prints '1', 
because the default value was NOT USED.   If it was used, you would see 'Nobody 
expects this' followed by 0.

--- Joseph S.

-Original Message-
From: Mark Polesky  
Sent: Tuesday, December 15, 2020 12:07 PM
To: python-list@python.org
Subject: dict.get(key, default) evaluates default even if key exists

Hi.

# Running this script

D = {'a':1}
def get_default():
    print('Nobody expects this')
    return 0
print(D.get('a', get_default()))

# ...generates this output:

Nobody expects this
1

###

Since I'm brand new to this community, I thought I'd ask here first... Is this 
worthy of a bug report?  This behavior is definitely unexpected to me, and I 
accidentally coded an endless loop in a mutual recursion situation because of 
it.  Calling dict.get.__doc__ only gives this short sentence: Return the value 
for key if key is in the dictionary, else default.  Nothing in that docstring 
suggests that the default value is evaluated even if the key exists, and I 
can't think of any good reason to do so.

Am I missing something?

Thanks,
Mark

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


RE: To check if number is in range(x,y)

2020-12-14 Thread Schachner, Joseph
>>> r = range(10)
So r is a list containing 0, 1, 2, 3, 4, 5, 6, 7, 8, 9

  >>> 2 in r
  True
As expected.

  >>> 2.5 in r
  False
Also as expected.  If you did int(floor(2.5)) in 5 that would be true.

  >>> r = range(1, 10, 2)
  >>> 2 in r
  False
  >>> list(r)
  [1, 3, 5, 7, 9]
Well, yes, because you started the range at 1.  Start at 0 and you'd get 0, 2, 
4, 6, 8.

"It also doesn't automatically convert from the string inputs you're getting 
from the input() function:

  >>> s = "5"
  >>> s in r
  False
  >>> int(s) in r
  True"
You have just discovered that Python, although it is dynamically typed, is 
STRICTLY typed.  Another way to say this: you have discovered that Python isn't 
the same as BASIC.  Yes, you have to convert strings to int or float, Python 
does not assume you want to if you did not do it. Similarly, you have to do 
something to convert int or float to text.  Python makes it very simple, but 
you have to do it.


"Additionally, note that the endpoint of the range is exclusive so
  >>> r = range(1, 10)
  >>> 10 in r
  False"

I don't have to note that, I KNOW that (as I've demonstrated above), because I 
read a couple of books on Python.  Python range starts on the number you 
specify and does NOT include the end number.
So: range(0,10) is 0 to 9(note that this is 10 integers)
  range(10,20) is 10 to 19(also 10 integers)
  range(20,30) is 20 to 29   (another 10 integers)

Now suppose that the end integer was not excluded. Each range call would 
produce 11 integers.  10, 20, and 30 would occur twice.  Or you'd have to set 
the range limits differently.

I recommend you read Python 101 and when you've done that, read Python 201.   I 
think they are very good "learn Python" books.
If you're surprised that the end point is not included in range, you need to 
read Python 101.

--- Joseph S.



-Original Message-
From: Tim Chase 
Sent: Saturday, December 12, 2020 11:51 AM
To: Bischoop 
Cc: Bischoop ; python-list@python.org
Subject: Re: To check if number is in range(x,y)

On 2020-12-12 15:12, Bischoop wrote:
> I need to check if input number is 1-5. Whatever I try it's not
> working. Here are my aproaches to the problem: https://bpa.st/H62A
>
> What I'm doing wrong and how I should do it?

A range is similar to a list in that it contains just the numbers
listed:

  >>> r = range(10)
  >>> 2 in r
  True
  >>> 2.5 in r
  False
  >>> r = range(1, 10, 2)
  >>> 2 in r
  False
  >>> list(r)
  [1, 3, 5, 7, 9]

It also doesn't automatically convert from the string inputs you're getting 
from the input() function:

  >>> s = "5"
  >>> s in r
  False
  >>> int(s) in r
  True

Additionally, note that the endpoint of the range is exclusive so

  >>> r = range(1, 10)
  >>> 10 in r
  False
  >>> list(r)
  [1, 2, 3, 4, 5, 6, 7, 8, 9]

If you want numeric-range checks, Python provides the lovely double-comparison 
syntax:

  >>> x = 5
  >>> 2 < x < 10
  True
  >>> x = 5.5
  >>> 2 < x < 10
  True
  >>> s = "5"
  >>> 2 < s < 10
  Traceback…
  >>> 2 < int(s) < 10
  True

Hopefully this gives you the hints that you need to troubleshoot.

-tkc






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


RE: linear algebric equations

2020-12-08 Thread Schachner, Joseph
Yes.  Import os, and use  os.system( ) to call your Fortran (or C) executable.  
If the executable saves results in a file or files, Python can read them in an 
format a nice overall report.  In html or xml, if you like.

Using Python as glue,  the execution time will be exactly what it was for your 
executable, because Python will call it; and in a second of so after it 
finishes Python can read in results and format whatever report you like.

--- Joseph S.

-Original Message-
From: Tito Sanò  
Sent: Monday, December 7, 2020 11:59 AM
To: python-list@python.org
Subject: linear algebric equations

Regarding the solution of linear algebraic equations I noticed a big difference 
in the computation

time in Python compared to the old fortran language.

I have compared both the linelg and lapack.dgesv-lapack.zgesv modules with the 
fortan: dgelg and f04adf. 

The difference in computation time is enormous:

for example for 430 degrees of freedom it is about 24 min in Python versus 
about 1 sec in fortran.

Is it possible to get better performance in Python?

Thanks in advance  

Tito Sano' 

Roma Italy

Cell: 339 6903895

 


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


RE: Letter replacer - suggestions?

2020-12-07 Thread Schachner, Joseph
The only comment I have is that you didn't check the inputs at all.  Suppose 
the word I type in is "1234".   1234 will turn into an int, not a string.
You can't index through an int, it's one thing.  So the program will probably 
throw an error.

If the word at least starts with a letter, then it will be a string.   If I say 
I want to replace "?" that may not exist in the string, but that's OK. 

 Joseph S. 

-Original Message-
From: Bischoop  
Sent: Monday, December 7, 2020 10:48 AM
To: python-list@python.org
Subject: Letter replacer - suggestions?


I worked on my wee script that replaces a letters: https://bpa.st/OYBQ .
I would like to have some suggestions about the code from more experienced 
programmers, the code does work and do its job but perhaps could work in a 
better way.

Thanks

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


RE: Question on ABC classes

2020-10-23 Thread Schachner, Joseph
I'm a C++ programmer and Python programmer as well.  Python classes are not 
exactly like C++ classes.

If you define a class where every method has an implementation, then it really 
isn't abstract.  It can be instantiated.  You can force it to be abstract by 
doing from abc import ABCMeta and declare class myclass(metaClass=ABCMeta).  
Otherwise, Python does not have a way to know that you intend the class to be 
abstract unless it contains an @abstractmethod that makes it actually abstract. 
  Such a method must be overridden.

Usually, an Abstract Base Class defines an interface.  You can make all the 
functions @abstractmethod, and separately make a another class that is based on 
your ABC and provides default implementations for all the functions.  Other 
classes can be based on that class.   I am not an authority on this so let me 
refer you to actual documentation:

See: https://docs.python.org/3/library/abc.html, that should help you. 

-Original Message-
From: Julio Di Egidio  
Sent: Thursday, October 22, 2020 12:26 PM
To: python-list@python.org
Subject: Question on ABC classes

Hello guys,

I am professional programmer but quite new to Python, and I am trying to get 
the grips of some peculiarities of the language.

Here is a basic question: if I define an ABC class, I can still instantiate the 
class unless there are abstract methods defined in the class.

(In the typical OO language the class would be not instantiable, period, since 
it's "abstract".  But this is not so in Python, to the point that, also for 
uniformity, I am feeling compelled to define an @abstractmethod __init__ in my 
ABC classes, whether they need one or not, and whether there are other abstract 
methods in the class or not.)

Now, I do read in the docs that that is as intended, but I am not understanding 
the rationale of it: why only if there are abstract methods defined in an ABC 
class is instantiation disallowed?  IOW, why isn't subclassing from ABC enough?

Thanks for any enlightenment,

Julio

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


RE: Python 3..9.0

2020-10-09 Thread Schachner, Joseph
You're not doing anything wrong, but clearly it's not what you want to do.  You 
are running the Python interpreter and not specifying any script to run, so it 
opens a command prompt and promptly closes it, I'll bet.  

What you want to do is open a development environment.  Try Idle, it's there in 
your Python installation.  Or download PyScripter, or Jetbrains' PyCharm, or 
Wing  (see recent new version announcement).   

--- Joseph S.

-Original Message-
From: jjall...@aol.com  
Sent: Thursday, October 8, 2020 12:59 PM
To: python-list@python.org
Subject: Fwd: Python 3..9.0


Hi,
I just downloaded the above for Windows but am unable to get it to run.  I have 
gone to the directory and double-clicked the "python.exe" file but that just 
brings me to the command prompt.
Any suggestions as to what I am doing wrong?
Thank you.
Joe
-- 
https://mail.python.org/mailman/listinfo/python-list


RE: What this error want to say? Can't we use return without function?

2020-09-08 Thread Schachner, Joseph
I see. You didn't declare a function, it's just a python script. So you don't 
need a return in that situation, the script just ends when there are no more 
lines.

By the way: you certainly don't want to return or quit BEFORE you print(nice).  
 But the fix here is simply to delete "return coun".  Then your script will run.

--- Joseph S.

-Original Message-
From: Shivlal Sharma  
Sent: Monday, September 7, 2020 3:09 AM
To: python-list@python.org
Subject: What this error want to say? Can't we use return without function?

N = int(input("enter a positive integer:")) coun = 1 while (N > 0):
coun = coun * N
N = N - 1
return coun
nice = ntime(N)
print(nice)


error: return outside of the function

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


RE: Output showing "None" in Terminal

2020-08-25 Thread Schachner, Joseph
The very first line of your function km_mi(): ends it:
def km_mi():
return answer

answer has not been assigned, so it returns None.

Advice: remove that "return" line from there.  Also get rid of the last line, 
answer = km_mi which makes answer refer to the function km_mi().
Put the "return answer" line at the end, where the "answer=km_mi" used to be.

That should help.  The code calculates "answer".   It prints "answer".   You 
should return "answer" at the end, after it has been calculated.

--- Joseph S.

-Original Message-
From: Py Noob  
Sent: Monday, August 24, 2020 9:12 AM
To: python-list@python.org
Subject: Output showing "None" in Terminal

Hi!

i'm new to python and would like some help with something i was working on from 
a tutorial. I'm using VScode with 3.7.0 version on Windows 7. Below is my code 
and the terminal is showing the word "None" everytime I execute my code.

Many thanks!

print("Conversion")

def km_mi():
return answer

selection = input("Type mi for miles or km for kilometers: ")

if selection == "mi":
n = int(input(print("Please enter distance in miles: ")))
answer = (1.6*n)
print("%.2f" % answer, "miles")

else:
n = float(input(print("Please enter distance in kilometers: ")))
answer = (n/1.6)
print("%.2f" % answer, "kilometers")

answer = km_mi

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


RE: Embedded python: How to debug code in an isolated way

2020-08-24 Thread Schachner, Joseph
Another suggestion:  If your Python code only references  few things outside of 
itself, make a simulated environment in Python on your PC, so that you can run 
your embedded code after importing your simulated environment, which should 
supply the functions it expects to call and variables it expects to access.

Then you can use any PC based debugger (PyScripter, Jetbrains' PyCharm, Visual 
Studio with Python support, etc) to debug in the simulated environment.

--- Joseph S.

-Original Message-
From: Grant Edwards  
Sent: Sunday, August 23, 2020 12:59 PM
To: python-list@python.org
Subject: Re: Embedded python: How to debug code in an isolated way

On 2020-08-22, Chris Angelico  wrote:
> On Sun, Aug 23, 2020 at 5:51 AM Eko palypse  wrote:
>> So the question is, what do I need to read/learn/understand in order to 
>> solve this issue?
>> Or in other words, how can I debug my script in an isolated environment.
>
> I'd go for the old standby - IIDPIO: If In Doubt, Print It Out!
> Instead of trying to use a debug harness, just run your code normally, 
> and print out whatever you think might be of interest. If you don't 
> have a console, well, that would be the first thing to do - you
> *always* need a console.

Yep.  Even if you have to bit-bang a tx-only UART on a GPIO pin.

I've had to do that many times, and the last time was only a couple years ago.  
Though I must admit I never had to do that _in_ Python or on a platform capable 
of running Python...

--
Grant




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


RE: why no camelCase in PEP 8?

2020-05-19 Thread Schachner, Joseph
I don't actually know, but I can take a guess.  CamelCase can be problematic 
with terms that are abbreviations and always upper case.  For example FIRFilter 
or USBPLL
The first violated camelCase because it has no lower case letters before 
Filter, and the second completely violates camelCase because both USB and PLL 
are well known always capitalized abbreviations so that name has no lower case 
letters.

On the other hand FIR_filter and USB_PLL have no problem showing where the 
split should be.

And, because '_' looks sort of like a space, the individual words are more 
easily readable.  notEveyoneThinksReadingCamelCaseIsEasy.

-- Joseph S.

-Original Message-
From: Lance E Sloan  
Sent: Monday, May 18, 2020 3:47 PM
To: python-list@python.org
Subject: why no camelCase in PEP 8?

I've been using Python for about 18 years.  Several things have changed in the 
language in those years.  I don't disagree with most of it, but one of the 
things that annoys me is the disapproval of using camelCase to name symbols 
such as variables, functions, etc.

I think PEP 8, the "Style Guide for Python Code" 
(https://www.python.org/dev/peps/pep-0008/), came out shortly after I began 
using Python.  I think the old habits of the people I worked with and the 
relative lack of tools like Flake8 and Pylint led to the standard being 
ignored.  However, now I see many developers really want to adhere to the 
standard.

My preference for using camelCase (in PEP 8, AKA mixedCase) is putting me at 
odds with my colleagues, who point to PEP 8 as "the rules".  I have reasons for 
my preferring camelCase.  I suspect the reasons the PEP 8 authors have for not 
using it are probably as strong as my reasons.  So our reasons probably nullify 
each other and what's left is simple preference.

So, I'd like to know what was the reason behind favoring snake_case (AKA 
lower_case_with_underscores) in PEP 8 instead of camelCase.

Does anyone in this group know?

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


RE: [RELEASE] Python 3.9.0a6 is now available for testing

2020-04-29 Thread Schachner, Joseph
> norm=lambda m: m+(m and(m[-1]!= '\n'and'\n'or'  ')or'\n')
Parentheses   1  2  
  1 0   
quotes 1  0 1   
0   1 01  0  

OK I don't see any violation of quoting or parentheses matching.   Still trying 
to figure out what this lambda does.

--- Joseph S.
 
-Original Message-
From: Robin Becker  
Sent: Wednesday, April 29, 2020 10:52 AM
To: Łukasz Langa ; python-list@python.org; 
python-annou...@python.org
Subject: Re: [RELEASE] Python 3.9.0a6 is now available for testing

On 28/04/2020 16:52, Łukasz Langa wrote:
> On behalf of the entire Python development community, and the currently 
> serving Python release team in particular, I’m pleased to announce the 
> release of Python 3.9.0a6. Get it here:
> 

thanks for the release; I tried to reply in the dev list, but failed miserably. 
Sorry for any noise.

I see this simple difference which broke some ancient code which works in 
Python 3.8.2



> $ python
> Python 3.8.2 (default, Apr  8 2020, 14:31:25) [GCC 9.3.0] on linux 
> Type "help", "copyright", "credits" or "license" for more information.
 norm=lambda m: m+(m and(m[-1]!='\n'and'\n'or'')or'\n')
 
> robin@minikat:~/devel/reportlab/REPOS/reportlab/tests
> $ python39
> Python 3.9.0a6 (default, Apr 29 2020, 07:46:29) [GCC 9.3.0] on linux 
> Type "help", "copyright", "credits" or "license" for more information.
 norm=lambda m: m+(m and(m[-1]!='\n'and'\n'or'')or'\n')
>   File "", line 1
> norm=lambda m: m+(m and(m[-1]!='\n'and'\n'or'')or'\n')
>  ^
> SyntaxError: invalid string prefix
 
> robin@minikat:~/devel/reportlab/REPOS/reportlab/tests
> $ python39 -X oldparser
> Python 3.9.0a6 (default, Apr 29 2020, 07:46:29) [GCC 9.3.0] on linux 
> Type "help", "copyright", "credits" or "license" for more information.
 norm=lambda m: m+(m and(m[-1]!='\n'and'\n'or'')or'\n')
>   File "", line 1
> norm=lambda m: m+(m and(m[-1]!='\n'and'\n'or'')or'\n')
>^
> SyntaxError: invalid string prefix
 


so presumably there has been some parser / language change which renders 
and'\n' illegal. Is this a real syntax error or an alpha issue? It looks like 
the tokenization has changed. Putting in the obvious spaces removes the syntax 
error.
--
Robin Becker

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


RE: Floating point problem

2020-04-20 Thread Schachner, Joseph
16 base 10 digits / log base10( 2) = 53.1508495182 bits.   Obviously, 
fractional bits don't exist, so 53 bits. If you note that the first non-zero 
digit as 4, and the first digit after the 15 zeroes was 2, then you got an 
extra bit. 54 bits.  Where did the extra bit come from?  It came from the IEEE 
format's assumption that the top bit of the mantissa of a normalized floating 
point value must be 1.  Since we know what it must be, there is no reason to 
use an actual bit for it.  The 53 bits in the mantissa do not include the 
assumed top bit.

Isn't floating point fun?

--- Joseph S.

-Original Message-
From: Pieter van Oostrum  
Sent: Sunday, April 19, 2020 7:49 AM
To: python-list@python.org
Subject: Re: Floating point problem

"R.Wieser"  writes:

> Souvik,
>
>> I have one question here. On using print(f"{c:.32f}") where c= 2/5 
>> instead of getting 32 zeroes I got some random numbers. The exact 
>> thing is 0.40002220446049250313 Why do I get this and not 
>> 32 zeroes?
>
> Simple answer ?   The conversion routine runs outof things to say.
>
> A bit more elaborate answer ? You should not even have gotten that many 
> zeroes after the 0.4.The precision of a 32-bit float is about 7 digits. 
> That means that all you can depend on is the 0.4 followed by 6 more digits. 
> Anything further is, in effect, up for grabs.
>
Most Python implementations use 64-bit doubles (53 bits of precision). See 
https://docs.python.org/3.8/tutorial/floatingpoint.html
--
Pieter van Oostrum
www: http://pieter.vanoostrum.org/
PGP key: [8DAE142BE17999C4]

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


RE: Python-list Digest, Vol 189, Issue 17

2019-06-17 Thread Schachner, Joseph
Please see https://docs.python.org/2/library/colorsys.html

And follow the links in there, read the FAQ. 

You'll find that python represents RGB values in three numeric values.  Very 
simple.  I believe scale is 0.0 to 1.0.

--- Joseph S.

-Original Message-
From: Python-list 
 On Behalf Of 
python-list-requ...@python.org
Sent: Monday, June 17, 2019 10:28 AM
To: python-list@python.org
Subject: Python-list Digest, Vol 189, Issue 17

---External Email---

Send Python-list mailing list submissions to
python-list@python.org

To subscribe or unsubscribe via the World Wide Web, visit
https://mail.python.org/mailman/listinfo/python-list
or, via email, send a message with subject or body 'help' to
python-list-requ...@python.org

You can reach the person managing the list at
python-list-ow...@python.org

When replying, please edit your Subject line so it is more specific than "Re: 
Contents of Python-list digest..."
-- 
https://mail.python.org/mailman/listinfo/python-list


RE: Design a function that finds all positive numbers

2019-04-09 Thread Schachner, Joseph
I'm willing to bet "sorted" is a sort of the list of strings.  The result is 
certainly not what I'd expect if the list contained numeric values.

So: make a new list that holds the values in your "Array" (which is probably a 
list) converted to numbers.  Sort the new list.  That should give you're a 
numerically sorted result.

After that, you can look through the negative numbers on the new list (they 
will all be before any positive value), and try to find the positive value in 
the new list.  Output the positive value.
Warning: keep track of the values you have already checked, and don't output 
the same value twice.  You the values you've already looked for into a set 
(sets do not ever store duplicate values, not important in this case) and check 
if a subsequent value is already in the set.  I say this because there are 
three -2 values, and two 2 values, but I think you only want to print 2 once.

--- Joseph S.


-Original Message-
From: Ben Bacarisse  
Sent: Tuesday, April 9, 2019 7:33 AM
To: python-list@python.org
Subject: Re: Design a function that finds all positive numbers

Ranjith Bantu  writes:

> A numeric array of length 'N' is given. you need to design a function 
> that finds all positive numbers in the array that have their opposites 
> in it swell. give the approach for solving the optimal average or best 
> case performance. answer will be your obsolute.
> Array: -7,4,-3, 2, 2, -8, -2, 3, 3, 7, -2, 3, -2
> sorted: -2, -2, -2 ,2 ,2, -3, 3, 3, 4, -7, 7, -8?
>
> can I solve any problems like this by learning python?

You need to learn how to solve problems as well as learning Python -- they go 
hand in hand -- but Python is a good language to get started with.

> if anybody
> knows this answer or any mistakes in this question, please explain to 
> me in detail?

That would require quite a long essay!  As to the question, it's a bit odd to 
talk of opposites, but it's not ambiguous.  More problematic is what to do with 
duplicates.  The question should be worded so that it's either clear what is 
wanted, or so that it is clear that you should decide what to do.

--
Ben.

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


RE: scalable bottleneck

2019-04-04 Thread Schachner, Joseph
If you are using Python 3, range does not create at list, it is a generator.   
If you're using Python 2.x, use xrange instead of range.  xrange is a 
generator.   In Python 3 there is no xrange, they just made range the generator.

--- Joseph S.

-Original Message-
From: Sayth Renshaw  
Sent: Wednesday, April 3, 2019 5:42 PM
To: python-list@python.org
Subject: scalable bottleneck

In an email, I received this question as part of a newsletter.

def fetch_squares ( max_root ):
squares = []
for x in range ( max_root ):
squares . append (x **2)
return squares

MAX = 5

for square in fetch_squares (MAX ):
 do_something_with ( square )

1) Do you see a memory bottleneck here? If so, what is it?
2) Can you think of a way to fix the memory bottleneck?

Want to know if I am trying to solve the correct bottleneck.
I am thinking that the bottleneck is to create a list only to iterate the same 
list you created sort of doubling the time through.

Is that the correct problem to solve?

If it is then I thought the best way is just to supply the numbers on the fly, 
a generator.

def supply_squares(max_root):
for x in max_root:
yield x

MAX = 5


So then I set up a loop and do whatever is needed. At this time I am creating 
generator objects. But is this the correct way to go? More of a am I thinking 
correctly questino.

item = 0
while item < MAX:
print(supply_squares(item))
item += 1




Thanks

Sayth

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


RE: Syntax for one-line "nonymous" functions in "declaration style"

2019-04-01 Thread Schachner, Joseph
Re: ">> Neither i like how a function magically turns into a generator if the 
>> keyword `yield` appears somewhere within its definition.

> I agree, there should have been a required syntactic element on the "def"
> line as well to signal it immediately to the reader. It won't stop me from 
> using them, though."

One way to save people looking at the code from having to look through a 
function for a yield statement to see if it is a generator would be to add a 
"""doc string""" immediately after the function def, saying that it is a 
generator
and describing what it does.  I realize I'm calling on the programmer to 
address this issue by adding doc strings.  Nonetheless adding doc strings is a 
good habit to get in to.
--- Joseph S.
-Original Message-
From: Ian Kelly  
Sent: Sunday, March 31, 2019 3:45 PM
To: Python 
Subject: Re: Syntax for one-line "nonymous" functions in "declaration style"

On Sun, Mar 31, 2019 at 1:09 PM Alexey Muranov 
wrote:
>
> On dim., Mar 31, 2019 at 6:00 PM, python-list-requ...@python.org wrote:
> > On Sat, Mar 30, 2019, 5:32 AM Alexey Muranov 
> > 
> > wrote:
> >
> >>
> >>  On ven., Mar 29, 2019 at 4:51 PM, python-list-requ...@python.org
> >> wrote:
> >>  >
> >>  > There could perhaps be a special case for lambda expressions 
> >> such  >  that,  > when they are directly assigned to a variable, 
> >> Python would use the  > variable name as the function name. I 
> >> expect this could be  >  accomplished by  > a straightforward 
> >> transformation of the AST, perhaps even by just  >  replacing  > 
> >> the assignment with a def statement.
> >>
> >>  If this will happen, that is, if in Python assigning a 
> >> lambda-defined  function to a variable will mutate the function's 
> >> attributes, or else,  if is some "random" syntactically-determined 
> >> cases
> >>
> >>  f = ...
> >>
> >>  will stop being the same as evaluating the right-hand side and  
> >> assigning the result to "f" variable, it will be a fairly good 
> >> extra  reason for me to go away from Python.
> >>
> >
> > Is there a particular reason you don't like this? It's not too 
> > different from the syntactic magic Python already employs to support 
> > the 0-argument form of super().
>
> I do not want any magic in a programming language i use, especially if 
> it breaks simple rules.
>
> I do not like 0-argument `super()` either, but at least I do not have 
> to use it.

Well, you wouldn't have to use my suggestion either, since it only applies to 
assignments of the form "f = lambda x: blah". As has already been stated, the 
preferred way to do this is with a def statement. So just use a def statement 
for this, and it wouldn't affect you (unless you *really* want the function's 
name to be "" for some reason).

That said, that's also the reason why this probably wouldn't happen. Why go to 
the trouble of fixing people's lambda assignments for them when the preferred 
fix would be for them to do it themselves by replacing them with def statements?

> Neither i like how a function magically turns into a generator if the 
> keyword `yield` appears somewhere within its definition.

I agree, there should have been a required syntactic element on the "def"
line as well to signal it immediately to the reader. It won't stop me from 
using them, though.

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


RE: Multiprocessing vs subprocess

2019-03-12 Thread Schachner, Joseph
Re: " My understanding (so far) is that the tradeoff of using multiprocessing 
is that my manager script can not exit until all the work processes it starts 
finish. If one of the worker scripts locks up, this could be problematic. Is 
there a way to use multiprocessing where processes are launched independent of 
the parent (manager) process?"

I just want to point out that subprocess (which uses the operating system to 
start another processes, to run whatever you say - doesn't have to be Python 
running another script, can be an .exe)  does not have that restriction.  The 
subprocess call can be blocking (the caller waits), or not.   If not the caller 
can do whatever it wants including decide not to wait forever, and it can even 
exit.  

Of course, if one of the processes you launched is locked up that is a problem 
all by itself, even thought the manager can exit.

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


RE: Why float('Nan') == float('Nan') is False

2019-02-13 Thread Schachner, Joseph
Because all comparisons with NAN return false, that's the spec.  is NAN > 0? 
False.  Is NAN< 0?   False.  Is NAN == 0?  False.  Is NAN == ? False. 
So: Is NAN == NAN? False. And one more:  Is NAN < 1.0e18? False

This makes some sense because NAN is Not A Number, so any comparison to a 
number fails.

--- Joseph S. 
-Original Message-
From: ast  
Sent: Wednesday, February 13, 2019 8:21 AM
To: python-list@python.org
Subject: Why float('Nan') == float('Nan') is False

Hello

 >>> float('Nan') == float('Nan')
False

Why ?

Regards


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


RE: The sum of ten numbers inserted from the user

2019-02-07 Thread Schachner, Joseph
I just realized that input has changed in Python 3 and I was using Python 
2.7.13 with from __future__ import print_function and some others, but not that.
In Python 3 the int( ) or float( ) cast is necessary because input( ) does what 
raw_input( ) did in Python 2; raw_input( ) name is therefore removed.

--- Joe S.

From: Ian Clark 
Sent: Thursday, February 7, 2019 1:27 PM
To: Schachner, Joseph 
Cc: python-list@python.org
Subject: Re: The sum of ten numbers inserted from the user

This is my whack at it, I can't wait to hear about it being the wrong big o 
notation!

numbers=[]

while len(numbers) < 10:
try:
chip = int(input('please enter an integer: '))
except ValueError:
print('that is not a number, try again')
else:
numbers.append(chip)

print(sum(numbers))


On Thu, Feb 7, 2019 at 10:23 AM Schachner, Joseph 
mailto:joseph.schach...@teledyne.com>> wrote:
Well of course that doesn't work.  For starters, x is an int or a float value.  
After the loop It holds the 10th value.  It might hold 432.7 ...   It is not a 
list.
The default start for range is 0.  The stop value, as you already know, is not 
part of the range.  So I will use range(10).

In the second loop, I think you thought x would be a list and you I'm sure you 
wanted to do
for y in x:
but instead you did
for y in range(x)
 and remember x might be a very large number.So the second loop would loop 
that many times, and each pass it would assign y (which has first value of 0 
and last value of whatever x-1 is) to sum.  Even though its name is "sum" it is 
not a sum.  After the loop it would hold x-1.  You wanted to do  sum += y.
Or sum = sum + y.   I prefer the former, but that could reflect my history as a 
C and C++ programmer.

And then you printed y, but you really want to print sum  (assuming that sum 
was actually the sum).

Putting all of the above together, you want to do this:

vallist =[] # an empty list, so we can append to it
for n in range(10):
x = input("Insert a number: ")# get 1 number into x
vallist.append(x)  # append it to our list

# Now vallist holds 10 values

sum = 0   # No need to start sum as a float, in Python if we add a float to an 
integer the result will be float. It doesn't matter in the program if sum is 
int or float.
for y in vallist:
 sum += y

print( "The sum is: ", sum)



-Original Message-
From: ^Bart mailto:gabriele1nos...@hotmail.com>>
Sent: Thursday, February 7, 2019 6:30 AM
To: python-list@python.org<mailto:python-list@python.org>
Subject: The sum of ten numbers inserted from the user

I thought something like it but doesn't work...

for n in range(1, 11):
 x = input("Insert a number: ")

for y in range(x):
 sum = y

 print ("The sum is: ",y)

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


RE: The sum of ten numbers inserted from the user

2019-02-07 Thread Schachner, Joseph
Well of course that doesn't work.  For starters, x is an int or a float value.  
After the loop It holds the 10th value.  It might hold 432.7 ...   It is not a 
list.
The default start for range is 0.  The stop value, as you already know, is not 
part of the range.  So I will use range(10).

In the second loop, I think you thought x would be a list and you I'm sure you 
wanted to do 
for y in x:
but instead you did 
for y in range(x)
 and remember x might be a very large number.So the second loop would loop 
that many times, and each pass it would assign y (which has first value of 0 
and last value of whatever x-1 is) to sum.  Even though its name is "sum" it is 
not a sum.  After the loop it would hold x-1.  You wanted to do  sum += y.
Or sum = sum + y.   I prefer the former, but that could reflect my history as a 
C and C++ programmer.

And then you printed y, but you really want to print sum  (assuming that sum 
was actually the sum).

Putting all of the above together, you want to do this:

vallist =[] # an empty list, so we can append to it
for n in range(10):
x = input("Insert a number: ")# get 1 number into x
vallist.append(x)  # append it to our list

# Now vallist holds 10 values

sum = 0   # No need to start sum as a float, in Python if we add a float to an 
integer the result will be float. It doesn't matter in the program if sum is 
int or float.
for y in vallist:
 sum += y

print( "The sum is: ", sum)



-Original Message-
From: ^Bart  
Sent: Thursday, February 7, 2019 6:30 AM
To: python-list@python.org
Subject: The sum of ten numbers inserted from the user

I thought something like it but doesn't work...

for n in range(1, 11):
 x = input("Insert a number: ")

for y in range(x):
 sum = y

 print ("The sum is: ",y)

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


RE: Exercize to understand from three numbers which is more high

2019-01-29 Thread Schachner, Joseph
Yes, that works.  Assuming it was correctly formatted when you ran it.
The formatting could not possibly be run in a Python interpreter, I think.

--- Joseph S.

From: Adrian Ordona 
Sent: Tuesday, January 29, 2019 2:52 PM
To: Schachner, Joseph 
Cc: Dan Sommers <2qdxy4rzwzuui...@potatochowder.com>; python-list@python.org
Subject: Re: Exercize to understand from three numbers which is more high

i'm also a beginner reading all the replies helps.
i was trying the problem myself and came up with the below code with a users 
input.


num1 = int(input("Enter first number: "))num2 = int(input("Enter second number: 
"))num3 = int(input("Enter third number: "))if num1 > num2 and num1 > num3:
print(num1, " is th max number")elif num2 > num1 and num2 > num3:
print(num2, " is the max number")else:     print(num3, "is the max number")

On Tue, Jan 29, 2019 at 1:48 PM Schachner, Joseph 
mailto:joseph.schach...@teledyne.com>> wrote:
Explanation: 5 > 4 so it goes into the first if.  5 is not greater than 6, so 
it does not assign N1 to MaxNum.  The elif (because of the lack of indent) 
applies to the first if, so nothing further is executed. Nothing has been 
assigned to MaxNum, so that variable does not exist.  You're right, it does not 
work.

How about this:
Mylist = [ N1, N2, N3]
Maxnum = N1
for value in Mylist:
if value > Maxnum:
Maxnum = value
print(Maxnum)

Or were lists and for loops excluded from this exercise?
--- Joe S.

On 1/29/19 9:27 AM, Jack Dangler wrote:

> wow. Seems like a lot going on. You have 3 ints and need to determine
> the max? Doesn't this work?
>
> N1, N2, N3
>
> if N1>N2
>if N1>N3
>  MaxNum = N1
> elif N2>N3
>MaxNum = N2
> elif N1MaxNum = N3

No.  Assuing that you meant to include colons where I think you did, what if 
(N1, N2, N3) == (5, 4, 6)?

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


RE: Exercize to understand from three numbers which is more high

2019-01-29 Thread Schachner, Joseph
Explanation: 5 > 4 so it goes into the first if.  5 is not greater than 6, so 
it does not assign N1 to MaxNum.  The elif (because of the lack of indent) 
applies to the first if, so nothing further is executed. Nothing has been 
assigned to MaxNum, so that variable does not exist.  You're right, it does not 
work.

How about this:
Mylist = [ N1, N2, N3]
Maxnum = N1
for value in Mylist:
if value > Maxnum:
Maxnum = value
print(Maxnum)

Or were lists and for loops excluded from this exercise?
--- Joe S.

On 1/29/19 9:27 AM, Jack Dangler wrote:

> wow. Seems like a lot going on. You have 3 ints and need to determine 
> the max? Doesn't this work?
> 
> N1, N2, N3
> 
> if N1>N2
>    if N1>N3
>      MaxNum = N1
> elif N2>N3
>    MaxNum = N2
> elif N1    MaxNum = N3

No.  Assuing that you meant to include colons where I think you did, what if 
(N1, N2, N3) == (5, 4, 6)?

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


What is your experience porting Python 2.7.x scripts to Python 3.x?

2019-01-22 Thread Schachner, Joseph
In the company I work for we have a program (free) that runs scripts (that we 
sell) to test according to particular standards.  The program embeds a Python 
interpreter, and the scripts are Python (which uses functions revealed to 
Python from within the program).

Well, this year must be time ... I've told my manager that we need to change 
from Python 2.7.13 (the last version to which I updated it) to Python 3.x, 
whatever the latest is, sometime this year and to get that on our roadmap. I 
should mention that updating from earlier 2.x versions through 2.7.13 has not 
caused any errors or problems in our scripts.  I guess that is as expected.

I've read about the 2to3 utility, and I think our Python code is pretty simple 
... I don't expect much beyond changing print to print( ) wherever it occurs 
(we capture stdout and stderr and emit what we get to a file, that can be very 
helpful). There are Python function calls to C functions that are callable from 
Python in our program but that should not be a problem, they are known to be 
functions.  Still, I am concerned; I have never tried using 2to3 so I can't 
give a justifiable estimate of how long this migration might take.

For anyone who has moved a substantial bunch of Python 2 to Python 3,   can you 
please reply with your experience?  Did you run into any issues?   Did 2to3 do 
its job well, or did you have to review its output to eliminate some working 
but silly thing?

Thank you, anyone who replies, for replying.

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


RE: Pythonic Y2K

2019-01-17 Thread Schachner, Joseph
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


RE: get the terminal's size

2019-01-14 Thread Schachner, Joseph
I just tested the fix I proposed, in Python 2.7.13

Code:
from win32api import GetSystemMetrics

def main():
print "Width =", GetSystemMetrics(0)
print "Height =", GetSystemMetrics(1)

if __name__ == '__main__':
main()

Result:
Width = 1536
Height = 864

-Original Message-
From: Alex Ternaute  
Sent: Monday, January 14, 2019 6:58 AM
To: python-list@python.org
Subject: get the terminal's size

Hi there,

I want to know the number of columns of the terminal where python2 writes it's 
outputs.

In a terminal, I type
$ echo $COLUMNS
100

But in Python, os.getenv("COLUMNS") gets nothing.
It gets nothing as well if I try to read the output of "echo $COLUMNS" 
from a subprocess.

I feel that I'm missing something but what ?

Looking on the internet for a hint, I see that python3 has an 
os.get_terminal_size(). 
Please, is there something similar for python2 ?

Cheers
--
Alex

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


RE: get the terminal's size

2019-01-14 Thread Schachner, Joseph
Note sure why you couldn't capture $ echo $COLUMNS from a subprocess call.  
But, how about this (found on the web):

from win32api import GetSystemMetrics
 
print "Width =", GetSystemMetrics(0)
print "Height =", GetSystemMetrics(1)

-Original Message-
From: Alex Ternaute  
Sent: Monday, January 14, 2019 6:58 AM
To: python-list@python.org
Subject: get the terminal's size

Hi there,

I want to know the number of columns of the terminal where python2 writes it's 
outputs.

In a terminal, I type
$ echo $COLUMNS
100

But in Python, os.getenv("COLUMNS") gets nothing.
It gets nothing as well if I try to read the output of "echo $COLUMNS" 
from a subprocess.

I feel that I'm missing something but what ?

Looking on the internet for a hint, I see that python3 has an 
os.get_terminal_size(). 
Please, is there something similar for python2 ?

Cheers
--
Alex

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


RE: Python read text file columnwise

2019-01-14 Thread Schachner, Joseph
About the original question:   If I were you, I would put the 3 numbers into a 
list (or a tuple, if you don't need to modify them) and put this into a 
dictionary.  The key would be the date & time string.

Then, if you need to find a particular entry you can look it up by date and 
time.  But I suspect, since you want column access, you won't need to do that.  
You can iterate through the entries in the dictionary easily and extract the 
data from a column, or from all the columns, if that’s what you want.

for entry in mydict:
value = entry.datalist[0]   # I hope I have the syntax correct


Now, what you do with value is up to you.  I think personally rather than 
building a list I would make a generator function.  A generator uses a "yield" 
statement to return a value, and it waits in that state.  The next time you 
call it it continues and returns the next value.  Kind of useful when the 
alternative is making and passing around huge lists.

--- Joseph S.

-Original Message-
From: DL Neil  
Sent: Saturday, January 12, 2019 4:48 PM
To: python-list@python.org
Subject: Re: Python read text file columnwise

On 12/01/19 1:03 PM, Piet van Oostrum wrote:
> shibashib...@gmail.com writes:
> 
>> Hello
>>>
>>> I'm very new in python. I have a file in the format:
>>>
>>> 2018-05-31  16:00:0028.90   81.77   4.3
>>> 2018-05-31  20:32:0028.17   84.89   4.1
>>> 2018-06-20  04:09:0027.36   88.01   4.8
>>> 2018-06-20  04:15:0027.31   87.09   4.7
>>> 2018-06-28  04.07:0027.87   84.91   5.0
>>> 2018-06-29  00.42:0032.20   104.61  4.8
>>
>> I would like to read this file in python column-wise.
>>
>> I tried this way but not working 
>>event_list = open('seismicity_R023E.txt',"r")
>>  info_event = read(event_list,'%s %s %f %f %f %f\n');


To the OP:

Python's standard I/O is based around data "streams". Whilst there is a concept 
of "lines" and thus an end-of-line character, there is not the idea of a 
record, in the sense of fixed-length fields and thus a defining and distinction 
between data items based upon position.

Accordingly, whilst the formatting specification of strings and floats might 
work for output, there is no equivalent for accepting input data. 
Please re-read refs on file, read, readline, etc.


> Why would you think that this would work?

To the PO:

Because in languages/libraries built around fixed-length files this is 
how one specifies the composition of fields making up a record - a data 
structure which dates back to FORTRAN and Assembler on mainframes and 
other magtape-era machines.

Whilst fixed-length records/files are, by definition, less flexible than 
the more free-form data input Python accepts, they are more efficient 
and faster in situations where the data (format) is entirely consistent 
- such as the OP is describing!


-- 
Regards =dn

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


RE: the python name

2019-01-02 Thread Schachner, Joseph
Python was started in the late 1980s by Guido Van Rossum, who (until quite 
recently) was the Benevolent Dictator for Life of Python.  His recent strong 
support of Type Annotation was what got it passed - and having to fight for it 
was what convinced him retire from the role of BDFL.  Anyway, at the time, he 
picked the name because he liked Monty Python's Flying Circus. At least, so I 
have read.  

If you don't know what Monty Python's Flying Circus was, I recommend looking 
for YouTube video snippets of it.  (You'll know you've found enough when you 
know the answer to "What's on the telly?" is "There's a penguin on the telly".) 
  

The name "Python" may not make sense, but what sense does the name Java make, 
or even C (unless you know that it was the successor to B), or Haskell or 
Pascal or even BASIC?  Or Caml or Kotlin or Scratch?  Or Oberon or R? Or 
Smalltalk, or SNOBOL?

By the way, C was 50 years old in 2018.  And C++ is still mostly backward 
compatible to C.  int, float, double and char are (still) not objects.   
Strings and arrays are not classes (and so do not have iterators, unless you 
create them).  Until C++ 2014, there was no threading library as part of C++ 
standard. Even though now there is, it's seems to be to be old school.  Look at 
Go (language) to see how concurrency can be built into the language instead of 
made available for optional use. 

 Joseph S.


-Original Message-
From: pritanshsahs...@gmail.com  
Sent: Tuesday, January 1, 2019 1:39 AM
To: python-list@python.org
Subject: the python name

why did you kept this name? i want to know the history behind this and the name 
of this snake python.

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


RE: question on the 'calendar' function

2018-11-20 Thread Schachner, Joseph
It's possible I don't understand the question.  The calendar functions are NOT 
limited to this year or any limited range.

Example:
import calendar
print( calendar.monthcalendar(2022, 12) )

Prints lists of dates in each week of December 2022.  It prints:
[[0, 0, 0, 1, 2, 3, 4], [5, 6, 7, 8, 9, 10, 11], [12, 13, 14, 15, 16, 17, 18], 
[19, 20, 21, 22, 23, 24, 25], [26, 27, 28, 29, 30, 31, 0]]

So, Dec 1 is a Wednesday; Dec 31 is a Saturday.  

That's 49 months ahead of this month.   Change the year and month to any 
(valid) number, and it will do what it does.  
The only caveat is that if the moon's orbit slows down as it gets farther away 
from the earth and the earth's rotation speed changes, then the calculations 
done by calendar for leap years may not be correct about the distant future.

--- Joseph S.


-Original Message-
From: o1bigtenor  
Sent: Tuesday, November 20, 2018 8:37 AM
To: python-list@python.org
Subject: question on the 'calendar' function

Greetings

I am in the process of learning my first computer programming language (unless 
g-code counts and then it is my second - - - grin). It definitely is a big 
world out there.

The calendar function has a lot of versatility and shows care in its 
development.

There is one area where I don't understand if I even could use this function or 
if I need to look to something(s) else to achieve what I need.

For planning I need to be able to easily look backward 6 months and forward at 
least 12 and better 18 months and would prefer perhaps even a total of 36 (and 
even 60 might be useful) months of calendar available. It could be useful to 
see the longer time spans as weeks rather than as days but seeing the larger 
time frames only as months would enable the planning that I need to do.

Do I need to (somehow and I have no idea how) extend the calendar function?
Is there some other way of displaying dates/calendars that would allow me to 
achieve my needed span?

TIA

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


RE: Python Enhancement Proposal for List methods

2018-10-22 Thread Schachner, Joseph
I agree with others that I don't see a compelling need to add these to Python, 
since they are all easy to implement in a few lines.

But what I really want to say is that Python tries hard to be easily readable 
and easily understood, by any reader.  List.removeall( ) that does not remove 
all elements, but all occurrences of a value passed to it, does not seem to me 
to meet that goal.  Even if you implement this as a function I encourage to 
think of a better name than removeall.  

--- Joseph S.



-Original Message-
From: Siva Sukumar Reddy  
Sent: Sunday, October 21, 2018 8:37 AM
To: python-list@python.org; python-id...@python.org
Subject: Python Enhancement Proposal for List methods

Hey everyone,

I am really new to Python contribution community want to propose below methods 
for List object. Forgive me if this is not the format to send an email.

1. *list.replace( item_to_be_replaced, new_item )*: which replaces all the 
occurrences of an element in the list instead of writing a new list 
comprehension in place.
2. *list.replace( item_to_be_replaced, new_item, number_of_occurrences )*:
which replaces the occurrences of an element in the list till specific number 
of occurrences of that element. The number_of_occurrences can defaulted to 0 
which will replace all the occurrences in place.
3. *list.removeall( item_to_be_removed )*: which removes all the occurrences of 
an element in a list in place.

What do you think about these features?
Are they PEP-able? Did anyone tried to implement these features before?
Please let me know.

Thank you,
Sukumar

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


RE: [OT] master/slave debate in Python

2018-09-26 Thread Schachner, Joseph
This really is an amazing discussion.  I actually do understand why "master" 
and "slave" might make people uncomfortable, although the meaning is quite 
clear.  Perhaps we need a currently used alternative:
1) Captain and Private
2) Manager and employee
3) CEO and Peon
4) Controller and Controlled
5) Commander and executer

You might not like any of these. That's OK, my goal was just to show that the 
relationship can be expressed without using outdated terms that some find 
objectionable.
These all have pretty much the same relationship (first one says what to do, 
second one does it) but I think any one of them feels more "comfortable" 
now-a-days than Master and Slave.

--- Joe S.

-Original Message-
From: Paul Moore  
Sent: Wednesday, September 26, 2018 11:41 AM
To: Ian Kelly 
Cc: Python 
Subject: Re: [OT] master/slave debate in Python

On Wed, 26 Sep 2018 at 16:30, Ian Kelly  wrote:

> Also: a human slave is not "a person being treated like a computer"
> and I find it highly disrespectful that you would move to trivialize 
> slavery like that.

I have no idea what it must feel like to be a slave (other than the trite and 
obvious idea that "it must be awful"). Unfortunately, debates like this do 
nothing to help me understand or empathise with the people suffering in that 
way, or people dealing with the aftermath of historical cases.

I'm more than happy to ensure that we are not causing pain or being 
disrespectful of the suffering of others, but rather than simply making the 
whole issue feel like a censorship debate, I'd rather we were helping people to 
understand and empathise, so that they would *of their own accord* act in an 
appropriate way. Self-censorship based on understanding and empathy is far more 
reasonable than any sort of externally-imposed rules.

But discussing what it means to be a slave, or the implications of slavery on 
our culture(s) is way off-topic for this list, so I'd prefer not to debate it 
further here. I'm sure anyone interested in understanding more can easily find 
more appropriate forums to participate in.

Paul

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


RE: Why emumerated list is empty on 2nd round of print?

2018-09-07 Thread Schachner, Joseph
The question "If I do this "aList = enumerate(numList)", isn't it stored 
permanently in aList now?  I see your point to use it directly, but just in 
case I do need to hang onto it from one loop to another, then how is that done?"
Reflects that you are thinking in a C++ kind of way I think.  

When you declare a variable name and assign to it, in Python what you have done 
is assigned to the name a reference to the content.   It is never true that the 
content is "in" the variable.  The variable does not have storage for what you 
assign to it.  That content is stored somewhere, but the variable just has a 
reference to it.

So, aList = enumerate(numList) creates an iterator, and aList is a reference to 
that iterator.  It is not "in" aLIst.   Despite the name, aList does not 
contain a list.  (See above).

Now, on to the second part: the problem you showed - that you can only loop 
through aList:print(i,j) once - is BECAUSE you hung onto it from one loop to 
another.  Once the iterator is exhausted, it's exhausted.  

Think of another more common iterator you've probably used:  file = 
open("filename.txt") for line in file;print line
On EOF the iterator throws an exception (that is expected), the for loop 
catches the exception and exits.  
Files can be "rewound" by file.seek(0).  But other than that, once you have 
reached EOF, you have reached EOF.  It doesn't automagically rewind.  If you do 
another for line in file;  print line  it will not print anything.  
Exactly the same behavior as you are surprised about for the enumerate iterator.

I don’t even know if there is a method to reset the enumerate iterator.  If 
there isn't one, then you should not hold the iterator from one loop to the 
next, you have to make another one.

--- Joe S.

-Original Message-
From: Viet Nguyen  
Sent: Thursday, September 6, 2018 2:50 PM
To: python-list@python.org
Subject: Re: Why emumerated list is empty on 2nd round of print?

On Thursday, September 6, 2018 at 10:34:19 AM UTC-7, Chris Angelico wrote:
> On Fri, Sep 7, 2018 at 3:26 AM, Viet Nguyen via Python-list 
>  wrote:
>  numList
> > [2, 7, 22, 30, 1, 8]
> >
>  aList = enumerate(numList)
> >
>  for i,j in aList:print(i,j)
> >
> > 0 2
> > 1 7
> > 2 22
> > 3 30
> > 4 1
> > 5 8
> >
>  for i,j in aList:print(i,j)
> >
> 
> 
> Because it's not an enumerated list, it's an enumerated iterator.
> Generally, you'll just use that directly in the loop:
> 
> for i, value in enumerate(numbers):
> 
> There's generally no need to hang onto it from one loop to another.
> 
> ChrisA

Thanks ChrisA. If I do this "aList = enumerate(numList)", isn't it stored 
permanently in aList now?  I see your point to use it directly, but just in 
case I do need to hang onto it from one loop to another, then how is that done? 
  Anyway I think I'm ok and I got what I need for now.

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


Guilty as charged

2018-07-27 Thread Schachner, Joseph
Re: "...while

   thing == None
would work perfectly in almost all cases in practice, it's unidiomatic and 
suggests the writer isn't quite comfortable with the workings of the language"

I admit, I've been a C++ programmer for many years and a Python programmer for 
only about 5 years.  But, I did learn something here.  I've read books on 
Python and somehow still did not know that None is guaranteed to be a singleton 
in all implementations, and that not only does "thing is None" therefore work 
(guaranteed), but that that is the Pythonic thing to do.  ...   Maybe I missed 
it, but I'll remember it now.

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


RE: Checking whether type is None

2018-07-25 Thread Schachner, Joseph
While I appreciate that use of "is" in   thing is None, I claim this relies on 
knowledge of how Python works internally, to know that every None actually is 
the same ID (the same object) - it is singular.  That probably works for 0 and 
1 also but you probably wouldn't consider testing   thing is 1, at least I hope 
you wouldn't.  thing is None looks just as odd to me.  Why not thing == None ?  
That works.

--- Joseph S.

-Original Message-
From: Tobiah  
Sent: Tuesday, July 24, 2018 3:33 PM
To: python-list@python.org
Subject: Checking whether type is None

Consider:

>>> type({}) is dict
True
>>> type(3) is int
True
>>> type(None) is None
False

Obvious I guess, since the type object is not None.
So what would I compare type(None) to?

>>> type(None)

>>> type(None) is NoneType
Traceback (most recent call last):
  File "", line 1, in 
NameError: name 'NoneType' is not defined


I know I ask whether:

>>> thing is None

but I wanted a generic test.
I'm trying to get away from things like:

>>> type(thing) is type(None)

because of something I read somewhere preferring my original test method.


Thanks

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


RE: PEP 526 - var annotations and the spirit of python

2018-07-05 Thread Schachner, Joseph
It is interesting to contemplate how this could transform Python into nearly a 
statically typed language:
x = 3
x = f(x)

If you say the type checker should infer that x is an int, and then therefore 
complain about x=f(x) if f() does not return an int, then we have what in new 
C++ is auto type declaration by default, and after that it's statically typed.

So this would still work
valStr = QueryMeasuringInstrument("app.Meas.P1.Result.Mean")
val = float(valStr)

but this would not:
val = QueryMeasuringInstrument("app.Meas.P1.Result.Mean")
val = float(val)
even though it works today in both Python 2 and Python 3.   I don't think the 
intent of var annotations is to automatically extract the type for variables 
that are not annotated, and then insist that they retain the same type at all 
times.   It would break this example.

I think if I do annotate a variable, THEN the type checker can insist that I do 
not change its type.  So this could cause an error:

string val = QueryMeasuringInstrument("app.Meas.P1.Result.Mean")
val = float(val)

--- Joe S. 

-Original Message-
From: Steven D'Aprano  
Sent: Wednesday, July 4, 2018 11:31 AM
To: python-list@python.org
Subject: Re: PEP 526 - var annotations and the spirit of python

On Wed, 04 Jul 2018 13:48:26 +0100, Bart wrote:

> Presumably one type hint applies for the whole scope of the variable, 
> not just the one assignment.

You know how in C you can write 

int x = 1;  # the type applies for just this one assignment
x = 2.5;# perfectly legal, right?


Wait, no, of course you can't do that. Why would you suggest that as even a 
possibility?

Of course the type (whether inferred or annotated) applies for the entire scope 
of that variable.


> Which means that here:
> 
> x: int = 3
> x = f(x)
> 
> you know x should still an int after these two statements, because the
> type hint says so. Without it:
> 
> x = 3
> x = f(x)
> 
> x could be anything.

That's not how type checking works. It makes *no difference* whether the 
type is inferred or hinted. Type hints only exist to cover the cases the 
type inference engine can't determine, or determine too strictly. See 
below.

In the Dark Ages of type-checking, the compiler was too dumb to work out 
for itself what the type of variables is, so you have to explicitly 
declare them all, even the most obvious ones. Given such a declaration:

int x = 3;  # using C syntax

the type checker is smart enough to look at the next line:

x = f(x);

and complain with a type-error if f() returns (say) a string, or a list. 
Checking that the types are compatible is the whole point of type 
checking.

Now fast forward to the Enlightenment of type-inference, first used in a 
programming language in 1973 (so older than half the programmers alive 
today). That purpose doesn't go away because we're using type inference.

With type-inference, the type-checker is smart enough to recognise what 
type a variable is supposed to be (at least sometimes):

x = 3;  # of course it's an int, what else could it be?
x = f(x);

and likewise complain if f(x) returns something other than an int. 
There's no point in type checking if you don't, you know, actually 
*check* the types.

With type inference, the only reason to declare a variable's type is if 
the type checker can't infer it from the code, or if it infers the wrong 
type. (More on this later.)

To do otherwise is as pointless and annoying as those comments which 
merely repeat what the code does:

import math   # import the math module
mylist.append(v)  # append v to mylist
counter += 1  # add 1 to counter
s = s.upper() # convert s to uppercase
x: int = 3# assign the int 3 to x

Don't be That Guy who writes comments stating the bleeding obvious.

There's not always enough information for the type checker to infer the 
right type. Sometimes the information simply isn't there:

x = []  # a list of what?

and sometimes you actually did intend what looks like a type-error to the 
checker:

x = 3   # okay, x is intended to be an int
x = "spam"  # wait, this can't be right


In the later case, you can annotate the variable with the most general 
"any type at all" type:

from typing import Any
x: Any = 3  # x can be anything, but happens to be an int now
x = "spam"  # oh that's fine then


or you can simply not check that module. (Type checking is optional, not 
mandatory.)



>> A better example would be:
>> 
>>  x: int = None
>> 
>> which ought to be read as "x is an int, or None, and it's currently
>> None".
> 
> In that case the type hint is lying.

"Practicality beats purity."

"This type, or None" is such a common pattern that any half-way decent 
type checker ought to be able to recognise it. You can, of course, 
explicitly annotate it:

x: Optional[int] = None

but the type checker should infer that if you assign None to a variable 
which is declared int, 

Re: range

2018-06-25 Thread Schachner, Joseph
Re: "I know I'm going to get flak for bringing this up this old issue, but 
remember when you used to write a for-loop and it involved creating an actual 
list of N integers from 0 to N-1 in order to iterate through them? Crazy.

But that has long been fixed - or so I thought. When I wrote, today:



for i in range(1): pass  # 100 million



on Python 2, it used up 1.8GB, up to the limit of my RAM, and it took several 
minutes to regain control of my machine (and it never did finish). You don't 
expect that in 2018 when executing a simple empty loop.

On Py 2 you have to use xrange for large ranges - that was the fix.

Somebody however must have had to gently and tactfully point out the issue. I'm 
 afraid I'm not very tactful."



It HAS been fixed in Python 3, since the beginning of that branch.  In Python 3 
range is what xrange was in Python 2.  I used past tense there on purpose.



Python 2 actual demise is scheduled.  See: https://python3statement.org/

It's a list of project that have pledged to drop support for Python2.7 no later 
than January 1, 2020. You will recognize many of them: Pandas, IPython, NumPy, 
Matplotlib, Jupyter... etc



Anyone talking about the future of Python and features that might be added to 
Python really has to be talking about Python 3, because Python 2 support is 
already ramping down and will completely end on January 1, 2020.  The original 
plan was to end it in 2015, but the extra five years were added to give 
everyone plenty of time to switch.



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


RE: ironpython not support py3.6

2018-06-22 Thread Schachner, Joseph
Wait.

-Original Message-
From: fantasywan...@gmail.com  
Sent: Friday, June 22, 2018 2:45 AM
To: python-list@python.org
Subject: ironpython not support py3.6

We have a project implemented with c# and python, iron python is  a good choice 
for us to integrate these two tech together but iron python not support python 
3.6 yet, any suggest for this?

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


RE: syntax difference

2018-06-18 Thread Schachner, Joseph
On YouTube you can watch videos of Guido van Rossum presenting at PyCon from a 
few years ago, in which he makes clear that he has been thinking about this 
since 2000, that he wants someone else to guide this PEP along its path because 
he is too close to it, and that NOTHING about having a typing module requires 
you to use it.  In fact, you can use it without affecting your source code and 
interleaving the (helpful) information into the source code.  They support 
"stub" files, with a ".pyi" extension, in which you can place the declarations 
with the typing information.   The type checker will read that an use it along 
with your unmodified source code to do its checking.  He also thanked multiple 
people for their contributions bringing this from an idea to a preliminary 
implementation in 3.5 and now possibly final form in 3.6.6rc1.  

Now that you know that 1) You are not required to modify your source code at 
all, even if you want to get full utility from typing, and 2) you really don't 
have use typing at all, nothing forces you to,  and 3) it's been developed by 
the Python community for years and was proposed by Guido years before he went 
to DropBox,  does that help?

-- Joe S.

-Original Message-
From: Rick Johnson  
Sent: Monday, June 18, 2018 1:16 PM
To: python-list@python.org
Subject: Re: syntax difference

Steven D'Aprano wrote:
> Moving the type-checking out of the core language into the IDE or 
> linter which can be used or not used according to the desire of the 
> programmer

Except, what your poppycock commentary seems to glaze over is the fact that 
whilst a programmer can certainly decided to "use or not use" the type-hints 
feature in his or her own code, he or she certainly cannot "see or _unsee_" 
type-hints that are written by other programmers.


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


RE: syntax difference (type hints)

2018-06-18 Thread Schachner, Joseph
Assuming that we want Python to remain a dynamically typed (but strongly typed) 
language, I believe the proposed type hints are only necessary for function 
definitions, where the caller really needs to know the types of arguments to 
pass in.   At the moment that purpose is (I think adequately) served by def 
strings, triple quoted strings immediately following the function declaration.  
When I do code reviews for Python developed here, if the argument names of a 
function do not hint at the type they should be and there is no def string then 
I insist that something be added.  Often what gets added is a def string that 
says something about what the function does and explains what argument types 
are expected.

-- Joseph S.

-Original Message-
From: Ed Kellett  
Sent: Monday, June 18, 2018 8:47 AM
To: python-list@python.org
Subject: Re: syntax difference

On 2018-06-18 13:18, Chris Angelico wrote:
> 1) Parse the code, keeping all the non-essential parts as well as the 
> essential parts.
> 2) Find the comments, or find the annotations
> 3) If comments, figure out if they're the ones you want to remove.
> 4) Reconstruct the file without the bits you want to remember.
> 
> Step 3 is removed if you're using syntactic annotations. Otherwise, 
> they're identical.

It's likely that Python comments are much easier to remove than arbitrary bits 
of Python syntax--you need to know the answer to "am I in a string literal?", 
which is a lexical analysis problem you could hack together a solution for over 
the course of about one coffee, as opposed to "where exactly am I in the Python 
parse tree?", which is... harder.
The information you need to keep track of and later reconstruct is 
substantially simpler, too.

I don't think "they're hard to mechanically remove" is a particularly good 
argument against type hints, but considered on its own it probably is true.

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


RE: syntax difference

2018-06-18 Thread Schachner, Joseph
As soon as I sent the previous message I realized it's "doc string" not def 
string.  Pardon me. 
--- Joe S.

-Original Message-
From: Ed Kellett  
Sent: Monday, June 18, 2018 8:47 AM
To: python-list@python.org
Subject: Re: syntax difference

On 2018-06-18 13:18, Chris Angelico wrote:
> 1) Parse the code, keeping all the non-essential parts as well as the 
> essential parts.
> 2) Find the comments, or find the annotations
> 3) If comments, figure out if they're the ones you want to remove.
> 4) Reconstruct the file without the bits you want to remember.
> 
> Step 3 is removed if you're using syntactic annotations. Otherwise, 
> they're identical.

It's likely that Python comments are much easier to remove than arbitrary bits 
of Python syntax--you need to know the answer to "am I in a string literal?", 
which is a lexical analysis problem you could hack together a solution for over 
the course of about one coffee, as opposed to "where exactly am I in the Python 
parse tree?", which is... harder.
The information you need to keep track of and later reconstruct is 
substantially simpler, too.

I don't think "they're hard to mechanically remove" is a particularly good 
argument against type hints, but considered on its own it probably is true.

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


RE: mutable sequences

2018-06-14 Thread Schachner, Joseph
No, it says lists are mutable and tuples are immutable.  

Mutable has the same root as "mutation".  Mutable means "can be changed in 
place".   Immutable means "cannot be changed in place".

Examples: 
1) pass your list to a function, the function modifies the list. When the 
function returns your script gets control back. Your list is modified.
2) pass a tuple to a function.  The function wants to modify the tuple.  It 
can't Append( ) to it, if it tries Python will throw an exception because 
tuples don't have an append method.  It can't assign a new value to an element 
of the tuple.  But it can assign different content to the tuple entirely.  When 
the function returns your script gets control back. YOUR tuple is NOT modified. 
 When the function assigned to it, a new tuple with a different ID was created. 
 Basically, from that point on, the function had its own tuple.  The original 
was not modified because it can't be modified. It's immutable.
3) You use a list constructor, i.e., function( list(mylist) ).   That passes a 
copy of your list, which has a different ID, to the function.  The function can 
append to it, or otherwise modify it.  When the function returns, YOUR list is 
not modified because you didn't pass your list to the function; you passed a 
newly constructed copy of your list to the function.

(Advanced comment:  If a tuple has an element which is a list, that list is 
mutable.  Thinking about whether the list inside the tuple should be modifiable 
gives me a headache.  Try it and see what happens.)

If you don't like the terms mutable and immutable, think of them as related to  
"pass by reference" and "pass by value" in some other languages.  If you pass 
by reference, you give the function a reference to your object; it modifies 
your object.  If you pass by value, you load a copy of your object probably 
onto the stack, to pass to the function; the function can modify the copy but 
your object is not modified (this seems most similar to example 3 above). To 
avoid having to copy huge things onto the stack, C++ grew a const keyword so 
that you can pass a const reference to a function, which means the function 
won't be allowed to modify it.  I think this is very much like immutable.

I think it's fair to say Python always passes by reference.  Immutable types 
allow Python to have behavior that acts sort of like pass by value, or very 
much like passing a const reference in C++.  (One difference is Python allows a 
line that looks like it's assigning to the tuple, but really it makes a new 
tuple.)  In example 3 above Python didn't actually pass a copy of your list 
(which could be huge), it passed a reference to a copy of your list.  

--- Joseph Schachner

-Original Message-
From: Sharan Basappa  
Sent: Wednesday, June 13, 2018 10:57 PM
To: python-list@python.org
Subject: mutable sequences

The term mutable appears quite often in Python.
Can anyone explain what is meant by mutable and immutable sequences.

For example, Python lists are mutable.

BTW, is the below explanation correct (it is taken from a book I am reading)

Python lists are mutable sequences. They are very similar to tuples, but they 
don't have the restrictions due to immutability.

It says lists are mutable and then says they are immutable???


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


RE: logging with multiprocessing

2018-06-08 Thread Schachner, Joseph
Multiprocessing, not multithreading.  Different processes.   This is pretty 
easy to do.

I have done this from a Python script to run an analysis program on many sets 
of data, at once.  To do it: 1) if there is going to be an output file, each 
output file must have a distinct name.   2) To use logging, log to file, and 
each log file will have to have  a distinct name.   This is not hard to do.  I 
assume input data is different for each run, so we don't have to do anything 
about that.  Then there won't be any conflict.  Input files are distinct output 
files are distinct, and log files are distinct.  

When I did this, we had the pleasure of running on a 20 core dual Xeon based 
system,  I don't remember if ran 20 processes at a time or slightly less.  
Anyway, we really did achieve nearly linear speed up. Windows did assign these 
processes to separate cores.

--- Joe S. 

-Original Message-
From: jenil.desa...@gmail.com  
Sent: Thursday, June 7, 2018 2:46 PM
To: python-list@python.org
Subject: logging with multiprocessing

Hello,

I am new to logging module. I want to use logging module with multiprocessing. 
can anyone help me understand how can I do it?. Any help would be appreciated.

Thank you.


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


RE: "Data blocks" syntax specification draft

2018-05-23 Thread Schachner, Joseph
I understand that the /// data representation is meant to emphasize data 
structure (and de-emphasize existing Python syntax for that purpose).  It's 
already been discussed that Python can export to pickle format, JSON, csv, XML 
and possibly others I can't think of right now.  So having a data 
representation format is not a foreign concept.

All I want to say is that I don't really feel that there is a need for another 
data representation.  Also, even if we leave out parentheses, "/// a,b,c" is 9 
characters, whereas "(a,b,c)" is 7 characters. And "a,b,c" is only 5 
characters.  I think I would actually prefer the usual Python syntax, because 
to me it is clear (I already know Python) and typing fewer characters to 
achieve the same result appeals to me.

Perhaps I just don't value the benefit of this data representation technique, 
or perhaps there really is a benefit that I didn't get. If so forgive me.  But 
I do think that a good exposition of the benefit obtained by using this data 
representation will need to be made, or you may find that there are many other 
people like me.

--- Joseph S.



-Original Message-
From: Chris Angelico  
Sent: Wednesday, May 23, 2018 9:56 AM
To: Python 
Subject: Re: "Data blocks" syntax specification draft

On Wed, May 23, 2018 at 11:11 PM, Steven D'Aprano 
 wrote:
> On Wed, 23 May 2018 11:10:33 +0100, bartc wrote:
>> 0 items within the list:
>>
>> ()Empty tuple
>> []Empty list
>> {}Empty dict
>
> Aye ... as we've acknowledged numerous times now, the empty tuple *is* 
> a genuine special case, one which *does* rely on an empty pair of 
> round brackets.

We actually have THREE special cases and only two types that follow the general 
case. Here's the general case:

List of three: [1, 2, 3] or [1, 2, 3,]
List of two: [1, 2] or [1, 2,]
List of one: [1] or [1,]
List of zero: []

Dict of three: {1:1, 2:2, 3:3} or {1:1, 2:2, 3:3,} Dict of two: {1:1, 2:2} or 
{1:1, 2:2,} Dict of one: {1:1} or {1:1,} Dict of zero: {}

Perfect! Now let's try that with other types.

Tuple of three: 1, 2, 3 or 1, 2, 3,
Tuple of two: 1, 2 or 1, 2,
Tuple of one: 1, # no other way to do it Tuple of zero: ()

Set of three: {1, 2, 3} or {1, 2, 3,}
Set of two: {1, 2} or {1, 2,}
Set of one: {1} or {1,}
Set of zero: set()

The empty set and empty tuple are special, as is the single-element tuple (you 
can't omit the comma). So, yes, there are definitely special cases in the 
grammar, and they come about because practicality beats purity. If we wanted 
perfectly clean grammar with no special cases, we'd probably have to use 
two-character bracketings, to ensure that everything is uniquely spellable, and 
there'd be no omitting them from tuples - so it really WOULD be the bracketing 
characters that define a tuple. But what would we gain? Very little. A few less 
special cases, maybe, in return for needing to write more verbose syntax for 
every literal/display type.

ChrisA

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