Re: from __future__ import annotations bug?

2023-06-30 Thread Joseph Garvin via Python-list
Should mention this also affects Protocol[Buzz]

On Fri, Jun 30, 2023, 5:35 PM Joseph Garvin  wrote:

> ```
> from __future__ import annotations
> from typing import Generic, TypeVar
>
> T = TypeVar("T")
> class Foo(Generic[T]): ...
> class Bar(Foo[Buzz]): ... # NameError here
> class Buzz: ...
> ```
>
> This will error, despite the __future__ import, because cpython is trying
> to look up Buzz before it's defined, even though we have supposedly
> prevented annotations from being processed. I realize that Class[Args] is
> allowed in that area in general and isn't always type annotation related,
> but does this mean that even with PEP 649 that forward references will
> still be needed?
>
-- 
https://mail.python.org/mailman/listinfo/python-list


from __future__ import annotations bug?

2023-06-30 Thread Joseph Garvin via Python-list
```
from __future__ import annotations
from typing import Generic, TypeVar

T = TypeVar("T")
class Foo(Generic[T]): ...
class Bar(Foo[Buzz]): ... # NameError here
class Buzz: ...
```

This will error, despite the __future__ import, because cpython is trying
to look up Buzz before it's defined, even though we have supposedly
prevented annotations from being processed. I realize that Class[Args] is
allowed in that area in general and isn't always type annotation related,
but does this mean that even with PEP 649 that forward references will
still be needed?
-- 
https://mail.python.org/mailman/listinfo/python-list


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: Problem when scraping the 100 Movie titles.

2022-09-22 Thread Fabian Joseph
#Try using, it's save in json format of the website: 
import json
import requests
from bs4 import BeautifulSoup


url = "https://www.empireonline.com/movies/features/best-movies-2/;

soup = BeautifulSoup(requests.get(url).content, "html.parser")
data = json.loads(soup.select_one("#__NEXT_DATA__").contents[0])

# uncomment this to print all data:
#print(json.dumps(data, indent=4))


def find_articles(data):
if isinstance(data, dict):
for k, v in data.items():
if k.startswith("ImageMeta:"):
yield v['image']['name']
else:
yield from find_articles(v)
elif isinstance(data, list):
for i in data:
yield from find_articles(i)


for a in find_articles(data):
print(a)
-- 
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


[Python-announce] Brand new: Line Profiler GUI v0.1

