Re: Typing: Is there a "cast operator"?

2022-10-26 Thread Peter Otten

On 24/10/2022 05:19, Chris Angelico wrote:

On Mon, 24 Oct 2022 at 14:15, Dan Stromberg  wrote:

I've found that mypy understands simple assert statements.

So if you:
if f is not None:
 assert f is not None
 os.write(f, ...)

You might be in good shape.


Why can't it simply understand the if statement?


Could it be that this specific problem is fixed in current mypy?
I get

$ type .\tmp.py
import os

f = None
if f is None:
f = os.open("tmp.txt", os.O_RDWR|os.O_CREAT)
os.write(f, b"yadda")
$ mypy tmp.py
Success: no issues found in 1 source file

My attempt to verify that

if name is None: ...

is recognized:

$ type .\tmp2.py
import os
import random

f = None
if random.randrange(2):
f = os.open("tmp.txt", os.O_RDWR|os.O_CREAT)
os.write(f, b"yadda")
$ mypy tmp2.py
tmp2.py:7: error: Argument 1 to "write" has incompatible type
"Optional[int]"; expected "int"
Found 1 error in 1 file (checked 1 source file)
$ mypy --version
mypy 0.982 (compiled: yes)
$

I'm not a fan of

coddling a type system like this. The entire point of type checking is
to help you find bugs more efficiently, so if you have to repeat
yourself every time you do these kinds of checks just so that mypy is
satisfied, that's counter-productive (case in point: what happens if
you say "if fn is not None: assert f is not None"? Now you've
introduced a bug just to deal with the type system).

ChrisA


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


Re: Any PyQt developers here?

2022-10-26 Thread DFS

On 10/25/2022 1:45 PM, Thomas Passin wrote:

On 10/25/2022 1:03 PM, DFS wrote:

Having problems with removeRow() on a QTableView object.