2022-02-08 Thread Joseph Martinot-Lagarde
Hi all,
In the dark moments of code optimization, line_profiler from Robert Kern (now 
https://github.com/pyutils/line_profiler) helped me a lot. To ease the usage of 
this tool I created a GUI, namely "Line Profiler GUI".
The installation is just a pip command away (choose your favorite python Qt 
binding):

$ pip install line-profiler-gui[PySide2]
$ pip install line-profiler-gui[PyQt5]

The code is available on Github: https://github.com/Nodd/lineprofilergui

Happy optimization!
Joseph
___
Python-announce-list mailing list -- python-announce-list@python.org
To unsubscribe send an email to python-announce-list-le...@python.org
https://mail.python.org/mailman3/lists/python-announce-list.python.org/
Member address: arch...@mail-archive.com


RE: Script profiling details

2022-01-11 Thread Joseph L. Casale
> You might try `py-spy`.

That worked well, I started trying to get more data from the profile
output with the stats module but didn't quite get there. 

Thank you everyone,
jlc
-- 
https://mail.python.org/mailman/listinfo/python-list


Script profiling details

2022-01-10 Thread Joseph L. Casale
I am trying to track down a slow script startup time. I have executed the
script using `python -m cProfile -o profile /path/script.py` and read through
the results, but the largest culprit only shows various built-ins.

I expected this given the implementation, but I was hoping to get some
finer details so I can track down the specific module or at least the specific
file so I have a place to start reviewing code for optimizations.

Is there something I can use to analyze the existing profile output or to 
generate
it with more feedback?

Thanks,
jlc
-- 
https://mail.python.org/mailman/listinfo/python-list


[issue45665] Problems caused by isinstance(list[int], type) returning True

2021-12-27 Thread Joseph Perez


Joseph Perez  added the comment:

There is also https://bugs.python.org/issue44293 about inspect.isclass

--
nosy: +joperez

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



[issue31042] Inconsistency in documentation of operator.index

2021-11-30 Thread Joseph Fox-Rabinovitz


Joseph Fox-Rabinovitz  added the comment:

I closed the issue (it's already been rejected), primarily based on

> a.__index__ =  is an unauthorized use of a *reserved* word and the 
> effect of such usage is not and need not be documented.  

> The entry for __*__ does include "*Any* use of __*__ names, in any context, 
> that does not follow explicitly documented use, is subject to breakage 
> without warning."  To me, that says that the effect of the reserved-word 
> assignment is undefined.  It could be made to raise an exception.

It's like filing a bug report for UB in C.

--
stage: needs patch -> resolved
status: pending -> closed

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



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


[issue44174] Unclear meaning of _Private__names in enum docs.

2021-10-20 Thread Joseph Riddle


Joseph Riddle  added the comment:

_Private__names seems to no longer exist in the Python 3.11 documentation.

https://docs.python.org/3.11/library/enum.html#private-names

It appears to have been removed in this PR 
https://github.com/python/cpython/pull/23748/files

Should this issue be updated to remove Python 3.11 from the Versions?

--
nosy: +joeriddles

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



[issue45418] types.UnionType is not subscriptable

2021-10-10 Thread Joseph Perez


Joseph Perez  added the comment:

Indeed, sorry, my example was bad. My library was raising at several place, and 
I've extrapolated about generic substitution.

I've indeed other substitutions (without `TypeVar`), and because they were 
failing, I've assumed that all of my substitutions were failing; I was wrong 
about generic one.

For example, if I want to substitute `int | Collection[int]` to `int | 
list[int]`, I will have to replace `types.UnionType` by `typing.Union` or use 
`reduce`, while it was not necessary in 3.9 where I could just write 
`get_origin(tp)[new_args]`.

So I'll have to add some `if` in my code.

--
stage:  -> resolved
status: pending -> closed

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



[issue45418] types.UnionType is not subscriptable

2021-10-09 Thread Joseph Perez


New submission from Joseph Perez :

`types.UnionType` is not subscriptable, and this is an issue when type 
manipulations are done.

A common maniputation I've to do is to substitute all the `TypeVar` of a 
potential generic type by their specialization in the given context.
For example, given a class:
```python
@dataclass
class Foo(Generic[T]):
bar: list[T]
baz: T | None
```
in the case of `Foo[int]`, I want to compute the effective type of the fields, 
which will be `list[int]` and `int | None`.
It could be done pretty easily by a recursive function:
```python
def substitute(tp, type_vars: dict):
origin, args = get_origin(tp), get_args(tp)
if isinstance(tp, TypeVar):
return type_vars.get(tp, tp)
elif origin is Annotated:
return Annotated[(substitute(args[0], type_vars), *args[1:])]
else:
return origin[tuple(substitute(arg) for arg in args)]  # this line 
fails for types.UnionType
```

And this is not the only manipulation I've to do on generic types. In fact, all 
my library (apischema) is broken in Python 3.10 because of `types.UnionType`.
I've to substitute `types.UnionType` by `typing.Union` everywhere to make 
things work; `types.UnionType` is just not usable for dynamic manipulations.

I've read PEP 604 and it doesn't mention if `types.UnionType` should be 
subscriptable or not. Is there a reason for not making it subscriptable?

--
messages: 403554
nosy: joperez
priority: normal
severity: normal
status: open
title: types.UnionType is not subscriptable
versions: Python 3.10

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



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


code to initialize a sequence

2021-08-29 Thread joseph pareti
In the code attached below, the A-variant is from somebody else who knows
Python better than I. But I do not like to just use any code without having
a grasp, specifically the line in* bold*, so I wrote the B-variant which
gives the same results. The C-variant is identical to A and is there for
verification: after resetting the seed I expect the same sequence. The
D-variant is closer to the way I code, and it does not work.


import random
from random import randint, seed

def generate_sequence(length, n_unique):
*return [randint(0, n_unique-1) for k in range(length)]*

def generate_sequence_JP(length, n_unique):
   LI = []
   for k in range(length):
 LI.append(randint(0, n_unique-1))
   return(LI)
def generate_sequence_EXPLICIT(length, n_unique):
   X =[None] * length
  for i in range(length):
X[i] = [randint(0, n_unique-1)]
   return X
#
# MAIN PROGRAM
#
random.seed(2)
A = generate_sequence(4, 10 )
random.seed(2)
B = generate_sequence_JP(4, 10)
random.seed(2)
C = generate_sequence(4, 10 )
random.seed(2)
D = generate_sequence_EXPLICIT(4, 10 )
print(A)
print(type(A))
print('-')
print(B)
print(type(B))
print('-')
print(C)
print(type(C))
print('-')
print(D)
print(type(D))


Regards,
Joseph Pareti - Artificial Intelligence consultant
Joseph Pareti's AI Consulting Services
https://www.joepareti54-ai.com/
cell +49 1520 1600 209
cell +39 339 797 0644
-- 
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: question on trax

2021-08-18 Thread joseph pareti
yes, but I do not see Fn anywhere.

Another question is on this line:
z = add((x, y))
If I code:
z = add(x, y)
Then the following exception occurs :

*Expected input to be a tuple or list; instead got .*


Am Di., 17. Aug. 2021 um 19:21 Uhr schrieb MRAB :

> On 2021-08-17 16:50, joseph pareti wrote:
> > In the following code, where does tl.Fn come from? i see it nowhere in
> the
> > documents, i.e I was looking for trax.layers.Fn :
> >
> > import numpy as np
> > *from trax import layers as tl*
> > from trax import shapes
> > from trax import fastmath
> > #
> > def Addition():
> >  layer_name = "Addition"  # don't forget to give your custom layer a
> > name to identify
> >
> >  # Custom function for the custom layer
> >  def func(x, y):
> >  return x + y
> >
> >  return *tl.Fn*(layer_name, func)
> >
> [snip]
> It comes from using the line:
>
>  from trax import layers as tl
>
> so it's equivalent to 'trax.layers.Fn'.
> --
> https://mail.python.org/mailman/listinfo/python-list
>


-- 
Regards,
Joseph Pareti - Artificial Intelligence consultant
Joseph Pareti's AI Consulting Services
https://www.joepareti54-ai.com/
cell +49 1520 1600 209
cell +39 339 797 0644
-- 
https://mail.python.org/mailman/listinfo/python-list


question on trax

2021-08-17 Thread joseph pareti
In the following code, where does tl.Fn come from? i see it nowhere in the
documents, i.e I was looking for trax.layers.Fn :

import numpy as np
*from trax import layers as tl*
from trax import shapes
from trax import fastmath
#
def Addition():
layer_name = "Addition"  # don't forget to give your custom layer a
name to identify

# Custom function for the custom layer
def func(x, y):
return x + y

return *tl.Fn*(layer_name, func)


# Test it
add = Addition()
# Inspect properties
print("-- Properties --")
print("name :", add.name)
print("expected inputs :", add.n_in)
print("promised outputs :", add.n_out, "\n")

# Inputs
x = np.array([3])
y = np.array([4])
print("-- Inputs --")
print("x :", x, "\n")
print("y :", y, "\n")

# Outputs
z = add((x, y))
print("-- Outputs --")
print("z :", z)

-- 
Regards,
Joseph Pareti - Artificial Intelligence consultant
Joseph Pareti's AI Consulting Services
https://www.joepareti54-ai.com/
cell +49 1520 1600 209
cell +39 339 797 0644
-- 
https://mail.python.org/mailman/listinfo/python-list


[issue44866] Inconsistent Behavior of int()

2021-08-08 Thread John Joseph Morelli


New submission from John Joseph Morelli :

I first noticed this and reported it on the W3 Schools Tutorial, the section 
entitled "Add Two Numbers with User Input"

There were many behaviors that I did not understand, but for this bug report, I 
will state that the input statements present seem to return a string and under 
most situations will return an error if the user inputs a real number like 2.8. 
 However, under a very specific situation, it will truncate 2.8 to 2 without 
error.  

After further investigation, I believe the following session in the IDLE's 
output window  and editor illustrates this inconsistent behavior.  Note that I 
have added comments after copying the session here...

>>> print(x)  #want to ensure new session has x as undefined
Traceback (most recent call last):
  File "", line 1, in 
print(x)
NameError: name 'x' is not defined  # confirmed x is undefined
>>> x="2" # define x as the string "2"
>>> print(x)
2
>>> print(type(x)) # confirm that x is a string value of "2" 

>>> y=int(x) # convert string value of "2" to integer of 2  -
# according to documentation this should work - see "If x is not a 
# number or if base is given, then x must be a string, bytes, or
# bytearray instance representing an integer literal in radix base."
# at link --> https://docs.python.org/3.9/library/functions.html#int
>>> print(type(y)) # ensure y is type int

>>> print(y)
2
>>> z=x+".8" # create z to be the concatenation of two strings "2" and ".8" = 
>>> "2.8", a string representation of the real number 2.8
>>> print(z)
2.8
>>> print(type(z)) # ensure z is a string

>>> aa=int(z) # convert z to an integer (as descried in the link
# above, this should NOT work
Traceback (most recent call last):
  File "", line 1, in 
aa=int(z)
ValueError: invalid literal for int() with base 10: '2.8'
>>> w="2.8" # Define w directly as the string value of 2.8 = "2.8"
>>> bb=int(w) # This should also produce an error
Traceback (most recent call last):
  File "", line 1, in 
bb=int(w)
ValueError: invalid literal for int() with base 10: '2.8'
>>> a='2.8'
>>> b=int(a)
Traceback (most recent call last):
  File "", line 1, in 
b=int(a)
ValueError: invalid literal for int() with base 10: '2.8'
>>> print(type(a)) # Ensure a is a string

>>> w="2"
>>> bb=int(w)
>>> print(bb)
2

>>> print(type(bb))

>>> test=int(input("What is test value? ")) #lets try inputting a
# real number but as an argument to int and assigning it to test
What is test value? 2.8 # this should not work either
Traceback (most recent call last):
  File "", line 1, in 
test=int(input("What is test value? "))
ValueError: invalid literal for int() with base 10: '2.8'
>>> # So everything here is working as expected, but...

Here is code from the IDLE editor... a file called testinput1.py

x = int(1)
y = input("Type a number: ")
print(type(y))
int_y = int(2.8) #conver y to an integer 2 and assign to int_y
z = int("3")
print(x)
print(y)
print(int_y)
print(z)

# I can find no documentation to suggest this should work, but it does.  Here 
is the output in IDLE's shell

Type a number: 2.8

1
2.8
2
3

Now, if I immediately go into the shell while the variables remain untouched 
and defined...

>>> a=int(y) # Correctly, this produces the expected error
Traceback (most recent call last):
  File "", line 1, in 
a=int(y)
ValueError: invalid literal for int() with base 10: '2.8'

After extensive testing, I conclude that after input, you may immediately apply 
the int() function to the resulting string, but you quickly lose that ability, 
resulting in the expected error.  I can find no documentation to explain this 
behavior.  

If I am not overlooking something, I think this should either be in the 
documentation of the function int(), if it is intended to behaviour this way, 
or as a bug, should be corrected.

NOTE, I just started learning Pytyon this weekend, so I may be just ignorant of 
the behavior, but I have searched a good bit and found nothing suggesting this 
is how int() should behalf.  I have also not studied the other constructor 
functions.

--
assignee: docs@python
components: Build, Documentation, IDLE, Library (Lib), Windows
files: function_int_08Aug21.txt
messages: 399224
nosy: TheDoctor165, docs@python, paul.moore, steve.dower, terry.reedy, 
tim.golden, zach.ware
priority: normal
severity: normal
status: open
title: Inconsistent Behavior of int()
type: behavior
versions: Python 3.9
Added file: https://bugs.python.org/file50205/function_int_08Aug21.txt

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



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


Re: [Errno 2] No such file or directory:

2021-07-29 Thread joseph pareti
indeed. There are better options than the one I attempted. Thanks for the
advice

Am Mi., 28. Juli 2021 um 18:19 Uhr schrieb Chris Angelico :

> On Thu, Jul 29, 2021 at 2:10 AM joseph pareti 
> wrote:
> >
> > The following code fails as shown in the title:
> >
> >
> >
> >
> >
> >
> > *import subprocesscmd = 'ls -l
> >
> /media/joepareti54/Elements/x/finance-2020/AI/Listen_attend_spell/VCTK-Corpus/wav48
> > | awk "{print  $9 }"'process = subprocess.Popen([cmd],
> >  stdout=subprocess.PIPE, stderr=subprocess.PIPE)stdout, stderr =
> > process.communicate()print('stdout ',stdout)print('stderr ',stderr)*
> >
> > 
> >
> > Traceback (most recent call last):
> >   File "PreProcess_1a.py", line 3, in 
> > process = subprocess.Popen([cmd],  stdout=subprocess.PIPE,
> > stderr=subprocess.PIPE)
> >   File "/home/joepareti54/anaconda3/lib/python3.8/subprocess.py", line
> 854,
> > in __init__
> > self._execute_child(args, executable, preexec_fn, close_fds,
> >   File "/home/joepareti54/anaconda3/lib/python3.8/subprocess.py", line
> > 1702, in _execute_child
> > raise child_exception_type(errno_num, err_msg, err_filename)
> > FileNotFoundError: [Errno 2] No such file or directory: 'ls -l
> >
> /media/joepareti54/Elements/x/finance-2020/AI/Listen_attend_spell/VCTK-Corpus/wav48
> > | awk "{print  $9
> >
>
> First off, you'll want to post code in a way that keeps the
> formatting, otherwise it becomes very hard to read.
>
> But the immediate problem here is that Popen takes an array of command
> arguments, NOT a shell command line. You cannot invoke ls and pipe it
> into awk this way.
>
> Don't think like a shell script. Python has very good
> directory-listing functionality, and you will very very seldom need to
> shell out to pipelines. Figure out what you actually need to learn
> from the directory listing and get that information directly, rather
> than trying to use two external commands and text parsing. It's far
> FAR easier, cleaner, and safer that way.
>
> ChrisA
> --
> https://mail.python.org/mailman/listinfo/python-list
>


-- 
Regards,
Joseph Pareti - Artificial Intelligence consultant
Joseph Pareti's AI Consulting Services
https://www.joepareti54-ai.com/
cell +49 1520 1600 209
cell +39 339 797 0644
-- 
https://mail.python.org/mailman/listinfo/python-list


[Errno 2] No such file or directory:

2021-07-28 Thread joseph pareti
The following code fails as shown in the title:






*import subprocesscmd = 'ls -l
/media/joepareti54/Elements/x/finance-2020/AI/Listen_attend_spell/VCTK-Corpus/wav48
| awk "{print  $9 }"'process = subprocess.Popen([cmd],
 stdout=subprocess.PIPE, stderr=subprocess.PIPE)stdout, stderr =
process.communicate()print('stdout ',stdout)print('stderr ',stderr)*



Traceback (most recent call last):
  File "PreProcess_1a.py", line 3, in 
process = subprocess.Popen([cmd],  stdout=subprocess.PIPE,
stderr=subprocess.PIPE)
  File "/home/joepareti54/anaconda3/lib/python3.8/subprocess.py", line 854,
in __init__
self._execute_child(args, executable, preexec_fn, close_fds,
  File "/home/joepareti54/anaconda3/lib/python3.8/subprocess.py", line
1702, in _execute_child
raise child_exception_type(errno_num, err_msg, err_filename)
FileNotFoundError: [Errno 2] No such file or directory: 'ls -l
/media/joepareti54/Elements/x/finance-2020/AI/Listen_attend_spell/VCTK-Corpus/wav48
| awk "{print  $9

-- 
Regards,
Joseph Pareti - Artificial Intelligence consultant
Joseph Pareti's AI Consulting Services
https://www.joepareti54-ai.com/
cell +49 1520 1600 209
cell +39 339 797 0644
-- 
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


[issue44353] PEP 604 NewType

2021-06-08 Thread Joseph Perez


New submission from Joseph Perez :

`typing.NewType` doesn't support PEP 604.

```
>>> import typing
>>> A = typing.NewType("A", int)
>>> B = typing.NewType("B", str)
>>> A | B
Traceback (most recent call last):
  File "", line 1, in 
TypeError: unsupported operand type(s) for |: 'function' and 'function'
```

--
messages: 395359
nosy: joperez
priority: normal
severity: normal
status: open
title: PEP 604 NewType
versions: Python 3.10

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



Re: Posting code on stackoverflow

2021-06-06 Thread joseph pareti
you need to put the code between 2 lines defined as follows:
```
then it will be formatted for you

Am Sa., 5. Juni 2021 um 23:40 Uhr schrieb Rich Shepard <
rshep...@appl-ecosys.com>:

> I tried to post a question on stackoverflow.com which included a bunch of
> code (entered after clicking the box 'code'). I noticed that lines were
> wrapped but could not find how to expand the input box so they would not
> wrap.
>
> SO wouldn't let me post the question because of the wrapped code. As I've
> not asked a question ther for a long time, and it didn't involve long lines
> of code, I need to learn a) how to enter code if it's not just clicking on
> the 'code' box before pasting text and b) how to keep code lines from
> wrapping so a horizontal scroll bar is made available.
>
> TIA,
>
> Rich
> --
> https://mail.python.org/mailman/listinfo/python-list
>


-- 
Regards,
Joseph Pareti - Artificial Intelligence consultant
Joseph Pareti's AI Consulting Services
https://www.joepareti54-ai.com/
cell +49 1520 1600 209
cell +39 339 797 0644
-- 
https://mail.python.org/mailman/listinfo/python-list


[issue44293] PEP 585 breaks inspect.isclass

2021-06-03 Thread Joseph Perez


Joseph Perez  added the comment:

@Jelle Zijlstra Thank you for the explanation.

> The current implementation of GenericAlias has been around for a few releases 
> by now, though, so that change might break some use cases.

I agree that a "fix" could have unexpected side-effect, my issue comes quite 
late indeed. By the way, Python typing is so much unstable (every version 
breaks the previous one), it's very complicated to write code that support 
multiple versions, so whatever the typing internal implementation, we must 
adapt.

> This is not true; it is the same for e.g. `set[int]`. Unless you meant 
> something else here.

I have chosen `list[int]` as an example of `types.GenericAlias` introduced by 
PEP 585 (i could have chosen `set[int]` or `collections.abc.Collection[int]`). 
But other generic aliases, e.g. `typing.List[int]` or `MyClass[int]` (where 
`MyClass` inherits `Generic[T]`), are not instances of `type`.

> @Joseph Perez, is there a specific library or pattern that is broken by this?

Because `issubclass` requires a "class" as arg 1, I use the pattern `if 
isinstance(tp, type) and issubclass(tp, SomeClass)` (`isinstance` check being 
equivalent to `inspect.isclass`). With PEP 585, it breaks for `list[int]` and 
other builtin generic aliases.

> FWIW I did think rather carefully about which attributes to delegate or not, 
> and delegating __class__ was intentional.

I don't have the context of the decision, so I can quite understand that 
delegating `__class__` was the right thing to do, especially when `__mro__` and 
other `type` attributes are also delegated. 
I mainly wanted to highlight this side effect, especially on the pattern 
mentioned above. (My issue title is a little bit excessive in this regard)

But as I've written, I've already so many wrappers to maintain compatibility 
between Python versions of typing that I can write a new one to handle this 
particularity of PEP 585. So this issue is not critical to me.

--

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



[issue44293] PEP 585 breaks inspect.isclass

2021-06-02 Thread Joseph Perez


New submission from Joseph Perez :

PEP 585 has the side-effect of making `list[int]` an instance of `type`. This 
is not the case for other generic aliases.

It also implies that `inspect.isclass(list[int]) is True`, while `list[int]` is 
not a class; as a proof of this statement `issubclass(list[int], 
collections.abc.Collection)` raises `TypeError: issubclass() arg 1 must be a 
class`.

By the way, there is the awkward thing of having `isinstance(list[int], type) 
is True` while `issubclass(type(list[int]), type) is False`.

--
messages: 394950
nosy: joperez
priority: normal
severity: normal
status: open
title: PEP 585 breaks inspect.isclass
versions: Python 3.9

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



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


[issue44183] Can't install certificates if GUI tools are not installed on macOS

2021-05-19 Thread Joseph Trask Still


New submission from Joseph Trask Still :

This issue occurs on my M1 MacBook Pro running macOS 11.3.1.
Steps to reproduce:
1. Open the Python installation package
2. When asked where to install the package, click "Customize" at the bottom of 
the dialog
3. Uncheck the GUI Tools option
4. Proceed through the installation as normal
5. At the conclusion of the installation, when offered to install certificates, 
click either the Finder link, or the link to the ReadMe.  The system will play 
the error sound, and nothing will open.

The issue appears to occur due to the fact the Python 3.9 folder is not created 
in Applications if the GUI Tools are not installed.

--
components: Installation
messages: 393998
nosy: thetechconspiracy
priority: normal
severity: normal
status: open
title: Can't install certificates if GUI tools are not installed on macOS
type: behavior
versions: Python 3.9

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



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


[issue43818] Email does not apply policy to multipart messages with defects

2021-04-12 Thread Joseph Ishac


New submission from Joseph Ishac :

I have noticed an issue (Python 3.8.5) where an email can be read in as bytes, 
but will not be returned as such with the as_bytes() call if the message is 
multipart, has a boundary which is not properly quoted, and the message has 
non-ascii text. It seems to be a result of how multipart messages are treated 
if the NoBoundaryInMultipartDefect is encountered [See Test #1].

I would argue that attempting to output the test message in the sample script 
with an 8bit, utf-8 enabled policy should return the original bytes as the 8bit 
policy should be applied to the "body" portion (any part after the null lines) 
of the email (as would be the case if it were not multipart) [See Test #4]

Currently it appears that the entire message is treated as headers, applying 
the strict 7bit, ascii requirement to the entire contents of the message. 
Furthermore, the msg.preamble is None.

I am also uncertain that attempting to leverage the handle_defect hooks would 
be helpful as correcting the boundary doesn't seem to work unless you re-parse 
the message [See Tests #2 and #3]

So the requested change would be to apply the encoding output policy to all 
portions of a message after the null line ending the headers.

--
components: email
files: email.multipart.test.py
messages: 390897
nosy: barry, jishac, r.david.murray
priority: normal
severity: normal
status: open
title: Email does not apply policy to multipart messages with defects
versions: Python 3.8
Added file: https://bugs.python.org/file49955/email.multipart.test.py

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



HELP Please, Python Program Help

2021-04-10 Thread Joseph Roffey
Hi, Im looking for some help with my program, I have been set a task to make a 
Strain Calculator. I need it to input two numbers, choosing either Metres or 
Inches for the 'Change in Length' divided by the 'Original Length' which can 
also be in Metres or Inches, the out put number also needs to give an option 
for the answer to be in metres or inches.

this is what i have come up with so far...


txt = "Strain Calculator"
x = txt.title()
print(x)

# This function divides two numbers
def divide(x, y):
return x / y

print("Select operation.")
print("1.Strain")

while True:
# Take input from the user
choice = input("Enter choice(1): ")

# Check if choice is one of the five options
if choice in ('1'):
num1 = float(input("Change in Length: "))
num2 = float(input("Original Length: "))

if choice == '1':
 print(num1, "/", num2, "=", divide(num1, num2)) 
break
else:
print("Invalid Input")


-- 
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 <https://compileralchemy.github.io/> | blog 
<https://www.pythonkitchen.com> github <https://github.com/Abdur-RahmaanJ>
Mauritius

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


RE: How to implement logging for an imported module?

2021-03-07 Thread Joseph L. Casale
> I couldn't find any information on how to implement logging in a library that
> doesn't know the name of the application that uses it. How is that done?

Hello,
That's not how it works, it is the opposite. You need to know the name of its 
logger,
and since you imported it, you do.

Logging is hierarchical, organized by dot separated names. However, all loggers
share the same root (top level) logger (a logger without any name, or in other 
words,
no hierarchical specificity). Loggers are singletons, all loggers share the 
same root
and each time you get a logger, if any code has previously asked for that 
logger by
name and therefore created it, you'll get that instance.

When you create a logger, it starts at level WARNING, which means only warnings
or higher are considered.

When you create a handler, it starts at level NOTSET, which means only level 0
and above are considered. Since NOTSET is 0, everything is considered by 
default.

Loggers pass messages that they are considering to all their handlers, which 
then
each filter again by the handlers own distinct level.

Don't add handlers in library code (except a null handler).

Do set a level on your library logger that you deem appropriate (INFO is likely
not appropriate).

Then, in your consuming code, if you instantiate a named logger, you won't see
messages that fall below the threshold of the library, and root defaults.

Create (get) a root logger (you don't have to use it) and set the level, and 
attach a
handler to it. Then get the logger your library uses and set the level to what 
you want.

Proceed with creating your own named logger and using that in your code, however
when the library emits a log message, it will traverse up, unfiltered and be 
passed to
a handler.

Think of the process like a tree data structure,  with the single root at the 
top, and
each immediate child being a named logger without additional specificity (no 
dot),
and each child of those taking the named plus one dot, followed by another name.

That helps when understanding the design behavior of propagation, and rather 
than
restate what is already well done, see 
https://docs.python.org/3/library/logging.html#logging.Logger.propagate. 

It does make a lot of sense, and it facilitates a concise and powerful ability 
to configure
an application where some messages can be ignored, written to different files, 
combined
into one, or some even emailed.

Last word of advice, don't fight it by hacking up or patching (somehow?), it 
will
simply not work right for any other case even slightly different than the one 
you
somehow beat into submission.

I hope that helps,
Joseph Casale

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


[issue43278] unnecessary leading '\n' from Py_GetCompiler() when build with different complier

2021-02-25 Thread Joseph Shen


Change by Joseph Shen :


--
nosy: +benjamin.peterson

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



[issue43278] unnecessary leading '\n' from Py_GetCompiler() when build with different complier

2021-02-21 Thread Joseph Shen


Joseph Shen  added the comment:

Right now there is no need to keep this limits, and the __version__ info from 
GCC is quite simple. Pls the attached snapshot image. 
Therefor I don't think we should keep a commit from 2000.

--

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



[issue43278] unnecessary leading '\n' from Py_GetCompiler() when build with different complier

2021-02-20 Thread Joseph Shen


Change by Joseph Shen :


--
title: Inconsistent behavior of Py_GetCompiler() -> unnecessary leading '\n'  
from Py_GetCompiler() when build with different complier

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



[issue43278] Inconsistent behavior of Py_GetCompiler()

2021-02-20 Thread Joseph Shen


Change by Joseph Shen :


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

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



[issue43278] Inconsistent behavior of Py_GetCompiler()

2021-02-20 Thread Joseph Shen


New submission from Joseph Shen :

The function Py_GetCompiler() return the version info with a leading '\n' when 
build with GCC/clang, while without this on other compilers. This inconsistent 
make the REPL print the 'welcome message' quit different, which I think is not 
we expect.
>From the snapshot images, we can see, when compiler with MSVC, the 'welcome 
>message' has two lines, but with GCC it is 3 lines, which two lines is what 
>expected.
Patch is given in the github rp, thanks for review.

--
components: C API
files: explorer_lN3ARB7gnj.png
messages: 387417
nosy: josephsmeng
priority: normal
pull_requests: 23377
severity: normal
status: open
title: Inconsistent behavior of Py_GetCompiler()
type: behavior
Added file: https://bugs.python.org/file49824/explorer_lN3ARB7gnj.png

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



Overriding property types on instances from a library

2021-02-20 Thread Joseph L. Casale
I have some code that makes use of the typing module.
This code creates several instances of objects it creates
from a library that has some issues.

For example, I have multiple list comps that iterate properties
of those instance and the type checker fails with:

Expected type 'collections.Iterable', got '() -> Any' instead

How can I override the type with a hint on a property of
those instances?

Thanks,
jlc
-- 
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: How do you debug in Python? Coming from a Matlab and R user. I'm already aware of pdb.

2021-01-26 Thread joseph pareti
To debug python code I use spyder from the anaconda distribution

Am Mittwoch, 27. Januar 2021 schrieb C W :

> Hi Michael,
> Here's the code again, class should be called PERSONDatabase, misspelled
> earlier:
> class PERSONDatabase:
>def __init__(self, id, created_at, name, attend_date, distance):
>   self._id = id
>   self.created_at = created_at
>   self.name= name
>   self.attend_date = attend_date
>   self.distance = distance
>
>@classmethod
>def get_person(self, employee):
>   return PERSONDatabase(employee['created_at'],
> employee['id'],
> employee['name'],
> employee['attend_date'],
> employee['distance'])
>
> The PERSONDatabase class is called from main. This is the trace back I got
> from the VS code:
>
> Traceback (most recent call last):
>File "/Users/Mike/Documents/Mike/main.py", line 95, in 
>   main()
>File "/Users/Mike/Documents/Mike/main.py", line 86, in main
>   args = get_feed()
>File "/Users/Mike/DocumentsMike/main.py", line 32, in get_feed
>   result = [PERSONatabase.get_person(raw_person) for raw_neo in
> raw_objects]
>File "/Users/Mike/Documents/Mike/main.py", line 32, in 
>   result = [NEODatabase.get_person(raw_person) for raw_neo in
> raw_objects]
>File "/Users/Mike/Documents/Mike/database.py", line 24, in get_person
>   return PERSONDatabase(person['created_at'],
> KeyError: 'created_at'
>
> Thank you very much!
>
> On Wed, Jan 27, 2021 at 12:10 AM Michael Torrie  wrote:
>
> > On 1/26/21 8:37 PM, C W wrote:
> > > I have a naive question. How do I use traceback or trace the stack? In
> > > particular, I'm using VS Code with Python interactive console.
> >
> > Show us the traceback here and we can help you interpret it.  Copy and
> > paste it from the VS Code console.
> >
> > > Say, I want to print the value of employee['name']. Can I do it?
> >
> > Yes I would think so.
> >
> > > My understanding is that these classes are just "skeletons". I must
> > > create an instance, assign values, then test?
> >
> > Can't you just do something like this?
> >
> > class NEODatabase:
> > def __init__(self, id, created_at, name, attend_date, distance):
> > self._id = id
> > self.created_at = created_at
> > self.name = name
> > self.attend_date = attend_date
> > self.distance = distance
> >
> > @classmethod
> > def get_person(self, employee):
> > print (employee['name'])
> >
> > return PERSONDatabase(employee['created_at'],
> >   employee['id'],
> >   employee['name'],
> >   employee['attend_date'],
> >   employee['distance'])
> >
> > --
> > https://mail.python.org/mailman/listinfo/python-list
> >
> --
> https://mail.python.org/mailman/listinfo/python-list
>


-- 
Regards,
Joseph Pareti - Artificial Intelligence consultant
Joseph Pareti's AI Consulting Services
https://www.joepareti54-ai.com/
cell +49 1520 1600 209
cell +39 339 797 0644
-- 
https://mail.python.org/mailman/listinfo/python-list


[issue42921] Inferred Optional type of wrapper function arguments

2021-01-12 Thread Joseph Perez


New submission from Joseph Perez :

`typing.get_type_hints` gives a different result for a wrapper created with 
`functools.wraps` in case of inferred `Optional` arguments (when the default 
value of the argument is None)

```python
from functools import wraps
from typing import get_type_hints

def foo(bar: int = None): ...

@wraps(foo)
def foo2(*args, **kwargs): ...

print(get_type_hints(foo))  # {'bar': typing.Optional[int]}
print(get_type_hints(foo2))  # {'bar': }
```

This is because `get_type_hints` use the defauts of the wrapper (`foo2`) and 
not those of the wrapped function (`foo`).
This is not consistent with some other tools like `inspect.signature` which 
gives the same signature (and thus same default argument) for the wrapped 
function and its wrapper.

I think this case has simply been forgotten in the resolution of 
https://bugs.python.org/issue37838 (fixing `get_type_hints` not taking `wraps` 
in account at all), because inferred `Optional` is a kind deprecated feature 
(https://github.com/python/typing/issues/275).

--
messages: 385005
nosy: joperez
priority: normal
severity: normal
status: open
title: Inferred Optional type of wrapper function arguments
type: behavior

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



Python 3.8.5

2021-01-06 Thread Joseph Milroy Felix Moraes (Moraes) via Python-list
Good day,

I keep getting this error message when trying to open Python 3.8.5 on my 
computer windows 7 , 64 bit.

---
python.exe - System Error
---
The program can't start because api-ms-win-crt-runtime-l1-1-0.dll is missing 
from your computer. Try reinstalling the program to fix this problem.
---
OK 
---

kindly assist

Regards,
Milroy

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


asyncio cancellation pattern

2020-12-28 Thread Joseph L. Casale
I've started writing some asyncio code in lieu of using threads and
managing concurrency and primitives manually.

Having spent a lot of time using c#'s async implementation, I am struggling
to see an elegant pattern for implementing cancellation. With the necessity
for the loop (that of which I understand) and the disconnect between
context and tasks, how does one act on a failure within a task and invoke
cancellation upwards.

Collecting all tasks and cancelling everything is not appropriate, they may
not necessarily all be part of the graph that needs cancelling.

In c#, we have several patterns available using a cancellation token source
and either passing the token (event only) into the task, or the token source
into the task execution context for signaling during a failure.

Does an easier way then manually creating tasks from coroutines and
tracking them explicitly exist?

Thanks,
jlc
-- 
https://mail.python.org/mailman/listinfo/python-list


RE: pexpect with kadmin

2020-12-23 Thread Joseph L. Casale
> If you have windows 10 can you use Windows Subsystem for Linux  (WSL)
> to install one of the Linux distros and use that?

Interesting idea, sadly I am too far past the deadline on this to go through
the red tape needed to get that in place.

Thanks,
jlc

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


pexpect with kadmin

2020-12-22 Thread Joseph L. Casale
Anyone ever used pexpect with tooling like kadmin and have
insight into how to manage interacting with it?

After setting up debug logging, I was able to adjust the expect
usage to get the input and output logs to at least appear correct
when setting a password for a principal, however even with a
successful return code from kadmin, there is some discrepancy
and the credential is not being set right.

When run manually, the credentials work fine, it's almost as if
kadmin is swallowing the newline from pexpect within the password.

I am using python 3.5 from Windows, over plink.exe, onto a rhel
7 server. Unfortunately, I am stuck with all the levels of indirection.

Thanks,
jlc
-- 
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: setuptools issue

2020-12-17 Thread Joseph L. Casale
> Installed on this Slackware-14.2/x86_64 workstation with python-3.9.1 are:
> python-setuptools-22.0.5-x86_64-1

I just ran into this recently, I don't recall the actual source but it was the 
version
of setuptools having been so old. Your version is from Jun 3, 2016...

Update it, that was what worked for me.

jlc
-- 
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: Python Client Rest API Invocation - POST with empty body - Invalid character found in method name [{}POST]. HTTP method names must be tokens

2020-11-20 Thread Joseph L. Casale
>  Invalid character found in method name [{}POST]. HTTP method names must be 
> tokens.

/snip

> I could see in from wireshark dumps it looked like - {}POST  
> HTTP/1.1

The error message and your own debugging indicate the error.

Your method *name* is {}POST, you have somehow included two
brackets in the name of the method.

jlc
-- 
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


[issue42114] Documentation of ctypes.CDLL does not correspond to code

2020-10-21 Thread Joseph Fox-Rabinovitz


Joseph Fox-Rabinovitz  added the comment:

Last attempt before I give up:

ctypes.CDLL initializer defined in version 3.8 and beyond as

```
def __init__(self, name, mode=DEFAULT_MODE, handle=None,
 use_errno=False,
 use_last_error=False,
 winmode=None):
```

Documentation says `winmode=0`:

```
class ctypes.CDLL(name, mode=DEFAULT_MODE, handle=None, use_errno=False, 
use_last_error=False, winmode=0)
```

Loading of normal DLL from custom directory works when `winmode=0`, but not 
when `winmode=None`. To reproduce, any combination of adding the folder 
containing the DLL via `os.eviron['PATH'] += os.pathsep + ...`, 
`os.add_dll_directory(...)`, `sys.path.append(...)` does not change the 
behavior.

Worked prior to 3.8 because there was no `winmode` parameter, `mode` was passed 
in diretly, and `ctypes.DEFAULT_MODE == 0`.

I don't know whether it's better to update the code, the docs, or something 
else, but based on current info, would prefer updating the code.

Discovery triggered by https://stackoverflow.com/q/59330863/2988730.
Some info summarized in https://stackoverflow.com/a/64472088/2988730.

Link to docs: https://docs.python.org/3.{8,9,10}/library/ctypes.html#ctypes.CDLL
Link to GitHub code: 
https://github.com/python/cpython/blob/3.{8,9}/Lib/ctypes/__init__.py#L340

--

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



[issue42114] Documentation of ctypes.CDLL does not correspond to code

2020-10-21 Thread Joseph Fox-Rabinovitz


Joseph Fox-Rabinovitz  added the comment:

Company firewall mutilated the text. Here is another attempt:

ctypes.CDLL initializer defined in version 3.8 and beyond as

```
def __init__(self, name, mode=DEFAULT_MODE, handle=None,
 use_errno=False,
 use_last_error=False,
 winmode=None):
```

Documentation says `winmode=0`:

```
class ctypes.CDLL(name, mode=DEFAULT_MODE, handle=None, use_errno=False, 
use_last_error=False, winmode=0)
```

Loading of normal DLL from custom directory works when `winmode=0`, but not 
when `winmode=None`. To reproduce, any combination of adding the folder 
containing the DLL via `os.eviron['PATH'] += os.pathsep + ...`, 
`os.add_dll_directory(...)`, `sys.path.append(...)` does not change the 
behavior.

Worked prior to 3.8 because there was no `parameter, and `mode` was passed in 
direcCompany firewall mutilated the text. Here is another attempt:

ctypes.CDLL initializer defined in version 3.8 and beyond as

```
def __init__(self, name, mode=DEFAULT_MODE, handle=None,
 use_errno=False,
 use_last_error=False,
 winmode=None):
```

Documentation says `winmode=0`:

```
class ctypes.CDLL(name, mode=DEFAULT_MODE, handle=None, use_errno=False, 
use_last_error=False, winmode=0)
```

Loading of normal DLL from custom directory works when `winmode=0`, but not 
when `winmode=None`. To reproduce, any combination of adding the folder 
containing the DLL via `os.eviron['PATH'] += os.pathsep + ...`, 
`os.add_dll_directory(...)`, `sys.path.append(...)` does not change the 
behavior.

Worked prior to 3.8 because there was no `winmode` parameter, `mode` was passed 
in diretly, and `ctypes.DEFAULT_MODE == 0`.

I don't know whether it's better to update the code, the docs, or something 
else, but based on current info, would prefer updating the code.

Discovery triggered by https://stackoverflow.com/q/59330863/2988730.
Some info summarized in https://stackoverflow.com/a/64472088/2988730.

yink to docs: https://docs.python.org/3.{8,9,10}/library/ctypes.html#ctypes.CDLL
Link to GitHub code: 
https://github.com/python/cpython/blob/3.{8,9}/Lib/ctypes/__init__.py#L340t.ly, 
`ctyp. .DEFAULT_MODE == 0`.
I don't know whether it's better to update the code, the docs, or something 
else, but based on current info, would prefer updating the code.

Discovery triggered by https://stackoverflow.com/q/59330863/2988730.
Some info summarized in https://stackoverflow.com/a/64472088/2988730.

yink to docs: https://docs.python.org/3.{8,9,10}/library/ctypes.html#ctypes.CDLL
Link to GitHub code: 
https://github.com/python/cpython/blob/3.{8,9}/Lib/ctypes/__init__.py#L340

--

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



[issue42114] Documentation of ctypes.CDLL does not correspond to code

2020-10-21 Thread Joseph Fox-Rabinovitz


Change by Joseph Fox-Rabinovitz :


--
title: Documentation of -> Documentation of ctypes.CDLL does not correspond to 
code

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



[issue42114] Documentation of

2020-10-21 Thread Joseph Fox-Rabinovitz


New submission from Joseph Fox-Rabinovitz :

ctypes.CDLL initializer defined in version 3.8 and beyond as

```
def __init__(self, name, mode=DEFAULT_MODE, handle=None,
 use_errno=False,
 use_last_error=False,
 winmode=None):
```

Documentation says `winmode=0`:

```
class ctypes.CDLL(name, mode=DEFAULT_MODE, handle=None, use_errno=False, 
use_last_error=False, winmode=0)
```

Loading of normal DLL from custom directory works when `winmode=0`, but when 
`winmode=None` To reproduce, any combination of adding the fol += der 
containing the DLL to `os.evia ron['PATH']`, `os.add_dll_directory(...)`

Discoveryos.pathsep + ... triggered by https://stackoverflow.co, `sys.path.appen

Worked prior to 3.8 because there was no `winmode` parameter, and d(...)` does 
not change the behavior.m/q/`mode` was passed in directly, 
59330863/298873`ctypes0. .DEFAULT_MODE == 0`.

I don't know whether it's better to update the code, the docs, or something 
else, but based on current info, would prefer updating the code.Some info 
summarized in https://stackoverflow.com/a/{8,9,}64472088/2988730.

Link to do pagecscorresponding : 
https://docs.python.org/3.10/library/ctypes.html#ctypes.CDLL
730.
Link to GitHub code: 
https://github.com/python/cpython/blob/3.{8,9}/Lib/ctypes/__init__.py#L340

--
components: ctypes
messages: 379261
nosy: madphysicist
priority: normal
severity: normal
status: open
title: Documentation of
versions: Python 3.10, Python 3.8, Python 3.9

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



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: dictionaries an matrices

2020-09-16 Thread joseph pareti
you can use the following: (change the matrices as it suits your app):

import numpy as np
def set_params(w, b):

params = {"w0": w[0], "w1": w[1] , "w2": w[2], "w3": w[3], "w4":
w[4], "b": b}

return params

w = np.random.randn((5))
b = 1
params = set_params(w, b)
for i in range(5):
W = params.get("w"+str(i))
print(W)
B = params.get('b')
print(B)

Am Mi., 16. Sept. 2020 um 13:14 Uhr schrieb Ing Diegohl <
ingdieg...@gmail.com>:

> Good morning everyone
> I would like to know if i can to create a dictionary with two matrices,
> where every element of the first matrix corresponds to dictionary's keys
> and the elements of the second matrix will be the values every key.
> thanks
> --
> https://mail.python.org/mailman/listinfo/python-list
>


-- 
Regards,
Joseph Pareti - Artificial Intelligence consultant
Joseph Pareti's AI Consulting Services
https://www.joepareti54-ai.com/
cell +49 1520 1600 209
cell +39 339 797 0644
-- 
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


[issue41644] builtin type kwargs

2020-08-26 Thread Joseph Perez


Joseph Perez  added the comment:

That's why it's not an interpreter issue but a lack in the official 
documentation where the signature is documented.
I quote https://docs.python.org/3/library/functions.html#type:
> class type(object)
> class type(name, bases, dict)

The second line should be "class type(name, bases, dict, **kwargs)".

(I've mentioned Pycharm and Mypy, but i think it's a kind of side-effect of the 
incomplete official documentation on which is based their typeshed)

In fact, I've raised this issue because I've found myself needing to 
instantiate a class using `type` and kwargs, and I've not found in the 
documentation an example of it.

--

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



[issue41644] builtin type kwargs

2020-08-26 Thread Joseph Perez


New submission from Joseph Perez :

Class definition can have kwargs which are used by `__init_subclass__` (and 
`__prepare__`).
However, passing these kwargs using `type` builtin function instead of class 
definition syntax is not documented; kwargs are not mentioned in the function 
signature.
https://docs.python.org/3/library/functions.html#type

However, passing kwargs to `type` works:
```python
class Foo:
def __init_subclass__(cls, **kwargs):
print(kwargs)
Bar = type("Bar", (Foo,), {}, bar=None) # mypy and Pycharm complain
#> {'bar': None}
```

By the way, the possibility to pass kwargs in `type` call is not documented  in 
https://docs.python.org/3/reference/datamodel.html#customizing-class-creation 
too.

--
assignee: docs@python
components: Documentation
messages: 375936
nosy: docs@python, joperez
priority: normal
severity: normal
status: open
title: builtin type kwargs
versions: Python 3.10, Python 3.6, Python 3.7, Python 3.8, Python 3.9

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



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


[issue41370] PEP 585 and ForwardRef

2020-07-22 Thread Joseph Perez


Joseph Perez  added the comment:

However, PEP 563 will not solve the recursive type alias issue like `A = 
list["A"]` but this is a minor concern.

--

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



[issue41370] PEP 585 and ForwardRef

2020-07-22 Thread Joseph Perez


New submission from Joseph Perez :

PEP 585 current implementation (3.10.0a0) differs from current Generic 
implementation about ForwardRef, as illustrated bellow:
```python
from dataclasses import dataclass, field
from typing import get_type_hints, List, ForwardRef

@dataclass
class Node:
children: list["Node"] = field(default_factory=list)
children2: List["Node"] = field(default_factory=list)

assert get_type_hints(Node) == {"children": list["Node"], "children2": 
List[Node]}
assert List["Node"].__args__ == (ForwardRef("Node"),)
assert list["Node"].__args__ == ("Node",) # No ForwardRef here, so no 
evaluation by get_type_hints
```
There is indeed no kind of ForwardRef for `list` arguments. As shown in the 
example, this affects the result of get_type_hints for recursive types handling.

He could be "fixed" in 2 lines in `typing._eval_type` with something like this :
```python
def _eval_type(t, globalns, localns, recursive_guard=frozenset()):
if isinstance(t, str):
t = ForwardRef(t)
if isinstance(t, ForwardRef):
   ...
```
but it's kind of hacky/dirty.

It's true that this issue will not concern legacy code, 3.9 still being not 
released. So developers of libraries using get_type_hints could add in their 
documentation that `from __future__ import annotations` is mandatory for 
recursive types with PEP 585 (I think I will do it).

By the way, Guido has quickly given his opinion about it in PR 21553: "We 
probably will not ever support this: importing ForwardRef from the built-in 
generic alias code would be problematic, and once from __future__ import 
annotations is always on there's no need to quote the argument anyway." (So 
feel free to close this issue)

--
messages: 374105
nosy: BTaskaya, eric.smith, gvanrossum, joperez, levkivskyi, lukasz.langa, 
vstinner
priority: normal
severity: normal
status: open
title: PEP 585 and ForwardRef
type: behavior
versions: Python 3.9

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



[issue41341] Recursive evaluation of ForwardRef (and PEP 563)

2020-07-19 Thread Joseph Perez


Joseph Perez  added the comment:

Ok, I admit that I did not think about recursive type when proposing this "fix".
I've tried an implementation that just stop when recursion is encountered in a 
PR.

--

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



[issue41341] Recursive evaluation of ForwardRef (and PEP 563)

2020-07-19 Thread Joseph Perez


Change by Joseph Perez :


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

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



[issue41341] Recursive evaluation of ForwardRef (and PEP 563)

2020-07-19 Thread Joseph Perez

New submission from Joseph Perez :

(This issue is already broached in https://bugs.python.org/issue38605, and a in 
some way in https://bugs.python.org/issue35834, but only as a secondary 
subject, that's why I've opened a ticket on this particular issue)

ForwardRef of ForwardRef are not currently evaluated by get_type_hints, only 
the first level is, as illustrated in these examples:
```python
from typing import ForwardRef, Optional, get_type_hints
def func(a: "Optional[\"int\"]"):
pass
assert get_type_hints(func)["a"] == Optional[ForwardRef("int")] 
# one would expect get_type_hints(func)["a"] == Optional[int] 
```
```python
from __future__ import annotations
from typing import ForwardRef, Optional, get_type_hints
def func(a: Optional["int"]):
pass
assert get_type_hints(func)["a"] == Optional[ForwardRef("int")]
# one would expect get_type_hints(func)["a"] == Optional[int] (which is the 
case without the import of __future__.annotations!)
```
On the one hand I find this behavior quite counter-intuitive; I rather think 
ForwardRef as kind of internal (and wonder why there is no leading underscore, 
like _GenericAlias where it's used) and I don't understand the purpose of 
exposing it as the result of the public API get_type_hints. By the way, if 
ForwardRef can be obtained by retrieving annotations without get_type_hints, 
stringified annotations (especially since PEP 563) make get_type_hints kind of 
mandatory, and thus make ForwardRef disappeared (only at the first level so …)

On the other hand, the second example show that adoptions of postponed 
annotations can change the result of get_type_hints; several libraries relying 
of get_type_hints could be broken.

An other issue raised here is that if these ForwardRef are not evaluated by 
get_type_hints, how will be done their evaluatation by the user? It would 
require to retrieve some globalns/localns — too bad, it's exactly what is doing 
get_type_hints. And if the ForwardRef is in a class field, the class 
globalns/localns will have to be kept somewhere while waiting to encounter 
these random ForwardRef; that's feasible, but really tedious.

Agreeing with Guido Von Rossum (https://bugs.python.org/msg370232), this 
behavior could be easily "fixed" in get_type_hints.
Actually, there would be only one line to change in ForwardRef._evaluate:
```python
# from
self.__forward_value__ = _type_check(
eval(self.__forward_code__, globalns, localns),
"Forward references must evaluate to types.",
is_argument=self.__forward_is_argument__)
# to
self.__forward_value__ = _eval_type(
_type_check(
eval(
self.__forward_code__, globalns, localns),
"Forward references must evaluate to types.",
is_argument=self.__forward_is_argument__,
),
globalns,
localns,
)

And if this fix could solve the "double ForwardRef" issue mentionned in 
https://bugs.python.org/issue38605, it would also resolve 
https://bugs.python.org/issue35834 in the same time, raising NameError in case 
of unknown ForwardRef with postponed annotation.

--
messages: 373960
nosy: BTaskaya, eric.smith, gvanrossum, joperez, levkivskyi, lukasz.langa, 
vstinner
priority: normal
severity: normal
status: open
title: Recursive evaluation of ForwardRef (and PEP 563)
type: behavior

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



[issue32958] socket module calls with long host names can fail with idna codec error

2020-07-04 Thread Joseph Hackman


Joseph Hackman  added the comment:

According to the DNS standard, hostnames with more than 63 characters per label 
(the sections between .) are not allowed 
[https://tools.ietf.org/html/rfc1035#section-2.3.1].

That said, enforcing that at the codec level might be the wrong choice. I threw 
together a quick patch moving the limits up to 250, and nothing blew up. It's 
unclear what the general usefulness of such a change would be, since DNS 
servers probably couldn't handle those requests anyway.

As for the original issue, if anybody is still doing something like that, could 
they provide a full example URL? I was unable to reproduce on HTTP (failed in a 
different place), or FTP.

--
nosy: +joseph.hackman

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



i don't understand this python class

2020-06-29 Thread joseph pareti
I have piece of code with constructs as follows:

*class* *SentimentNetwork**:*

*def* __init__*(*self*,* reviews*,* labels*,* hidden_nodes *=* 10*,*
learning_rate *=* 0.1*):*



np*.*random*.*seed*(*1*)*



   self*.*init_network*(**len**(*self*.*review_vocab*),*hidden_nodes*,*
1*,* learning_rate*)*







*def* init_network*(*self*,* input_nodes*,* hidden_nodes*,* output_nodes
*,* learning_rate*):*

# Store the number of nodes in input, hidden, and output layers.

self*.*input_nodes *=* input_nodes

self*.*hidden_nodes *=* hidden_nodes

self*.*output_nodes *=* output_nodes

which makes me think about the redundant usage of* init_network:*

   1. as a method, AND
   2. as a property

So far I have only seen codes where the 2 things are separated, e.g. :

*import* insurance *as* ins

*class* *Vehicle**:*

*def* __init__*(*self*,* speed*,* make*):*

self*.*speed *=* speed

self*.*make *=* make

*class* *car**(*Vehicle*):*

*def* __init__*(*self*,* speed*,* make*):*

Vehicle*.*__init__*(*self*,* speed*,* make*)*

self*.*insurance *=* ins*.*calc*(*make*)*

*def* show_out*(*self*):*

*print**(*'vehicle is '*,*self*.*make*,*' insurance premium '*,*self
*.*insurance*)*

*def* claim*(*self*,* discount*):*

X *=* self*.*insurance *+* discount

*return* X


And hence I am not sure about the behavior of the first code in this email.
-- 
Regards,
Joseph Pareti - Artificial Intelligence consultant
Joseph Pareti's AI Consulting Services
https://www.joepareti54-ai.com/
cell +49 1520 1600 209
cell +39 339 797 0644
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Python-list Digest, Vol 201, Issue 9

2020-06-09 Thread Joseph Jenne via Python-list

On 2020-06-09 09:00, zljubi...@gmail.com wrote:


Well the problem that I am facing with is, that I have to establish interface 
between python and outer system.

Original question was about creation of input object (data that I have received from outer system). 
If I accept recommendation to use "from_" instead of "from", it could work, for 
processing input, because processing is under my control.

However, my process will create output object that I should json serialize and return back to outer system as a 
response to the input. If I will have "from_" object property instead of "from", I believe that I 
should write a custom object to json serializer in order to support changing names from "from_" to 
"from".


It should be possible to name it from_ and then insert it into the __dict__ as 
'from', although a custom serializer
would probably be preferable from a design standpoint.

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


Re: From an existing Pandas DataFrame, how can I create a summary DataFrame based on the union of overlapping date ranges (given a start and an end date) and an additional column?

2020-06-09 Thread joseph pareti
i gave it a shot, see attached

Am Mi., 3. Juni 2020 um 23:38 Uhr schrieb Aaron :

> Hello,
>
> Given a dateframe with trips made by employees of different companies, I am
> trying to generate a new dataframe with only the company names.  I am
> looking to combine the overlapping travel times from employees of the SAME
> company into a single row.  If there are no overlapping travel times, then
> that row just transfers over as-is.  When there are overlapping travel
> times, then the following will happen:
>
> --The name field is removed b/c that is no longer relevant (company name
> stays), the Depart date will be the earliest date of any of the trip dates
> regardless of the employee, the Return date will be the latest date of any
> of the trip dates regardless of the employee, the charges for the trip will
> be summed
>
> For example, if trips had dates 01/01/20 - 01/31/20, 01/15/20 - 02/15/20,
> 02/01-20 - 02/28/20, then all three would be combined.  The starting date
> will be 1/1/20 and ending as of 2/28/20.  Basically, the company was on
> that trip from start to finish… kinda like a relay run handing off the
> baton.  Also, the charges will be summed for each of those trips and
> transferred over to the single row.
>
> Here is the starting dataframe code/output (note: the row order is
> typically not already sorted by company name as in this example):
>
> import pandas as pd
>
>
> emp_trips = {'Name': ['Bob','Joe','Sue','Jack', 'Henry', 'Frank',
> 'Lee', 'Jack'],
> 'Company': ['ABC', 'ABC', 'ABC', 'HIJ', 'HIJ', 'DEF', 'DEF',
> 'DEF'],
> 'Depart' : ['01/01/2020', '01/01/2020', '01/06/2020',
> '01/01/2020', '05/01/2020', '01/13/2020', '01/12/2020', '01/14/2020'],
> 'Return' : ['01/31/2020', '02/15/2020', '02/20/2020',
> '03/01/2020', '05/05/2020', '01/15/2020', '01/30/2020', '02/02/2020'],
> 'Charges': [10.10, 20.25, 30.32, 40.00, 50.01, 60.32, 70.99, 80.87]
> }
>
> df = pd.DataFrame(emp_trips, columns = ['Name', 'Company', 'Depart',
> 'Return', 'Charges'])
> # Convert to date format
> df['Return']= pd.to_datetime(df['Return'])
> df['Depart']= pd.to_datetime(df['Depart'])
>
>   Name Company Depart Return  Charges0Bob ABC
> 2020-01-01 2020-01-3110.101Joe ABC 2020-01-01 2020-02-15
>  20.252Sue ABC 2020-01-06 2020-02-2030.323   Jack HIJ
> 2020-01-01 2020-03-0140.004  Henry HIJ 2020-05-01 2020-05-05
>  50.015  Frank DEF 2020-01-13 2020-01-1560.326Lee DEF
> 2020-01-12 2020-01-3070.997   Jack DEF 2020-01-14 2020-02-02
>  80.87
>
> And, here is the desired/generated dataframe:
>
>   Company  Depart  Return  Charges0 ABC  01/01/2020
> 02/20/202060.671 HIJ  01/01/2020  03/01/202040.002 HIJ
>  05/01/2020  05/05/202050.013 DEF  01/12/2020  02/02/2020
> 212.18
>
> I have been trying to use a combination of sorting and grouping but
> the best I've achieved is reordering the dataframe.  Even though I am
> able to sort/group based on values, I still run into the issues of
> finding overlapping date ranges and pulling out all trips based on a
> single company per aggregate/overlapping date range.
>
> Thank you in advance for any help!
>
> Aaron
> --
> https://mail.python.org/mailman/listinfo/python-list
>


-- 
Regards,
Joseph Pareti - Artificial Intelligence consultant
Joseph Pareti's AI Consulting Services
https://www.joepareti54-ai.com/
cell +49 1520 1600 209
cell +39 339 797 0644
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: [RELEASE] Python 3.9.0b1 is now available for testing

2020-06-01 Thread Joseph Jenne via Python-list


I used https://github.com/python/pyperformance pyperformance to 
compare Arch linux latest



Python 3.8.3 (default, May 17 2020, 18:15:42) [GCC 10.1.0] on linux
Type "help", "copyright", "credits" or "license" for more information.




against a vanilla build (configure make makeinstall) of python 3.9b1


Python 3.9.0b1 (default, May 19 2020, 21:09:14) [GCC 10.1.0] on linux
Type "help", "copyright", "credits" or "license" for more information.




I find all the bench marks seem to be slower in python 3.9b1.


38.json
===

Performance version: 1.0.1
Report on Linux-5.6.14-arch1-1-x86_64-with-glibc2.2.5
Number of logical CPUs: 4
Start date: 2020-05-31 04:00:24.503704
End date: 2020-05-31 04:22:44.961331

39.json
===

Performance version: 1.0.1
Report on Linux-5.6.14-arch1-1-x86_64-with-glibc2.31
Number of logical CPUs: 4
Start date: 2020-05-31 04:23:21.247268
End date: 2020-05-31 04:49:09.891889

### 2to3 ###
Mean +- std dev: 437 ms +- 5 ms -> 548 ms +- 7 ms: 1.25x slower
Significant (t=-96.22)

### chameleon ###
Mean +- std dev: 12.5 ms +- 0.1 ms -> 16.2 ms +- 0.2 ms: 1.30x slower
Significant (t=-111.53)

> ...

Is this because I haven't built in the same way as Arch or are there 
real slowdowns in this beta? Or even dumber have I got the results the 
wrong way round?

--
Robin Becker


Most builds of python included with distribution packages are built with 
various levels of optimization. I have experienced slowdowns from source 
built python of the same version as the distribution python even when 
using some optimization flags with the configure script. This appears to 
be normal behavior and is not cause for concern about the performance of 
python 3.9.0b1


--

Joseph Jenne


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


Constructing mime image attachment

2020-05-28 Thread Joseph L. Casale
I have some json encoded input for nodemailer 
(https://nodemailer.com/message/embedded-images)
where the path key is a string value which contains the base64 encoded data 
such as:

{
html: 'Embedded image: ',
attachments: [{
filename: 'image.png',
path: 'data:image/png;base64,iVBORw',
cid: 'uni...@nodemailer.com'
}]
}

Does an approach exist to construct a MIMEImage object with the existing
base64 string without parsing it and decoding it?

Thanks,
jlc
-- 
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: Help with installation please

2020-05-15 Thread Jhoana Kacheva Melissa Joseph
Ok, thanks Souvik. Appreciate your help.

On Fri, May 15, 2020, 11:47 PM Souvik Dutta  wrote:

> I dont know if you should shift from powershell to cmd. Python kinda does
> not work in powershell.
>
> Souvik flutter dev
>
> On Sat, May 16, 2020, 8:54 AM Jhoana Kacheva Melissa Joseph <
> kachev...@gmail.com> wrote:
>
>> 藍藍 but I still get the error in powershell. What should I do Souvik?
>>
>> On Fri, May 15, 2020, 11:20 PM Souvik Dutta 
>> wrote:
>>
>>> Then you will have to use python3 forever in your life (atleast as long
>>> as you don't change your os... 藍藍).
>>>
>>> On Sat, 16 May, 2020, 8:42 am Jhoana Kacheva Melissa Joseph, <
>>> kachev...@gmail.com> wrote:
>>>
>>>> When I turn off the other one, it brought me to the store.
>>>>
>>>> Yes, I did the path
>>>>
>>>> On Fri, May 15, 2020, 11:01 PM Souvik Dutta 
>>>> wrote:
>>>>
>>>>> Have you switched off both the pythons? If so then switch on one off
>>>>> them and try. If it still doesn't work then switch on the previous one and
>>>>> off the other and try again.
>>>>>
>>>>> On Sat, 16 May, 2020, 8:29 am Souvik Dutta, 
>>>>> wrote:
>>>>>
>>>>>> Have you added python into path?
>>>>>>
>>>>>> On Sat, 16 May, 2020, 8:15 am Jhoana Kacheva Melissa Joseph, <
>>>>>> kachev...@gmail.com> wrote:
>>>>>>
>>>>>>> Thanks for the tip! Now that I turned it off. This is what it says.
>>>>>>>
>>>>>>> Please see attached
>>>>>>>
>>>>>>>
>>>>>>>
>>>>>>> On Fri, May 15, 2020, 9:10 PM Souvik Dutta 
>>>>>>> wrote:
>>>>>>>
>>>>>>>> App execution aliases is not on store. Search it in the start menu.
>>>>>>>>
>>>>>>>> On Sat, 16 May, 2020, 6:27 am Jhoana Kacheva Melissa Joseph, <
>>>>>>>> kachev...@gmail.com> wrote:
>>>>>>>>
>>>>>>>>> Thanks for the tip! But there is nothing to unchecked.
>>>>>>>>>
>>>>>>>>> I typed python on powershell, once redirected to the app store I
>>>>>>>>> type app execution aliases in search bar, hit enter and I see this 
>>>>>>>>> picture
>>>>>>>>> attached. Am I missing something please ?
>>>>>>>>>
>>>>>>>>>
>>>>>>>>>
>>>>>>>>> On Fri, May 15, 2020, 7:59 PM Souvik Dutta <
>>>>>>>>> souvik.vik...@gmail.com> wrote:
>>>>>>>>>
>>>>>>>>>> Windows has a default python 3. that is not installed
>>>>>>>>>> but registered (which is as wierd as Microsoft). That is why you are
>>>>>>>>>> redirected everytime to the store. You might want to check app 
>>>>>>>>>> execution
>>>>>>>>>> aliases in the search bar an scroll down to find the two pythons and 
>>>>>>>>>> then
>>>>>>>>>> uncheck one of them to avoid future confusions.
>>>>>>>>>>
>>>>>>>>>> On Sat, 16 May, 2020, 12:01 am Jhoana Kacheva Melissa Joseph, <
>>>>>>>>>> kachev...@gmail.com> wrote:
>>>>>>>>>>
>>>>>>>>>>> Hello,
>>>>>>>>>>>
>>>>>>>>>>> I downloaded python 3.8 in my windows, I selected the box for
>>>>>>>>>>> the path but
>>>>>>>>>>> when I try to run it in powershell it brought me to app store to
>>>>>>>>>>> get it
>>>>>>>>>>> again.
>>>>>>>>>>>
>>>>>>>>>>> Please let me know
>>>>>>>>>>>
>>>>>>>>>>> Thanks
>>>>>>>>>>> Melissa
>>>>>>>>>>> --
>>>>>>>>>>> https://mail.python.org/mailman/listinfo/python-list
>>>>>>>>>>>
>>>>>>>>>>
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Help with installation please

2020-05-15 Thread Jhoana Kacheva Melissa Joseph
藍藍 but I still get the error in powershell. What should I do Souvik?

On Fri, May 15, 2020, 11:20 PM Souvik Dutta  wrote:

> Then you will have to use python3 forever in your life (atleast as long as
> you don't change your os... 藍藍).
>
> On Sat, 16 May, 2020, 8:42 am Jhoana Kacheva Melissa Joseph, <
> kachev...@gmail.com> wrote:
>
>> When I turn off the other one, it brought me to the store.
>>
>> Yes, I did the path
>>
>> On Fri, May 15, 2020, 11:01 PM Souvik Dutta 
>> wrote:
>>
>>> Have you switched off both the pythons? If so then switch on one off
>>> them and try. If it still doesn't work then switch on the previous one and
>>> off the other and try again.
>>>
>>> On Sat, 16 May, 2020, 8:29 am Souvik Dutta, 
>>> wrote:
>>>
>>>> Have you added python into path?
>>>>
>>>> On Sat, 16 May, 2020, 8:15 am Jhoana Kacheva Melissa Joseph, <
>>>> kachev...@gmail.com> wrote:
>>>>
>>>>> Thanks for the tip! Now that I turned it off. This is what it says.
>>>>>
>>>>> Please see attached
>>>>>
>>>>>
>>>>>
>>>>> On Fri, May 15, 2020, 9:10 PM Souvik Dutta 
>>>>> wrote:
>>>>>
>>>>>> App execution aliases is not on store. Search it in the start menu.
>>>>>>
>>>>>> On Sat, 16 May, 2020, 6:27 am Jhoana Kacheva Melissa Joseph, <
>>>>>> kachev...@gmail.com> wrote:
>>>>>>
>>>>>>> Thanks for the tip! But there is nothing to unchecked.
>>>>>>>
>>>>>>> I typed python on powershell, once redirected to the app store I
>>>>>>> type app execution aliases in search bar, hit enter and I see this 
>>>>>>> picture
>>>>>>> attached. Am I missing something please ?
>>>>>>>
>>>>>>>
>>>>>>>
>>>>>>> On Fri, May 15, 2020, 7:59 PM Souvik Dutta 
>>>>>>> wrote:
>>>>>>>
>>>>>>>> Windows has a default python 3. that is not installed
>>>>>>>> but registered (which is as wierd as Microsoft). That is why you are
>>>>>>>> redirected everytime to the store. You might want to check app 
>>>>>>>> execution
>>>>>>>> aliases in the search bar an scroll down to find the two pythons and 
>>>>>>>> then
>>>>>>>> uncheck one of them to avoid future confusions.
>>>>>>>>
>>>>>>>> On Sat, 16 May, 2020, 12:01 am Jhoana Kacheva Melissa Joseph, <
>>>>>>>> kachev...@gmail.com> wrote:
>>>>>>>>
>>>>>>>>> Hello,
>>>>>>>>>
>>>>>>>>> I downloaded python 3.8 in my windows, I selected the box for the
>>>>>>>>> path but
>>>>>>>>> when I try to run it in powershell it brought me to app store to
>>>>>>>>> get it
>>>>>>>>> again.
>>>>>>>>>
>>>>>>>>> Please let me know
>>>>>>>>>
>>>>>>>>> Thanks
>>>>>>>>> Melissa
>>>>>>>>> --
>>>>>>>>> https://mail.python.org/mailman/listinfo/python-list
>>>>>>>>>
>>>>>>>>
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Help with installation please

2020-05-15 Thread Jhoana Kacheva Melissa Joseph
When I turn off the other one, it brought me to the store.

Yes, I did the path

On Fri, May 15, 2020, 11:01 PM Souvik Dutta  wrote:

> Have you switched off both the pythons? If so then switch on one off them
> and try. If it still doesn't work then switch on the previous one and off
> the other and try again.
>
> On Sat, 16 May, 2020, 8:29 am Souvik Dutta, 
> wrote:
>
>> Have you added python into path?
>>
>> On Sat, 16 May, 2020, 8:15 am Jhoana Kacheva Melissa Joseph, <
>> kachev...@gmail.com> wrote:
>>
>>> Thanks for the tip! Now that I turned it off. This is what it says.
>>>
>>> Please see attached
>>>
>>>
>>>
>>> On Fri, May 15, 2020, 9:10 PM Souvik Dutta 
>>> wrote:
>>>
>>>> App execution aliases is not on store. Search it in the start menu.
>>>>
>>>> On Sat, 16 May, 2020, 6:27 am Jhoana Kacheva Melissa Joseph, <
>>>> kachev...@gmail.com> wrote:
>>>>
>>>>> Thanks for the tip! But there is nothing to unchecked.
>>>>>
>>>>> I typed python on powershell, once redirected to the app store I type
>>>>> app execution aliases in search bar, hit enter and I see this picture
>>>>> attached. Am I missing something please ?
>>>>>
>>>>>
>>>>>
>>>>> On Fri, May 15, 2020, 7:59 PM Souvik Dutta 
>>>>> wrote:
>>>>>
>>>>>> Windows has a default python 3. that is not installed but
>>>>>> registered (which is as wierd as Microsoft). That is why you are 
>>>>>> redirected
>>>>>> everytime to the store. You might want to check app execution aliases in
>>>>>> the search bar an scroll down to find the two pythons and then uncheck 
>>>>>> one
>>>>>> of them to avoid future confusions.
>>>>>>
>>>>>> On Sat, 16 May, 2020, 12:01 am Jhoana Kacheva Melissa Joseph, <
>>>>>> kachev...@gmail.com> wrote:
>>>>>>
>>>>>>> Hello,
>>>>>>>
>>>>>>> I downloaded python 3.8 in my windows, I selected the box for the
>>>>>>> path but
>>>>>>> when I try to run it in powershell it brought me to app store to get
>>>>>>> it
>>>>>>> again.
>>>>>>>
>>>>>>> Please let me know
>>>>>>>
>>>>>>> Thanks
>>>>>>> Melissa
>>>>>>> --
>>>>>>> https://mail.python.org/mailman/listinfo/python-list
>>>>>>>
>>>>>>
-- 
https://mail.python.org/mailman/listinfo/python-list


Help with installation please

2020-05-15 Thread Jhoana Kacheva Melissa Joseph
Hello,

I downloaded python 3.8 in my windows, I selected the box for the path but
when I try to run it in powershell it brought me to app store to get it
again.

Please let me know

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


Re: basic Python question

2020-05-08 Thread joseph pareti
yet, something is still unclear; in Python you can do things like:

*clf0.fit(X_train, y_train)*

which is not the way I programmed in other languages where a left-hand side
and a right hand side is required.

Am Fr., 8. Mai 2020 um 21:52 Uhr schrieb joseph pareti <
joeparet...@gmail.com>:

> yes, it is random forest classifier from scikit learn. Thank you.
>
> Am Fr., 8. Mai 2020 um 21:50 Uhr schrieb MRAB  >:
>
>> On 2020-05-08 20:02, joseph pareti wrote:
>> > In general I prefer doing:
>> >
>> >
>> > X_train, X_test, y_train, y_test = train_test_split(X, y,
>> test_size=0.33, random_state=42)
>>  >clf = RandomForestClassifier(n_estimators = 100, max_depth=
>> > None) *clf_f = clf.fit(X_train, y_train)* predicted_labels =
>> clf_f.predict(
>> > X_test) score = clf.score(X_test, y_test) score1 =
>> metrics.accuracy_score(
>> > y_test, predicted_labels)
>> >
>> >
>> > rather than:
>> >
>> > X_train, X_test, y_train, y_test = train_test_split(X, y,
>> test_size=0.33,
>> > random_state=42) clf0=RandomForestClassifier(n_estimators=100,
>> max_depth=
>> > None) *clf0.fit(X_train, y_train)* y_pred =clf0.predict(X_test) score=
>> > metrics.accuracy_score(y_test, y_pred)
>> >
>> >
>> > Are the two codes really equivalent?
>> >
>> You didn't give any context and say what package you're using!
>>
>> After searching for "RandomForestClassifier", I'm guessing that you're
>> using scikit.
>>
>>  From the documentation here:
>>
>>
>> https://scikit-learn.org/stable/modules/generated/sklearn.ensemble.RandomForestClassifier.html#sklearn.ensemble.RandomForestClassifier.fit
>>
>> it says:
>>
>>  Returns: self : object
>>
>> so it looks like clf.fit(...) returns clf.
>>
>> That being the case, then, yes, they're equivalent.
>> --
>> https://mail.python.org/mailman/listinfo/python-list
>>
>
>
> --
> Regards,
> Joseph Pareti - Artificial Intelligence consultant
> Joseph Pareti's AI Consulting Services
> https://www.joepareti54-ai.com/
> cell +49 1520 1600 209
> cell +39 339 797 0644
>


-- 
Regards,
Joseph Pareti - Artificial Intelligence consultant
Joseph Pareti's AI Consulting Services
https://www.joepareti54-ai.com/
cell +49 1520 1600 209
cell +39 339 797 0644
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: basic Python question

2020-05-08 Thread joseph pareti
yes, it is random forest classifier from scikit learn. Thank you.

Am Fr., 8. Mai 2020 um 21:50 Uhr schrieb MRAB :

> On 2020-05-08 20:02, joseph pareti wrote:
> > In general I prefer doing:
> >
> >
> > X_train, X_test, y_train, y_test = train_test_split(X, y,
> test_size=0.33, random_state=42)
>  >clf = RandomForestClassifier(n_estimators = 100, max_depth=
> > None) *clf_f = clf.fit(X_train, y_train)* predicted_labels =
> clf_f.predict(
> > X_test) score = clf.score(X_test, y_test) score1 =
> metrics.accuracy_score(
> > y_test, predicted_labels)
> >
> >
> > rather than:
> >
> > X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.33,
> > random_state=42) clf0=RandomForestClassifier(n_estimators=100, max_depth=
> > None) *clf0.fit(X_train, y_train)* y_pred =clf0.predict(X_test) score=
> > metrics.accuracy_score(y_test, y_pred)
> >
> >
> > Are the two codes really equivalent?
> >
> You didn't give any context and say what package you're using!
>
> After searching for "RandomForestClassifier", I'm guessing that you're
> using scikit.
>
>  From the documentation here:
>
>
> https://scikit-learn.org/stable/modules/generated/sklearn.ensemble.RandomForestClassifier.html#sklearn.ensemble.RandomForestClassifier.fit
>
> it says:
>
>  Returns: self : object
>
> so it looks like clf.fit(...) returns clf.
>
> That being the case, then, yes, they're equivalent.
> --
> https://mail.python.org/mailman/listinfo/python-list
>


-- 
Regards,
Joseph Pareti - Artificial Intelligence consultant
Joseph Pareti's AI Consulting Services
https://www.joepareti54-ai.com/
cell +49 1520 1600 209
cell +39 339 797 0644
-- 
https://mail.python.org/mailman/listinfo/python-list


basic Python question

2020-05-08 Thread joseph pareti
In general I prefer doing:


X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.33,
random_state=42) clf = RandomForestClassifier(n_estimators = 100, max_depth=
None) *clf_f = clf.fit(X_train, y_train)* predicted_labels = clf_f.predict(
X_test) score = clf.score(X_test, y_test) score1 = metrics.accuracy_score(
y_test, predicted_labels)






rather than:

X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.33,
random_state=42) clf0=RandomForestClassifier(n_estimators=100, max_depth=
None) *clf0.fit(X_train, y_train)* y_pred =clf0.predict(X_test) score=
metrics.accuracy_score(y_test, y_pred)














Are the two codes really equivalent?
-- 
Regards,
Joseph Pareti - Artificial Intelligence consultant
Joseph Pareti's AI Consulting Services
https://www.joepareti54-ai.com/
cell +49 1520 1600 209
cell +39 339 797 0644
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Pip not working on windows

2020-05-03 Thread joseph pareti
are you doing *pip** install* from Windows cmd of from Anaconda prompt? I
used the latter and it works

Am So., 3. Mai 2020 um 16:48 Uhr schrieb Aakash Jana <
aakashjana2...@gmail.com>:

> I recently upgraded pip to version 20.1 and now whenever I try pup install
> on my PC I get the following error :- Fatal error in launcher : unable to
> create process using '"c:\python38\python.exe '
> "c:\Python38\Scripts\pip.exe" : The system cannot find the file specified.
> But when I manually inspected the folder  the files were there I even
> tried upgrading it by python -m pip install --upgrade pip which worked but
> I still can not use pip.
> --
> https://mail.python.org/mailman/listinfo/python-list
>


-- 
Regards,
Joseph Pareti - Artificial Intelligence consultant
Joseph Pareti's AI Consulting Services
https://www.joepareti54-ai.com/
cell +49 1520 1600 209
cell +39 339 797 0644
-- 
https://mail.python.org/mailman/listinfo/python-list


  1   2   3   4   5   6   7   >