removeRow() isn't listed as being a method of a QTableView, not even an 
inherited method, so how are you calling removeRow() on it? (See 
https://doc.qt.io/qt-6/qtableview-members.html)



* I thought I was calling it the same way it's called with
  QTableWidgets:  tbl.removeRow()

  But looking at my code again I was using tbl.model().removeRow()


* Plus I found several others online with similar removeRow() issues
  with QTableViews.


* Plus the code didn't throw an error:

selected = tbl.selectionModel().selectedRows()
#reverse sort the selected items to delete from bottom up
selected = sorted(selected,reverse=True)
for i,val in enumerate(selected):
 tbl.model().removeRow(selected[i].row())


But... as you say, when looking at the docs, removeRow() isn't even one 
of the slots for QTableViews.  So duh!


I see the QTableView.hideRow(row) method, which does exactly what I need.

Thanks man!





After calling removeRow(), the screen isn't updating.  It's as if the 
model is read-only, but it's a QSqlTableModel() model, which is not 
read-only.


The underlying SQL is straightforward (one table) and all columns are 
editable.


None of the editStrategies are working either.

I tried everything I can think of, including changes to the 
EditTriggers, but no luck.  HELP!


FWIW, the same removeRow() code works fine with a QTableWidget.

---
object creation and data loading all works fine
---
#open db connection
qdb = QSqlDatabase.addDatabase("QSQLITE")
qdb.setDatabaseName(dbname)
qdb.open()

#prepare query and execute to return data
query = QSqlQuery()
query.prepare(cSQL)
query.exec_()

#set model type and query
model = QSqlTableModel()
model.setQuery(query)

#assign model to QTableView object
view = frm.tblPostsView
view.setModel(model)

#get all data
while(model.canFetchMore()): model.fetchMore()
datarows = model.rowCount()



---
iterate selected rows also works fine
SelectionMode is Extended.
identical code works for a QTableWidget
---
selected = tbl.selectionModel().selectedRows()
#reverse sort the selected items to delete from bottom up
selected = sorted(selected,reverse=True)
for i,val in enumerate(selected):
 tbl.model().removeRow(selected[i].row())





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


Re: Any PyQt developers here?

2022-10-26 Thread DFS

On 10/25/2022 2:03 PM, Barry Scott wrote:

There is an active PyQt mailing list that has lots of helpful and knowledgeable 
people on it.

https://www.riverbankcomputing.com/mailman/listinfo/pyqt

Barry



Thanks.  I'll send some questions their way, I'm sure.
--
https://mail.python.org/mailman/listinfo/python-list


Re: score function in linear regression model

2022-10-26 Thread Fatemeh Heydari
On Monday, October 24, 2022 at 7:14:10 AM UTC-7, Reto wrote:
> On Sun, Oct 23, 2022 at 05:11:10AM -0700, Fatemeh Heydari wrote: 
> > model.score(X,Y) 
> 
> That will basically check how good your model is. 
> 
> It takes a bunch of X values with known values, which you provide in Y 
> and compares the output of model.Predict(X) with the Y's and gives you 
> some metrics as to how good that performed. 
> 
> In the case of linear regression that be R^2, the coefficient of 
> determination 
> of the prediction. 
> 
> Cheers, 
> Reto


Dear Reto
Thanks for your attention. But I calculated R^2 for the model with the code : 
r2_score(predictedY,Y)
and I got different result from the "score " function. I wish to know what 
mathematical formulation is behind this function

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


Re: score function in linear regression model

2022-10-26 Thread Thomas Passin

There's a fairly good rundown of score() here:

"[Python/Sklearn] How does .score() works?"
https://www.kaggle.com/getting-started/27261

On 10/26/2022 2:18 AM, Fatemeh Heydari wrote:

On Monday, October 24, 2022 at 7:14:10 AM UTC-7, Reto wrote:

On Sun, Oct 23, 2022 at 05:11:10AM -0700, Fatemeh Heydari wrote:

model.score(X,Y)


That will basically check how good your model is.

It takes a bunch of X values with known values, which you provide in Y
and compares the output of model.Predict(X) with the Y's and gives you
some metrics as to how good that performed.

In the case of linear regression that be R^2, the coefficient of determination
of the prediction.

Cheers,
Reto



Dear Reto
Thanks for your attention. But I calculated R^2 for the model with the code : 
r2_score(predictedY,Y)
and I got different result from the "score " function. I wish to know what 
mathematical formulation is behind this function

Thanks again


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


"mailcap" to be removed (3.13) -- suggested replacement ?

2022-10-26 Thread Karsten Hilbert
Dear list,

Python 3.11 marks "mailcap" for removal in 3.13. The
documentation speaks about "mimetypes" being a replacement,
of sorts. I agree with removing dead batteries.

However, I can't really see how "mimetypes" helps in
replacing the functionality of "mailcap" ?

Put another way: what is the suggested way of replacing that
module in existing code ?  The use case is "find the viewer
for any kind of file (by mimetype), as long as the system
knows".

Thanks,
Karsten
--
GPG  40BE 5B0E C98E 1713 AFA6  5BC0 3BEA AC80 7D4F C89B
-- 
https://mail.python.org/mailman/listinfo/python-list


Operator: inappropriate wording?

2022-10-26 Thread elas tica
Quotes from The Python Language Reference, Release 3.10.8:

- Note that tuples are not formed by the parentheses, but rather by use of the 
comma operator (p. 66)
- Note: If the object is a class instance and the attribute reference occurs on 
both sides of the assignment operator (p. 86)
- The second half of the list, the augmented assignment operators, serve 
lexically as delimiters, but also perform an operation (p. 15)



Do you agree with this use of the term "operator"? 

Because there is no such "comma operator" in Python as explained by the 
official FAQ: 
https://docs.python.org/3/faq/programming.html#what-s-up-with-the-comma-operator-s-precedence

And, =, += and the like are not operators since (a=b), (a+=b), etc have no 
value. There is no assignment operator instead there exists an assignment 
statement. The only assignment operator I can figure out is the walrus 
operator. To confirm, The Python Language Reference gives here:

https://docs.python.org/3/reference/lexical_analysis.html#operators

the set of tokens considered as operator and the =, += tokens are not listed 
whereas := is.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Operator: inappropriate wording?

2022-10-26 Thread Roel Schroeven




elas tica schreef op 26/10/2022 om 21:01:

Quotes from The Python Language Reference, Release 3.10.8:

- Note that tuples are not formed by the parentheses, but rather by use of the 
comma operator (p. 66)
- Note: If the object is a class instance and the attribute reference occurs on 
both sides of the assignment operator (p. 86)
- The second half of the list, the augmented assignment operators, serve 
lexically as delimiters, but also perform an operation (p. 15)



Do you agree with this use of the term "operator"?
It's a bit fuzzy, I guess. Comma, =, +=, *= etc. are in section 2.6 
"Delimiters" and not in section 2.5 "Operators" of The Python Language 
Reference, which would seem to imply that those are not operators. But 
the text in section 2.6 then says "The second half of the list, the 
augmented assignment _operators_, serve lexically as delimiters, but 
also perform an operation.", so at least the augmented assignment 
operators are seen as operators despite not being in the Operators section.



Because there is no such "comma operator" in Python as explained by the 
official FAQ: 
https://docs.python.org/3/faq/programming.html#what-s-up-with-the-comma-operator-s-precedence

That does seem to contradict the text in the language reference.

And, =, += and the like are not operators since (a=b), (a+=b), etc have no 
value. There is no assignment operator instead there exists an assignment 
statement. The only assignment operator I can figure out is the walrus operator.
I think that's a good point too. The language reference calls those 
things 'delimiters', which doesn't feel like a good description either 
for many of them. I find it weird to think of =, *+, +=as a delimiter. 
Maybe that's why those things are called operators anyway instead of 
delimiters in many places? Things like "Note: If the object is a class 
instance and the attribute reference occurs on both sides of the 
assignment _delimiter_" sound a bit weird I feel, even though completely 
correct according to the language reference.


So yeah I think you have a point that the terminology regarding those 
tokens is not very consistent at the least.


--
"Honest criticism is hard to take, particularly from a relative, a friend,
an acquaintance, or a stranger."
-- Franklin P. Jones

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


Re: Operator: inappropriate wording?

2022-10-26 Thread Weatherby,Gerard
No. If the docs say in one place a comma is not an operator, they shouldn’t 
call it an operator in another place.

I’ve submitted a pull request https://github.com/python/cpython/pull/98736 -- 
we’ll have to see what The Powers That Be think.

From: Python-list  on 
behalf of elas tica 
Date: Wednesday, October 26, 2022 at 3:32 PM
To: [email protected] 
Subject: Operator: inappropriate wording?
*** Attention: This is an external email. Use caution responding, opening 
attachments or clicking on links. ***

Quotes from The Python Language Reference, Release 3.10.8:

- Note that tuples are not formed by the parentheses, but rather by use of the 
comma operator (p. 66)
- Note: If the object is a class instance and the attribute reference occurs on 
both sides of the assignment operator (p. 86)
- The second half of the list, the augmented assignment operators, serve 
lexically as delimiters, but also perform an operation (p. 15)



Do you agree with this use of the term "operator"?

Because there is no such "comma operator" in Python as explained by the 
official FAQ: 
https://urldefense.com/v3/__https://docs.python.org/3/faq/programming.html*what-s-up-with-the-comma-operator-s-precedence__;Iw!!Cn_UX_p3!nL9TZBaXZH87JOWNN7D_3E0ytfdXH8tkUxvTdF4dXbVqOJS0yF0C7idVg4ZGee7FiFyPQqqNRcNeVeWVu5edfg$

And, =, += and the like are not operators since (a=b), (a+=b), etc have no 
value. There is no assignment operator instead there exists an assignment 
statement. The only assignment operator I can figure out is the walrus 
operator. To confirm, The Python Language Reference gives here:

https://urldefense.com/v3/__https://docs.python.org/3/reference/lexical_analysis.html*operators__;Iw!!Cn_UX_p3!nL9TZBaXZH87JOWNN7D_3E0ytfdXH8tkUxvTdF4dXbVqOJS0yF0C7idVg4ZGee7FiFyPQqqNRcNeVeVnKYO3BA$

the set of tokens considered as operator and the =, += tokens are not listed 
whereas := is.
--
https://urldefense.com/v3/__https://mail.python.org/mailman/listinfo/python-list__;!!Cn_UX_p3!nL9TZBaXZH87JOWNN7D_3E0ytfdXH8tkUxvTdF4dXbVqOJS0yF0C7idVg4ZGee7FiFyPQqqNRcNeVeW3iNHD7g$
-- 
https://mail.python.org/mailman/listinfo/python-list


A little source file analyzer

2022-10-26 Thread DFS

Nothing special, but kind of fun to use

$python progname.py sourcefile.py

-
#count blank lines, comments, source code

import sys

#counters
imports, blanks,comments, source  = 0,0,0,0
functions, dbexec, total  = 0,0,0

#python builtins
builtins = 0
bins = 
['abs','aiter','all','any','anext','ascii','bin','bool','breakpoint','bytearray','bytes','callable','chr','classmethod','compile','complex','delattr','dict','dir','divmod','enumerate','eval','exec','filter','float','format','frozenset','getattr','globals','hasattr','hash','help','hex','id','input','int','isinstance','issubclass','iter','len','list','locals','map','max','memoryview','min','next','object','oct','open','ord','pow','property','range','repr','reversed','round','set','setattr','slice','sorted','staticmethod','str','sum','super','tuple','type','vars','zip']

bins2,bins3 = [],[]
for bi in bins: bins2.append(' ' + bi + '(')  #look for leading space 
then builtin then open paren


#todo use for source files other than .py
ccomments = 0
py_comment = ['#','~','@']
c_comment  = ['/*','//']

#read file
f = open(sys.argv[1], encoding='utf-8')
lines = f.read().splitlines()
f.close()

#print builtin usage count
#def binusage():

#iterate file
linenbr = 0
for line in lines:
line = line.strip()
linenbr += 1

if line == ''   : blanks += 1
if line != '':
if line[0:1]  == '#': comments += 1
if line[0:3]  == '"""'  : comments += 1
if line[-3:1] == '"""'   : comments += 1

if line[0:1] not in ['#','"']:
source += 1
if line[0:3] == 'def' and line[-2:] == '):'  : 
functions += 1
if '.execute' in line   : dbexec += 1
if 'commit()' in line   : dbexec += 1
if 'import' in line : imports += 1
if 'print(' in line : bins3.append('print')
for bi in bins2:#usage of a python builtin 
function
if bi in line:
bins3.append(bi[1:-1])  
total += 1  

#output 
print('imports   : ' + str(imports))
print('source: ' + str(source))
print('-functions: ' + str(functions))
print('-db exec  : ' + str(dbexec) + 'x')
ctxt = ''
x = [(i,bins3.count(i)) for i in sorted(set(bins3))]
for bi,cnt in x: ctxt += bi + '('+ str(cnt) + '), '
print('-builtins : ' + str(len(bins3)) + 'x [' + ctxt[:-2] + ']')
print('comments  : ' + str(comments))
print('blanks: ' + str(blanks))
print('Total : ' + str(total))
-
--
https://mail.python.org/mailman/listinfo/python-list