Re: Dataclasses, immutability(?), and ChatGPT

2023-04-12 Thread Roel Schroeven

Op 12/04/2023 om 6:58 schreef dn via Python-list:

Are dataclasses (or instances thereof) mutable or immutable?
- and in what sense?
Instances of dataclasses are mutable, just like normal classes. 
Dataclasses *are* normal classes, with some extra special methods. They 
are totally different from namedtuples, even though the use cases 
somewhat overlap. They *can* be immutable, I think, if the programmer 
takes care to make them so. I don't think adding __hash__() is enough: 
as I understand it's an indication that a class is immutable, but 
doesn't actually by itself make it so. "Mutability is a complicated 
property that depends on the programmer’s intent, the existence and 
behavior of |__eq__()|, and the values of the |eq| and |frozen| flags in 
the |dataclass()| 
 
decorator.", says the documentation.

Amongst the four benefits ChatGPT listed was:
«
Immutable instances: By default, instances of dataclasses are 
immutable, which means that once created, their attributes cannot be 
modified. This can help to prevent unintended modifications to the data.

»

Huh? If we'd been discussing namedtuples over (say) dictionaries, I'd 
perhaps have accepted the reply.

ChatGPT is wrong.

Anything I've 'missed'?
- or a salutary tale of not depending upon ChatGPT etc?
You didn't miss anything, ChatGPT is wrong. The thing to look out for is 
that when ChatGPT is wrong, it sounds just as convincing as when it's 
right; there is no indication in it's tone or style that it's making 
things up. Always double check!


--
"A common mistake that people make when trying to design something completely
foolproof is to underestimate the ingenuity of complete fools."
-- Douglas Adams
--
https://mail.python.org/mailman/listinfo/python-list


Re: Christoph Gohlke and compiled packages

2023-04-12 Thread Mike Dewhirst

Well thank you Christoph Gohlke and thank you Ian Bicking and colleagues.

I just used pip to nakedly install psycopg2 and Pillow without a hitch. 
My distrust of Windows has kept me going back to Christoff's well for 
years.


Maybe it is time to assume innocence unless proven guilty ;-)

Thanks to all who showed me the way.

Cheers

Mike

On 11/04/2023 11:39 pm, Thomas Passin wrote:

On 4/11/2023 6:58 AM, Chris Angelico wrote:
On Tue, 11 Apr 2023 at 20:15, Jim Schwartz  
wrote:


What’s the problem now?  Is it with python on windows?  I use python 
on windows so I’d like to know. Thanks




Python itself is fine, but a lot of third-party packages are hard to
obtain. So if you need numpy, for instance, or psycopg2, you might
need to find an alternative source.


I've noticed a big change in the last few years in that PyPi has many, 
many amd-64 packages than it used to in the heyday of Christoph 
Gohlke's efforts. I haven't needed to go there for some time whereas I 
used to need to all the time.  So if I "need numpy, for instance, or 
psycopg2" for Windows, I get them from PyPi.


Yes, I know that some projects haven't caught up to Python 3.11x yet. 
And I'm glad I haven't needed to create a binary wheel for Windows 
myself.  But the situation is way better than it used to be.  I've had 
more trouble with Python and Python packages on Linux than on Windows.





--
Signed email is an absolute defence against phishing. This email has
been signed with my private key. If you import my public key you can
automatically decrypt my signature and be sure it came from me. Your
email software can handle signing.



OpenPGP_signature
Description: OpenPGP digital signature
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Dataclasses, immutability(?), and ChatGPT

2023-04-12 Thread Grant Edwards
On 2023-04-12, Roel Schroeven  wrote:

>> Huh? If we'd been discussing namedtuples over (say) dictionaries, I'd 
>> perhaps have accepted the reply.
>
> ChatGPT is wrong.
>
>> Anything I've 'missed'?
>> - or a salutary tale of not depending upon ChatGPT etc?

> You didn't miss anything, ChatGPT is wrong. The thing to look out for is 
> that when ChatGPT is wrong, it sounds just as convincing as when it's 
> right; there is no indication in it's tone or style that it's making 
> things up.

Yep, that's how ChatGPT works. It's a program to generate output
language that sounds right based on a huge training set of
text. Whether that "right sounding" language agrees with real world
facts or not is irrelevent to the language-generating algorithm.

--
Grant


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


Re: Dataclasses, immutability(?), and ChatGPT

2023-04-12 Thread Thomas Passin

On 4/12/2023 12:58 AM, dn via Python-list wrote:

Are dataclasses (or instances thereof) mutable or immutable?
- and in what sense?


Have been experimenting with ChatGPT. In particular: its possibilities 
as a trainer, good ideas for methods of introducing new topics, its 
capability for drawing-up demonstrations or examples, its interpretation 
of assessment questions (ie evaluating my own work, eg do they test 
desired specifics, is it possible/likely to misinterpret the question, ...)



Conversed with ChatGPT about the differences between (standard) 
custom-classes and dataclasses, and when one might prefer one over the 
other.


We(?) started discussing how dataclasses might be introduced to trainees 
currently only familiar with Python's built-ins: "...how they are 
superior to using built-in data-constructs..."


Amongst the four benefits ChatGPT listed was:
«
Immutable instances: By default, instances of dataclasses are immutable, 
which means that once created, their attributes cannot be modified. This 
can help to prevent unintended modifications to the data.

»

Huh? If we'd been discussing namedtuples over (say) dictionaries, I'd 
perhaps have accepted the reply.



The next step was to write some code to double-check my understanding 
(reproduced below). No change there.

(given that I'm perfect...cough, cough, splutter)


Thus, back to ChatGPT to seek clarification:
«
You said "Immutable instances: By default, instances of dataclasses are 
immutable, which means that once created, their attributes cannot be 
modified. This can help to prevent unintended modifications to the 
data." The attribute-values within a data-class can be changed. In what 
way are Python dataclasses immutable?

»

ChatGPT did indeed clarify that:
«
You're correct that the attribute values within a dataclass can be 
changed, even though the instance itself is considered immutable.

»

That's better. The machine is as smart as I am - or I, as smart as it - 
or something(?)



However, the supporting-explanation then appears to argue against its 
own clarification (and the assertion in the question):

«
So to clarify, when we say that instances of dataclasses are immutable, 
we mean that the attributes of an instance cannot be changed after it is 
created.


In other words, if you create an instance of a dataclass, its attributes 
cannot be modified by any external code. If you want to change the value 
of an attribute, you need to create a new instance of the dataclass with 
the updated attribute value.


... [code excised - see below]

This is because the instance is considered immutable, and its attributes 
cannot be changed directly. Instead, we need to create a new instance of 
the dataclass with the updated attribute value, like this...


Now, new_person is a new instance of the Person dataclass with the 
updated attribute values, while the original person instance remains 
unchanged.


So to summarize, while the attribute values within a dataclass can be 
changed, instances of dataclasses are considered immutable because their 
attributes cannot be modified directly once they are created. Any 
updates to the attributes require the creation of a new instance of the 
dataclass.

»

[Note]
In and amongst the above explanatory-paragraphs it gives example 
code-snippets. Those are condensed into:


 >>> from dataclasses import dataclass
 >>>
 >>> @dataclass
... class Person:
... name: str
... age: int
...
 >>> person = Person(name='Alice', age=20)
 >>>
 >>> person.name = 'Bob'  # raises AttributeError: can't set attribute
 >>> person.age = 21  # raises AttributeError: can't set attribute

- note the erroneous comments about exceptions being raised
(they weren't/aren't)!


Here's a home-grown version illustrating all the points made during the 
investigation, by way of proof/disproof:


""" PythonTraining:dataclass.py
     Prove/disprove claim made by Chat-GPT.
"""

__author__ = "dn, IT&T Consultant"
__python__ = "3.11"
__created__ = "PyCharm, 12 Apr 2023"
__copyright__ = "Copyright © 2023~"
__license__ = "MIT"

# PSL
from dataclasses import dataclass


@dataclass
class Coordinates():
     """Sample dataclass. """
     x:int
     y:int


if __name__ == "__main__":
     print( "\nCommencing execution\n" )

     coordinates = Coordinates( 1, 2, )
     print( coordinates, id( coordinates ), )
     coordinates.x = 3
     print( coordinates, id( coordinates ), )
     coordinates.z = 4
     print( coordinates, id( coordinates ), )
     print( coordinates.x, coordinates.y, coordinates.z, )


### output:
Commencing execution

Coordinates(x=1, y=2) 140436963150928
Coordinates(x=3, y=2) 140436963150928
Coordinates(x=3, y=2) 140436963150928
3 2 4

Terminating
###

Not only are a dataclass instance's attribute-values mutable, but 
further attributes can be dynamically-added to the object-instance!


Yes, if the code included:

coordinates = Coordinates( 5, 6, )

the new "coordinates" identifier would point to a differe

Re: Christoph Gohlke and compiled packages

2023-04-12 Thread Mike Dewhirst

Sadly Windows is still in the dock. The jury is still out.

Turns out the "without a hitch" was based on cached wheels.

I'm going to start from scratch with new projects using Pythons 3.8, 
3.10 and 3.11 and report back.


Cheers

Mike

On 12/04/2023 6:13 pm, Mike Dewhirst wrote:

Well thank you Christoph Gohlke and thank you Ian Bicking and colleagues.

I just used pip to nakedly install psycopg2 and Pillow without a 
hitch. My distrust of Windows has kept me going back to Christoff's 
well for years.


Maybe it is time to assume innocence unless proven guilty ;-)

Thanks to all who showed me the way.

Cheers

Mike

On 11/04/2023 11:39 pm, Thomas Passin wrote:

On 4/11/2023 6:58 AM, Chris Angelico wrote:
On Tue, 11 Apr 2023 at 20:15, Jim Schwartz  
wrote:


What’s the problem now?  Is it with python on windows?  I use 
python on windows so I’d like to know. Thanks




Python itself is fine, but a lot of third-party packages are hard to
obtain. So if you need numpy, for instance, or psycopg2, you might
need to find an alternative source.


I've noticed a big change in the last few years in that PyPi has 
many, many amd-64 packages than it used to in the heyday of Christoph 
Gohlke's efforts. I haven't needed to go there for some time whereas 
I used to need to all the time.  So if I "need numpy, for instance, 
or psycopg2" for Windows, I get them from PyPi.


Yes, I know that some projects haven't caught up to Python 3.11x yet. 
And I'm glad I haven't needed to create a binary wheel for Windows 
myself.  But the situation is way better than it used to be.  I've 
had more trouble with Python and Python packages on Linux than on 
Windows.









--
Signed email is an absolute defence against phishing. This email has
been signed with my private key. If you import my public key you can
automatically decrypt my signature and be sure it came from me. Your
email software can handle signing.



OpenPGP_signature
Description: OpenPGP digital signature
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Christoph Gohlke and compiled packages

2023-04-12 Thread Thomas Passin

On 4/12/2023 8:59 AM, Mike Dewhirst wrote:

Sadly Windows is still in the dock. The jury is still out.

Turns out the "without a hitch" was based on cached wheels.

I'm going to start from scratch with new projects using Pythons 3.8, 
3.10 and 3.11 and report back.


Sorry for the length to come, but here's what I've got so far - on 
Windows, python 3.11 - all pip-installed.  Note especially numpy, scipy, 
statsmodels, mysql-connector-python, scikit-learn -


C:\Users\tom>py -V
Python 3.11.3

C:\Users\tom>py -m pip list
Package   Version
- ---
accessible-pygments   0.0.4
alabaster 0.7.13
argcomplete   3.0.5
asciidoc  10.2.0
asciidoc3 3.2.3
astroid   2.15.2
asttokens 2.2.1
async-generator   1.10
attrs 22.2.0
Babel 2.12.1
beautifulsoup44.12.1
black 23.3.0
bleach6.0.0
bokeh 2.4.3
build 0.10.0
certifi   2022.12.7
cffi  1.15.1
cftime1.6.2
charset-normalizer3.1.0
click 8.1.3
colorama  0.4.6
colorcet  3.0.1
contourpy 1.0.7
csaps 1.1.0
cycler0.11.0
datatable 1.1.0a0+pr3440.2228
defusedxml0.7.1
dialite   0.5.3
dill  0.3.6
docutils  0.19
exceptiongroup1.1.1
fastjsonschema2.16.3
fire  0.5.0
flexx 0.8.4
fonttools 4.39.3
frechetdist   0.6
GenDoc1.0.1
ghp-import2.1.0
h11   0.14.0
holoviews 1.15.4
idna  3.4
imageio   2.27.0
imagesize 1.4.1
importlib-metadata6.1.0
iniconfig 2.0.0
isort 5.12.0
jaraco.classes3.2.3
jill  0.11.3
Jinja23.1.2
joblib1.2.0
jsonschema4.17.3
jupyter_client8.1.0
jupyter_core  5.3.0
jupyterlab-pygments   0.2.2
karma-sphinx-theme0.0.8
keyring   23.13.1
kiwisolver1.4.4
lazy_loader   0.2
lazy-object-proxy 1.9.0
leo   6.7.2
linkify-it-py 2.0.0
localreg  0.5.0
lxml  4.9.2
lz4   4.3.2
Markdown  3.3.7
markdown-it-py2.2.0
MarkupSafe2.1.2
matplotlib3.6.3
mccabe0.7.0
mdit-py-plugins   0.3.5
mdurl 0.1.2
mergedeep 1.3.4
meta  1.0.2
mistune   2.0.5
mizani0.8.1
mkdocs1.4.2
mkdocs-exclude1.0.2
more-itertools9.1.0
mpmath1.3.0
multidict 6.0.4
mypy  1.2.0
mypy-extensions   1.0.0
mysql-connector-python8.0.32
mysqlclient   2.1.1
nbclient  0.7.3
nbconvert 7.3.0
nbformat  5.8.0
nest-asyncio  1.5.6
netCDF4   1.6.3
networkx  3.1
nltk  3.8.1
numpy 1.24.2
outcome   1.2.0
packaging 23.0
palettable3.3.1
pandas2.0.0
pandoc2.3
pandocfilters 1.5.0
panel 0.14.4
param 1.13.0
pathspec  0.11.1
patsy 0.5.3
pep5170.13.0
Pillow9.5.0
pip   23.0.1
pipx  1.2.0
pkginfo   1.9.6
platformdirs  3.2.0
plotly5.14.1
plotnine  0.10.1
pluggy1.0.0
plumbum   1.8.1
ply   3.11
progressbar2  4.2.0
protobuf  4.22.1
pscript   0.7.7
pwlf  2.2.1
pycodestyle   2.10.0
pycparser 2.21
pyct  0.5.0
pydata-sphinx-theme   

Weak Type Ability for Python

2023-04-12 Thread Ali Mohseni Roodbari
Hi all,
Please make this command for Python (if possible):

>>> x=1
>>> y='a'
>>> wprint (x+y)
>>> 1a

In fact make a new type of print command which can print and show strings
and integers together.

Sincerely yours,
Ali.
-- 
https://mail.python.org/mailman/listinfo/python-list


DIPY Workshop 2023 now to be held online! April 24-28.

2023-04-12 Thread Eleftherios Garyfallidis
Dear all,

Due to unexpected events we have had to make the decision to
transition our workshop
to a virtual format.
While this change was unexpected, we are well-prepared due to our previous
experience with our own online platform. Rest assured, we are fully
equipped to ensure that the virtual workshop will run smoothly.

It's worth noting that all talks this year will be conducted live, as
opposed to pre-recorded. So now we are offering the following updated and
flexible registration
options:

Silver : Starts from $200

   1.

   Listen to the talks live. Learn from the experts.
   2.

   3 days workshop, get the basic kit to strive in the diffusion imaging
   world.
   3.

   Ability to upgrade during the workshop.


Gold :  Starts from $500

Everything in Silver plus:

   1.

   Ability to attend study groups and to present your work.
   2.

   Full 5 days workshop.
   3.

   Certificate of attendance (Linkedin verifiable).


Platinum : Starts from $995

Everything in Gold plus:

   1.

   Provides additional preset hourly meetings with the DIPY developers
   beyond the workshop's duration. These will be 1 to 1 meetings to set up or
   improve your pipeline for your needs. Maximum 6 meetings. Each meeting will
   be 1 hour long.
   2.

   Provides access to the talks and all materials after the workshop.
   3.

   Ability to move to yearly long support.


Register now !

In summary, the workshop offers:


   -

   Hands-on tutorials - Every single day !!!
   -

   Guided practice sessions (bring your data)
   -

   Personalized certificates of attendance
   -

   Effective networking opportunities with one-to-one follow ups
   -

   Comprehensive explanation of theoretical foundations with practical
   examples
   -

   Access to latest and established methods with code and interfaces
   -

   Pointers to move beyond the current challenges and navigate hard to do
   analyses
   -

   Multiple clinical use cases (AZ, Parkinson’s, Stroke, etc.)


This year there is a higher level of focus in AI and ML. These technologies
have been transforming various industries, and now they are revolutionizing
medical imaging. By harnessing the power of advanced algorithms and vast
data sets, we have successfully integrated machine learning into our
imaging solutions, providing unparalleled accuracy and efficiency.


For those of you who are new to this. DIPY is an open source
software project
used for processing structural and diffusion imaging data. Join us for an
exciting in person workshop hosted online April 24-28.
https://dipy.org/workshops/latest

Our team of expert instructors will guide you through the fundamentals of
diffusion theory, data pre-processing, fiber tracking, and much more.
You'll have the opportunity to learn from industry-leading professionals,
ask questions, and network with like-minded peers.

Register today to secure your spot in this highly anticipated event. Now
online!!

https://dipy.org/workshops/dipy-workshop-2023#Registration


Happy to answer any questions you may have.

Thank you!,

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


for a 'good python'

2023-04-12 Thread jak

Hi everyone,
some time ago I wrote a class to determine if an ipv4 address belonged
to a subnet. Seldom using python I'm pretty sure it's not written in
'good python' nor too portable. Could you give me some advice to make it
better?

class calcip:
def __init__(self, psubnet: str):
ssubnet, scidr = psubnet.replace(' ', '').split('/')
subnet = int.from_bytes(tuple(
  map(lambda n: (int(n)), 
ssubnet.split('.'))),

'big')
cidr = int(scidr)
mask = ((2 ** cidr) - 1) << (32 - cidr)
self.__network = subnet & mask
self.__wildcard = ~mask & 0x
self.__broadcast = (subnet | self.__wildcard) & 0x
self.__tsubnet = tuple(subnet.to_bytes(4, 'big'))
self.__tnetwork = tuple(self.__network.to_bytes(4, 'big'))
self.__tbroadcast = tuple(self.__broadcast.to_bytes(4, 'big'))
self.__tmask = tuple(mask.to_bytes(4, 'big'))
self.__twildcard = tuple(self.__wildcard.to_bytes(4, 'big'))
self.__host_min = tuple((self.__network + 1).to_bytes(4, 'big'))
self.__host_max = tuple((self.__broadcast - 1).to_bytes(4, 'big'))

@staticmethod
def __to_str(val: tuple):
return '.'.join(str(v) for v in val)

@property
def subnet(self):
return self.__to_str(self.__tsubnet)

@property
def network(self):
return self.__to_str(self.__tnetwork)

@property
def broadcast(self):
return self.__to_str(self.__tbroadcast)

@property
def mask(self):
return self.__to_str(self.__tmask)

@property
def wildcard(self):
return self.__to_str(self.__twildcard)

@property
def host_min(self):
return self.__to_str(self.__host_min)

@property
def host_max(self):
return self.__to_str(self.__host_max)

@property
def hosts_num(self):
return self.__wildcard - 1

@property
def net_class(self):
tst = (self.__tnetwork[0] & 0xf0) >> 4
if (tst & 0x8) == 0:
clx = 'A'
elif (tst & 0xc) == 0x8:
clx = 'B'
elif (tst & 0xe) == 0xc:
clx = 'C'
elif (tst & 0xf) == 0xe:
clx = 'D'
elif (tst & 0xf) == 0xf:
clx = 'E'
return clx

def __contains__(self, item):
ret = True
row_hdr = None
try:
row_hdr = int.from_bytes(tuple(map(lambda n: (int(n)), 
item.split('.'))), 'big')

except:
ret = False
if ret:
if not self.__network < row_hdr < self.__broadcast:
ret = False
return ret


def main():
sn = calcip('10.0.0.0/26')

print(f"subnet: {sn.subnet}")
print(f"network: {sn.network}")
print(f"broadcast: {sn.broadcast}")
print(f"mask: {sn.mask}")
print(f"wildcard: {sn.wildcard}")
print(f"host_min: {sn.host_min}")
print(f"host_max: {sn.host_max}")
print(f"Avaible hosts: {sn.hosts_num}")
print(f"Class: {sn.net_class}")

tst_hdr = '10.0.0.31'
is_not = 'is '
if not tst_hdr in sn:
is_not = 'is NOT '
print("hdr %s %sin range %s - %s" %
  (tst_hdr, is_not, sn.host_min, sn.host_max))

if __name__ == '__main__':
main()
--
https://mail.python.org/mailman/listinfo/python-list


Post Degree in Machine Learning | Job position at CMCC Foundation, Italy

2023-04-12 Thread info cmcc
*POST-DEGREE IN MACHINE LEARNING*
[Job Opening Code: 12404]
*Lecce (Italy) - Deadline: 15/04/2023*


Our Division of Advanced Scientific Computing (ASC Division) is considering
the possibility to hire a talented and proactive Post Degree candidate to
support CMCC research activities. The contract will be jointly funded by
CMCC and the HPC Training and Research for Earth Sciences (HPC-TRES)
program.



The job location is CMCC Headquarters in Lecce, Italy.



We are looking for a motivated person with the following requirements:

   - M.Sc. degree in Computer Science or Computer Engineering or equivalent
   fields;
   - 2+ years’ experience in scientific software development;
   - Excellent knowledge of Python programming language;
   - Good knowledge of Python scientific (numpy, scipy, scikit-learn,
   pandas) and visualization (e.g., matplotlib) libraries;
   - Good theoretical knowledge of Machine Learning algorithms and
   techniques for regression and classification tasks;
   - Good knowledge of at least one Machine/Deep Learning framework (e.g.,
   TensorFlow, Keras, Pytorch);
   - Good capabilities in writing technical reports and scientific papers
   as well as documenting code;
   - Good knowledge of both written and spoken English language.

Additional preferred experience:

   - Experience with HPC systems
   - Experience in training ML models in distributed environments and
   corresponding strategies

Belonging to legally protected categories (ex L. 68/99) will constitute a
preferential condition.


*More details and info about HOW TO APPLY:*
https://cmccfoundation.applytojob.com/apply/c4A2a92Co7/12404-POST-DEGREEMachine-Learning-Skills?source=Our%20Career%20Page%20Widget
--

Fondazione CMCCCentro Euro-Mediterraneo sui Cambiamenti Climatici
Via Marco Biagi, 5 - 73100 Lecce
[email protected] - www.cmcc.it
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: for a 'good python'

2023-04-12 Thread jak

Stefan Ram ha scritto:

jak  writes:

@property
def subnet(self):
return self.__to_str(self.__tsubnet)


   Maybe each of those attributes should be an object of a
   special class where your "__to_str" is "__str__"? E.g.,

# code in "calcip.__init__"
self.tsubnet = ip_address_class.from_int( subnet )

   where "ip_address_class" is as in:

import collections
import random

class ip_address_class( collections.UserList ):
 def __init__( self, bytes_address ):
 super().__init__( bytes_address )
 @classmethod
 def from_int( cls, int_address ):
 return cls( int_address.to_bytes( 4, 'big' ))
 def __str__( self ):
 return '.'.join( str( byte_ )for byte_ in self.data )

if __name__ == '__main__':
 ip_address = \
 ip_address_class.from_int( random.randint( 0, 4294967295 ))
 print( ip_address[ 0 ])
 print( ip_address )

   . Now the client can access each byte individually and also
   get a "nice" string representation.

   (You may add more "from_..." methods for all the various
   formats you create addresses from.)

   But you should also research the standard library to see
   if something like this doesn't already exist ready-made
   specifically for IP addresses in the standard library.



ok. thanks a lot. now i try to do that.


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


Re: Weak Type Ability for Python

2023-04-12 Thread Chris Angelico
On Thu, 13 Apr 2023 at 03:05, Ali Mohseni Roodbari
 wrote:
>
> Hi all,
> Please make this command for Python (if possible):
>
> >>> x=1
> >>> y='a'
> >>> wprint (x+y)
> >>> 1a
>
> In fact make a new type of print command which can print and show strings
> and integers together.
>

Try:

print(x, y)

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


Re: Weak Type Ability for Python

2023-04-12 Thread Mats Wichmann

On 4/12/23 11:11, Chris Angelico wrote:

On Thu, 13 Apr 2023 at 03:05, Ali Mohseni Roodbari
 wrote:


Hi all,
Please make this command for Python (if possible):


x=1
y='a'
wprint (x+y)
1a


In fact make a new type of print command which can print and show strings
and integers together.



Try:

print(x, y)

ChrisA



To continue on, what do you want "addition" of dissimilar types to do - 
since that's what you have asked for above.


You can write yourself an object which is happy with certain 
combinations, so you don't have this scenario:


>>> x + y
Traceback (most recent call last):
  File "", line 1, in 
x + y
 ~~^~~
TypeError: can only concatenate str (not "int") to str
>>> y + x
Traceback (most recent call last):
  File "", line 1, in 
y + x
 ~~^~~
TypeError: unsupported operand type(s) for +: 'int' and 'str'
>>>


Or you can help out the print function by doing some of the fiddling 
yourself:


>>> print(f"{x}{y}")
1a




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


Re: Weak Type Ability for Python

2023-04-12 Thread Thomas Passin

On 4/12/2023 1:11 PM, Chris Angelico wrote:

On Thu, 13 Apr 2023 at 03:05, Ali Mohseni Roodbari
 wrote:


Hi all,
Please make this command for Python (if possible):


x=1
y='a'
wprint (x+y)
1a


In fact make a new type of print command which can print and show strings
and integers together.



Try:

print(x, y)

ChrisA


It puts a space between "1" and "a", whereas the question does not want 
the space.  print(f'{x}{y}') would do it, but only works for variables 
named "x" and "y".


As happens so often, the OP has not specified what he actually wants to 
do so we can only answer the very specific question.


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


Re: Weak Type Ability for Python

2023-04-12 Thread MRAB

On 2023-04-12 19:57, Mats Wichmann wrote:

On 4/12/23 11:11, Chris Angelico wrote:

On Thu, 13 Apr 2023 at 03:05, Ali Mohseni Roodbari
 wrote:


Hi all,
Please make this command for Python (if possible):


x=1
y='a'
wprint (x+y)
1a


In fact make a new type of print command which can print and show strings
and integers together.



Try:

print(x, y)

ChrisA



To continue on, what do you want "addition" of dissimilar types to do -
since that's what you have asked for above.

You can write yourself an object which is happy with certain
combinations, so you don't have this scenario:

  >>> x + y
Traceback (most recent call last):
File "", line 1, in 
  x + y
   ~~^~~
TypeError: can only concatenate str (not "int") to str
  >>> y + x
Traceback (most recent call last):
File "", line 1, in 
  y + x
   ~~^~~
TypeError: unsupported operand type(s) for +: 'int' and 'str'
  >>>


Or you can help out the print function by doing some of the fiddling
yourself:

  >>> print(f"{x}{y}")
1a


Or:


print(x, y, sep='')

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


Re: Weak Type Ability for Python

2023-04-12 Thread Grant Edwards
On 2023-04-12, Ali Mohseni Roodbari  wrote:
> Hi all,
> Please make this command for Python (if possible):
>
 x=1
 y='a'
 wprint (x+y)
 1a

If that's what you want, use PHP or some other language. Don't try to ruin 
Python.

> In fact make a new type of print command which can print and show strings
> and integers together.


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


Re: Weak Type Ability for Python

2023-04-12 Thread 2QdxY4RzWzUUiLuE
On 2023-04-12 at 14:51:44 -0400,
Thomas Passin  wrote:

> On 4/12/2023 1:11 PM, Chris Angelico wrote:
> > On Thu, 13 Apr 2023 at 03:05, Ali Mohseni Roodbari
> >  wrote:
> > > 
> > > Hi all,
> > > Please make this command for Python (if possible):
> > > 
> > > > > > x=1
> > > > > > y='a'
> > > > > > wprint (x+y)
> > > > > > 1a
> > > 
> > > In fact make a new type of print command which can print and show strings
> > > and integers together.
> > > 
> > 
> > Try:
> > 
> > print(x, y)
> > 
> > ChrisA
> 
> It puts a space between "1" and "a", whereas the question does not want the
> space.  print(f'{x}{y}') would do it, but only works for variables named "x"
> and "y".

Or possibly print(x, y, sep='').

> As happens so often, the OP has not specified what he actually wants to do
> so we can only answer the very specific question.

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


Re: for a 'good python'

2023-04-12 Thread Barry



> On 12 Apr 2023, at 18:10, jak  wrote:
> Hi everyone,
> some time ago I wrote a class to determine if an ipv4 address belonged
> to a subnet. Seldom using python I'm pretty sure it's not written in
> 'good python' nor too portable. Could you give me some advice to make it
> better?
> 
> class calcip:
>def __init__(self, psubnet: str):
>ssubnet, scidr = psubnet.replace(' ', '').split('/')
>subnet = int.from_bytes(tuple(
>  map(lambda n: (int(n)), ssubnet.split('.'))),
>'big')
>cidr = int(scidr)
>mask = ((2 ** cidr) - 1) << (32 - cidr)
>self.__network = subnet & mask
>self.__wildcard = ~mask & 0x
>self.__broadcast = (subnet | self.__wildcard) & 0x
>self.__tsubnet = tuple(subnet.to_bytes(4, 'big'))
>self.__tnetwork = tuple(self.__network.to_bytes(4, 'big'))
>self.__tbroadcast = tuple(self.__broadcast.to_bytes(4, 'big'))
>self.__tmask = tuple(mask.to_bytes(4, 'big'))
>self.__twildcard = tuple(self.__wildcard.to_bytes(4, 'big'))
>self.__host_min = tuple((self.__network + 1).to_bytes(4, 'big'))
>self.__host_max = tuple((self.__broadcast - 1).to_bytes(4, 'big'))
> 
>@staticmethod
>def __to_str(val: tuple):
>return '.'.join(str(v) for v in val)
> 
>@property
>def subnet(self):
>return self.__to_str(self.__tsubnet)
> 
>@property
>def network(self):
>return self.__to_str(self.__tnetwork)
> 
>@property
>def broadcast(self):
>return self.__to_str(self.__tbroadcast)
> 
>@property
>def mask(self):
>return self.__to_str(self.__tmask)
> 
>@property
>def wildcard(self):
>return self.__to_str(self.__twildcard)
> 
>@property
>def host_min(self):
>return self.__to_str(self.__host_min)
> 
>@property
>def host_max(self):
>return self.__to_str(self.__host_max)
> 
>@property
>def hosts_num(self):
>return self.__wildcard - 1
> 
>@property
>def net_class(self):
>tst = (self.__tnetwork[0] & 0xf0) >> 4
>if (tst & 0x8) == 0:
>clx = 'A'
>elif (tst & 0xc) == 0x8:
>clx = 'B'
>elif (tst & 0xe) == 0xc:
>clx = 'C'
>elif (tst & 0xf) == 0xe:
>clx = 'D'
>elif (tst & 0xf) == 0xf:
>clx = 'E'
>return clx
> 
>def __contains__(self, item):
>ret = True
>row_hdr = None
>try:
>row_hdr = int.from_bytes(tuple(map(lambda n: (int(n)), 
> item.split('.'))), 'big')
>except:
>ret = False
>if ret:
>if not self.__network < row_hdr < self.__broadcast:
>ret = False
>return ret
> 
> 
> def main():
>sn = calcip('10.0.0.0/26')
> 
>print(f"subnet: {sn.subnet}")
>print(f"network: {sn.network}")
>print(f"broadcast: {sn.broadcast}")
>print(f"mask: {sn.mask}")
>print(f"wildcard: {sn.wildcard}")
>print(f"host_min: {sn.host_min}")
>print(f"host_max: {sn.host_max}")
>print(f"Avaible hosts: {sn.hosts_num}")
>print(f"Class: {sn.net_class}")
> 
>tst_hdr = '10.0.0.31'
>is_not = 'is '
>if not tst_hdr in sn:
>is_not = 'is NOT '
>print("hdr %s %sin range %s - %s" %
>  (tst_hdr, is_not, sn.host_min, sn.host_max))
> 
> if __name__ == '__main__':
>main()

There is this https://docs.python.org/3/howto/ipaddress.html if you just want a 
solution.

Or are you after code review feedback?

Barry

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


Re: for a 'good python'

2023-04-12 Thread jak

Barry ha scritto:





On 12 Apr 2023, at 18:10, jak  wrote:
Hi everyone,
some time ago I wrote a class to determine if an ipv4 address belonged
to a subnet. Seldom using python I'm pretty sure it's not written in
'good python' nor too portable. Could you give me some advice to make it
better?

class calcip:
def __init__(self, psubnet: str):
ssubnet, scidr = psubnet.replace(' ', '').split('/')
subnet = int.from_bytes(tuple(
  map(lambda n: (int(n)), ssubnet.split('.'))),
'big')
cidr = int(scidr)
mask = ((2 ** cidr) - 1) << (32 - cidr)
self.__network = subnet & mask
self.__wildcard = ~mask & 0x
self.__broadcast = (subnet | self.__wildcard) & 0x
self.__tsubnet = tuple(subnet.to_bytes(4, 'big'))
self.__tnetwork = tuple(self.__network.to_bytes(4, 'big'))
self.__tbroadcast = tuple(self.__broadcast.to_bytes(4, 'big'))
self.__tmask = tuple(mask.to_bytes(4, 'big'))
self.__twildcard = tuple(self.__wildcard.to_bytes(4, 'big'))
self.__host_min = tuple((self.__network + 1).to_bytes(4, 'big'))
self.__host_max = tuple((self.__broadcast - 1).to_bytes(4, 'big'))

@staticmethod
def __to_str(val: tuple):
return '.'.join(str(v) for v in val)

@property
def subnet(self):
return self.__to_str(self.__tsubnet)

@property
def network(self):
return self.__to_str(self.__tnetwork)

@property
def broadcast(self):
return self.__to_str(self.__tbroadcast)

@property
def mask(self):
return self.__to_str(self.__tmask)

@property
def wildcard(self):
return self.__to_str(self.__twildcard)

@property
def host_min(self):
return self.__to_str(self.__host_min)

@property
def host_max(self):
return self.__to_str(self.__host_max)

@property
def hosts_num(self):
return self.__wildcard - 1

@property
def net_class(self):
tst = (self.__tnetwork[0] & 0xf0) >> 4
if (tst & 0x8) == 0:
clx = 'A'
elif (tst & 0xc) == 0x8:
clx = 'B'
elif (tst & 0xe) == 0xc:
clx = 'C'
elif (tst & 0xf) == 0xe:
clx = 'D'
elif (tst & 0xf) == 0xf:
clx = 'E'
return clx

def __contains__(self, item):
ret = True
row_hdr = None
try:
row_hdr = int.from_bytes(tuple(map(lambda n: (int(n)), 
item.split('.'))), 'big')
except:
ret = False
if ret:
if not self.__network < row_hdr < self.__broadcast:
ret = False
return ret


def main():
sn = calcip('10.0.0.0/26')

print(f"subnet: {sn.subnet}")
print(f"network: {sn.network}")
print(f"broadcast: {sn.broadcast}")
print(f"mask: {sn.mask}")
print(f"wildcard: {sn.wildcard}")
print(f"host_min: {sn.host_min}")
print(f"host_max: {sn.host_max}")
print(f"Avaible hosts: {sn.hosts_num}")
print(f"Class: {sn.net_class}")

tst_hdr = '10.0.0.31'
is_not = 'is '
if not tst_hdr in sn:
is_not = 'is NOT '
print("hdr %s %sin range %s - %s" %
  (tst_hdr, is_not, sn.host_min, sn.host_max))

if __name__ == '__main__':
main()


There is this https://docs.python.org/3/howto/ipaddress.html if you just want a 
solution.

Or are you after code review feedback?

Barry


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



Thank you too. I had seen this library but I always try not to use
libraries outside the standard ones. Now I don't remember why I was
convinced that this wasn't part of it, perhaps because it was like that
at the time or because I got confused. Only now I realized that it is
not necessary to install it. Now I'm considering whether to use
'ipaddress' or 'socket'. What is certain is that this one you have
suggested is really comfortable. Thanks again for the report.

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


Re: Christoph Gohlke and compiled packages

2023-04-12 Thread Mike Dewhirst

On 12/04/2023 10:59 pm, Mike Dewhirst wrote:

Sadly Windows is still in the dock. The jury is still out.

Turns out the "without a hitch" was based on cached wheels.

I'm going to start from scratch with new projects using Pythons 3.8, 
3.10 and 3.11 and report back.


Report summary:

pip install works well with Python 3.8 and 3.10 (and presumably 3.9) but 
3.11 fails.


Report conclusion:

As indicated in this thread, pip cannot find Python 3.11 wheels and 
therefore needs to compile from source. It is looking for Microsoft's 
C++ compiler version 14.


I'll (gulp) attempt to swallow the Koolaid.

See error below ...

Cheers

Mike

(xreq) D:\Users\mike\envs\xreq>pip install -r requirements\dev.txt

...

Collecting psycopg2==2.9.3

  Downloading psycopg2-2.9.3.tar.gz (380 kB)

 --- 380.6/380.6 kB 6.0 MB/s eta 0:00:00

  Preparing metadata (setup.py) ... done

Collecting Pillow==9.1.1

  Downloading Pillow-9.1.1.tar.gz (49.8 MB)

  49.8/49.8 MB 4.5 MB/s eta 0:00:00

  Preparing metadata (setup.py) ... done

...

Installing collected packages: psycopg2, Pillow, ...

  DEPRECATION: psycopg2 is being installed using the legacy 'setup.py install' 
method, because it does not have a 'pyproject.toml' and the 'wheel' package is 
not installed. pip 23.1 will enforce this behaviour change. A possible 
replacement is to enable the '--use-pep517' option. Discussion can be found 
athttps://github.com/pypa/pip/issues/8559

  Running setup.py install for psycopg2 ... error

  error: subprocess-exited-with-error

  × Running setup.py install for psycopg2 did not run successfully.

  │ exit code: 1

  ╰─> [24 lines of output]

  
D:\Users\mike\envs\xreq\Lib\site-packages\setuptools\config\setupcfg.py:508: 
SetuptoolsDeprecationWarning: The license_file parameter is deprecated, use 
license_files instead.

    warnings.warn(msg, warning_class)

  running install

  
D:\Users\mike\envs\xreq\Lib\site-packages\setuptools\command\install.py:34: 
SetuptoolsDeprecationWarning: setup.py install is deprecated. Use build and pip 
and other standards-based tools.

    warnings.warn(

  running build

  running build_py

  creating build

  creating build\lib.win-amd64-cpython-311

  creating build\lib.win-amd64-cpython-311\psycopg2

  copying lib\errorcodes.py -> build\lib.win-amd64-cpython-311\psycopg2

  copying lib\errors.py -> build\lib.win-amd64-cpython-311\psycopg2

  copying lib\extensions.py -> build\lib.win-amd64-cpython-311\psycopg2

  copying lib\extras.py -> build\lib.win-amd64-cpython-311\psycopg2

  copying lib\pool.py -> build\lib.win-amd64-cpython-311\psycopg2

  copying lib\sql.py -> build\lib.win-amd64-cpython-311\psycopg2

  copying lib\tz.py -> build\lib.win-amd64-cpython-311\psycopg2

  copying lib\_ipaddress.py -> build\lib.win-amd64-cpython-311\psycopg2

  copying lib\_json.py -> build\lib.win-amd64-cpython-311\psycopg2

  copying lib\_range.py -> build\lib.win-amd64-cpython-311\psycopg2

  copying lib\__init__.py -> build\lib.win-amd64-cpython-311\psycopg2

  running build_ext

  building 'psycopg2._psycopg' extension

  error: Microsoft Visual C++ 14.0 or greater is required. Get it with 
"Microsoft C++ Build 
Tools":https://visualstudio.microsoft.com/visual-cpp-build-tools/

  [end of output]

  note: This error originates from a subprocess, and is likely not a problem 
with pip.

error: legacy-install-failure

× Encountered error while trying to install package.

╰─> psycopg2

note: This is an issue with the package mentioned above, not pip.

hint: See above for output from the failure.

(xreq) D:\Users\mike\envs\xreq>






Cheers

Mike

On 12/04/2023 6:13 pm, Mike Dewhirst wrote:
Well thank you Christoph Gohlke and thank you Ian Bicking and 
colleagues.


I just used pip to nakedly install psycopg2 and Pillow without a 
hitch. My distrust of Windows has kept me going back to Christoff's 
well for years.


Maybe it is time to assume innocence unless proven guilty ;-)

Thanks to all who showed me the way.

Cheers

Mike

On 11/04/2023 11:39 pm, Thomas Passin wrote:

On 4/11/2023 6:58 AM, Chris Angelico wrote:
On Tue, 11 Apr 2023 at 20:15, Jim Schwartz  
wrote:


What’s the problem now?  Is it with python on windows?  I use 
python on windows so I’d like to know. Thanks




Python itself is fine, but a lot of third-party packages are hard to
obtain. So if you need numpy, for instance, or psycopg2, you might
need to find an alternative source.


I've noticed a big change in the last few years in that PyPi has 
many, many amd-64 packages than it used to in the heyday of 
Christoph Gohlke's efforts. I haven't needed to go there for some 
time whereas I used to need to all the time.  So if I "need numpy, 
for instance, or psycopg2" for Windows, I get them from PyPi.


Yes, I know that some projects haven't caught up to Python 3.11

Re: Christoph Gohlke and compiled packages

2023-04-12 Thread MRAB

On 2023-04-13 02:27, Mike Dewhirst wrote:

On 12/04/2023 10:59 pm, Mike Dewhirst wrote:

Sadly Windows is still in the dock. The jury is still out.

Turns out the "without a hitch" was based on cached wheels.

I'm going to start from scratch with new projects using Pythons 3.8, 
3.10 and 3.11 and report back.


Report summary:

pip install works well with Python 3.8 and 3.10 (and presumably 3.9) but
3.11 fails.

Report conclusion:

As indicated in this thread, pip cannot find Python 3.11 wheels and
therefore needs to compile from source. It is looking for Microsoft's
C++ compiler version 14.

I'll (gulp) attempt to swallow the Koolaid.

See error below ...

Cheers

Mike

(xreq) D:\Users\mike\envs\xreq>pip install -r requirements\dev.txt

...

Collecting psycopg2==2.9.3

    Downloading psycopg2-2.9.3.tar.gz (380 kB)

   --- 380.6/380.6 kB 6.0 MB/s eta 
0:00:00

    Preparing metadata (setup.py) ... done

Collecting Pillow==9.1.1

    Downloading Pillow-9.1.1.tar.gz (49.8 MB)

    49.8/49.8 MB 4.5 MB/s eta 
0:00:00

    Preparing metadata (setup.py) ... done

...

Installing collected packages: psycopg2, Pillow, ...

    DEPRECATION: psycopg2 is being installed using the legacy 'setup.py 
install' method, because it does not have a 'pyproject.toml' and the 'wheel' 
package is not installed. pip 23.1 will enforce this behaviour change. A 
possible replacement is to enable the '--use-pep517' option. Discussion can be 
found athttps://github.com/pypa/pip/issues/8559

    Running setup.py install for psycopg2 ... error

    error: subprocess-exited-with-error

    × Running setup.py install for psycopg2 did not run successfully.

    │ exit code: 1

    ╰─> [24 lines of output]

    
D:\Users\mike\envs\xreq\Lib\site-packages\setuptools\config\setupcfg.py:508: 
SetuptoolsDeprecationWarning: The license_file parameter is deprecated, use 
license_files instead.

      warnings.warn(msg, warning_class)

    running install

    
D:\Users\mike\envs\xreq\Lib\site-packages\setuptools\command\install.py:34: 
SetuptoolsDeprecationWarning: setup.py install is deprecated. Use build and pip 
and other standards-based tools.

      warnings.warn(

    running build

    running build_py

    creating build

    creating build\lib.win-amd64-cpython-311

    creating build\lib.win-amd64-cpython-311\psycopg2

    copying lib\errorcodes.py -> build\lib.win-amd64-cpython-311\psycopg2

    copying lib\errors.py -> build\lib.win-amd64-cpython-311\psycopg2

    copying lib\extensions.py -> build\lib.win-amd64-cpython-311\psycopg2

    copying lib\extras.py -> build\lib.win-amd64-cpython-311\psycopg2

    copying lib\pool.py -> build\lib.win-amd64-cpython-311\psycopg2

    copying lib\sql.py -> build\lib.win-amd64-cpython-311\psycopg2

    copying lib\tz.py -> build\lib.win-amd64-cpython-311\psycopg2

    copying lib\_ipaddress.py -> build\lib.win-amd64-cpython-311\psycopg2

    copying lib\_json.py -> build\lib.win-amd64-cpython-311\psycopg2

    copying lib\_range.py -> build\lib.win-amd64-cpython-311\psycopg2

    copying lib\__init__.py -> build\lib.win-amd64-cpython-311\psycopg2

    running build_ext

    building 'psycopg2._psycopg' extension

    error: Microsoft Visual C++ 14.0 or greater is required. Get it with 
"Microsoft C++ Build 
Tools":https://visualstudio.microsoft.com/visual-cpp-build-tools/

    [end of output]

    note: This error originates from a subprocess, and is likely not a problem 
with pip.

error: legacy-install-failure

× Encountered error while trying to install package.

╰─> psycopg2

note: This is an issue with the package mentioned above, not pip.

hint: See above for output from the failure.

(xreq) D:\Users\mike\envs\xreq>


[snip]

C:\Users\mrab>py -3.11 -m pip install psycopg2
Collecting psycopg2
  Downloading psycopg2-2.9.6-cp311-cp311-win_amd64.whl (1.2 MB)
  1.2/1.2 MB 2.4 MB/s eta 
0:00:00

Installing collected packages: psycopg2
Successfully installed psycopg2-2.9.6

C:\Users\mrab>py -3.11 -m pip install Pillow
Requirement already satisfied: Pillow in c:\python311\lib\site-packages 
(9.2.0)


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


Re: Christoph Gohlke and compiled packages

2023-04-12 Thread Eryk Sun
On 4/12/23, Mike Dewhirst  wrote:
>
> Collecting psycopg2==2.9.3

x86 and x64 wheels are available for Python 3.11 if you can use
Psycopg 2 version 2.9.5 or 2.9.6 instead of 2.9.3:

https://pypi.org/project/psycopg2/2.9.5/#files
https://pypi.org/project/psycopg2/2.9.6/#files
-- 
https://mail.python.org/mailman/listinfo/python-list


RE: Weak Type Ability for Python

2023-04-12 Thread avi.e.gross
As originally written, the question posed has way too many possible answers
but the subject line may give a hint. Forget printing.

The Python statement
1 + "a"

SHOULD fail. The first is an integer and the second is  string. These two
are native Python objects that neither define what to do if they are paired
with an object of the other type on the left or the right.

In any case, what should the answer be? Since "a" has no integer value, it
presumably was intended to be the string "1a".

So why NOT use the built-in conversion and instead of:

print(x+y) # where x=1, y='a'

It should be:

print(str(x) + y)

Could this behavior be added to Python? Sure. I wonder how many would not
like it as it often will be an error not caught!

If you defined your own object derived from string and added a __radd__()
method then the method could be made to accept whatever types you wanted
(such as integer or double or probably anything) and simply have code that
converts it to the str() representation and then concatenates them with, or
if you prefer without, any padding between.

I suspect the OP is thinking of languages like PERL or JAVA which guess for
you and make such conversions when it seems to make sense.

Python does not generally choose that as it is quite easy to use one of so
many methods, and lately an f-string is an easy way as others mentioned.


-Original Message-
From: Python-list  On
Behalf Of Thomas Passin
Sent: Wednesday, April 12, 2023 2:52 PM
To: [email protected]
Subject: Re: Weak Type Ability for Python

On 4/12/2023 1:11 PM, Chris Angelico wrote:
> On Thu, 13 Apr 2023 at 03:05, Ali Mohseni Roodbari
>  wrote:
>>
>> Hi all,
>> Please make this command for Python (if possible):
>>
> x=1
> y='a'
> wprint (x+y)
> 1a
>>
>> In fact make a new type of print command which can print and show strings
>> and integers together.
>>
> 
> Try:
> 
> print(x, y)
> 
> ChrisA

It puts a space between "1" and "a", whereas the question does not want 
the space.  print(f'{x}{y}') would do it, but only works for variables 
named "x" and "y".

As happens so often, the OP has not specified what he actually wants to 
do so we can only answer the very specific question.

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

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


Re: Christoph Gohlke and compiled packages

2023-04-12 Thread Mike Dewhirst

On 13/04/2023 12:00 pm, Eryk Sun wrote:

On 4/12/23, Mike Dewhirst  wrote:

Collecting psycopg2==2.9.3

x86 and x64 wheels are available for Python 3.11 if you can use
Psycopg 2 version 2.9.5 or 2.9.6 instead of 2.9.3:

https://pypi.org/project/psycopg2/2.9.5/#files
https://pypi.org/project/psycopg2/2.9.6/#files


Many thanks to both of you ...

I'll uninstall Microsoft Build Tools as soon as its finished installing 
(37.3GB and I had to clear space for it)


Cheers

Mike




--
Signed email is an absolute defence against phishing. This email has
been signed with my private key. If you import my public key you can
automatically decrypt my signature and be sure it came from me. Your
email software can handle signing.



OpenPGP_signature
Description: OpenPGP digital signature
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Weak Type Ability for Python

2023-04-12 Thread Cameron Simpson

On 12Apr2023 22:12, [email protected]  wrote:
I suspect the OP is thinking of languages like PERL or JAVA which guess 
for

you and make such conversions when it seems to make sense.


JavaScript guesses. What a nightmare. Java acts like Python and will 
forbid it on type grounds (at compile time with Java, being staticly 
typed).


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


Re: Weak Type Ability for Python

2023-04-12 Thread MRAB

On 2023-04-13 03:12, [email protected] wrote:

As originally written, the question posed has way too many possible answers
but the subject line may give a hint. Forget printing.

The Python statement
1 + "a"

SHOULD fail. The first is an integer and the second is  string. These two
are native Python objects that neither define what to do if they are paired
with an object of the other type on the left or the right.

In any case, what should the answer be? Since "a" has no integer value, it
presumably was intended to be the string "1a".

So why NOT use the built-in conversion and instead of:

print(x+y) # where x=1, y='a'

It should be:

print(str(x) + y)

Could this behavior be added to Python? Sure. I wonder how many would not
like it as it often will be an error not caught!

If you defined your own object derived from string and added a __radd__()
method then the method could be made to accept whatever types you wanted
(such as integer or double or probably anything) and simply have code that
converts it to the str() representation and then concatenates them with, or
if you prefer without, any padding between.

I suspect the OP is thinking of languages like PERL or JAVA which guess for
you and make such conversions when it seems to make sense.

In the case of Perl, there are distinct operators for addition and 
string concatenation, with automatic type conversion (non-numeric 
strings have a numeric value of 0, which can hide bugs).



Python does not generally choose that as it is quite easy to use one of so
many methods, and lately an f-string is an easy way as others mentioned.


-Original Message-
From: Python-list  On
Behalf Of Thomas Passin
Sent: Wednesday, April 12, 2023 2:52 PM
To: [email protected]
Subject: Re: Weak Type Ability for Python

On 4/12/2023 1:11 PM, Chris Angelico wrote:

On Thu, 13 Apr 2023 at 03:05, Ali Mohseni Roodbari
 wrote:


Hi all,
Please make this command for Python (if possible):


x=1
y='a'
wprint (x+y)
1a


In fact make a new type of print command which can print and show strings
and integers together.



Try:

print(x, y)

ChrisA


It puts a space between "1" and "a", whereas the question does not want
the space.  print(f'{x}{y}') would do it, but only works for variables
named "x" and "y".

As happens so often, the OP has not specified what he actually wants to
do so we can only answer the very specific question.



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


Re: Weak Type Ability for Python

2023-04-12 Thread MRAB

On 2023-04-13 03:21, Cameron Simpson wrote:

On 12Apr2023 22:12, [email protected]  wrote:
I suspect the OP is thinking of languages like PERL or JAVA which guess 
for

you and make such conversions when it seems to make sense.


JavaScript guesses. What a nightmare. Java acts like Python and will
forbid it on type grounds (at compile time with Java, being staticly
typed).

I thought that in Java you can, in fact, concatenate a string and an 
int, so I did a quick search online and it appears that you can.

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


RE: Weak Type Ability for Python

2023-04-12 Thread avi.e.gross
On closer reading, the OP may be asking how to make a function doing what
they want, albeit without a plus.

Here is a python function as a one-liner that takes exactly two arguments of
any kind (including string and integer) and concatenates them into one
string without anything between and prints them:

def strprint(first, second): print(str(first) + str(second))

>>> strprint(5,1)
51
>>> strprint("a5",1)
a51
>>> strprint(12,"o'clock")
12o'clock
>>> strprint(3.1415926535,complex(3,4))
3.1415926535(3+4j)

Want something similar for any number of arguments? Here is a slightly
longer one-liner:

def strprintall(*many): print(''.join([str(each) for each in many]))

>>>
strprintall(1,"=egy\n",2,"=kettő\n",3,"=három\n",4,"=négy\n",5,"=öt\n","in
my childhood language.\n")
1=egy
2=kettő
3=három
4=négy
5=öt
in my childhood language.

Note my meager attempt is not using a plus sign as I addressed a sort of way
that could be done using a __radd__ method or other ways like an f-string.

I can not repeat this often enough. The easiest way to do something you want
in a new language is to work within the existing language as-is and not to
ask the language to change to be the way you want. That can take years or
never happen, and especially if the designers did not want the feature you
ask for. 





-Original Message-
From: Python-list  On
Behalf Of [email protected]
Sent: Wednesday, April 12, 2023 3:17 PM
To: [email protected]
Subject: Re: Weak Type Ability for Python

On 2023-04-12 at 14:51:44 -0400,
Thomas Passin  wrote:

> On 4/12/2023 1:11 PM, Chris Angelico wrote:
> > On Thu, 13 Apr 2023 at 03:05, Ali Mohseni Roodbari
> >  wrote:
> > > 
> > > Hi all,
> > > Please make this command for Python (if possible):
> > > 
> > > > > > x=1
> > > > > > y='a'
> > > > > > wprint (x+y)
> > > > > > 1a
> > > 
> > > In fact make a new type of print command which can print and show
strings
> > > and integers together.
> > > 
> > 
> > Try:
> > 
> > print(x, y)
> > 
> > ChrisA
> 
> It puts a space between "1" and "a", whereas the question does not want
the
> space.  print(f'{x}{y}') would do it, but only works for variables named
"x"
> and "y".

Or possibly print(x, y, sep='').

> As happens so often, the OP has not specified what he actually wants to do
> so we can only answer the very specific question.

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

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


Re: Weak Type Ability for Python

2023-04-12 Thread Cameron Simpson

On 13Apr2023 03:36, MRAB  wrote:
I thought that in Java you can, in fact, concatenate a string and an 
int, so I did a quick search online and it appears that you can.


I stand corrected. I could have sworn it didn't, but it has been a long 
time. - Cameron Simpson 

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


RE: Weak Type Ability for Python

2023-04-12 Thread avi.e.gross
Given the significant number of languages other than Python that have some
version of a feature that allows implicit conversion of unlike operands to
concatenate something like a "number" and a string into a string, the
question may not be silly as to how or why Python chose as it chose.

As I see it, python did put in quite a bit of customizability and
flexibility including the ability to create your own object types that alter
the behavior of an operator like plus. I have seen plenty of code that takes
advantage and makes the user of the code assume that different types can
interact seamlessly.

But it is like many other things. Languages that support a wide variety of
integer types such as signed and unsigned versions of integers in 8 bits,
sixteen bits, 32 bits and even 64 bits or perhaps higher, will often look
like they allow you to mix them in various combinations for not just
addition. But underneath it all can be lots of hidden complexity. I have
seen languages that make lots of functions with the same names but different
signatures and then dispatch a call like add(int8, unsignedint32) to the
right function that best matches their signature. The functions internally
can do many things but often convert their arguments to a common format,
perform the operations, then perhaps convert back to whatever result output
was expected.

In the case being discussed we might have to create something that looks
like do_plus(int, int) and then do_plus(int, char) and so on.

The other alternatives can include tables of "generality" and
"convertibility" with rules that govern how to perform a calculation by
changing or upgrading or downgrading things to make a match that can then be
handled. 

The issue here is a sort of operator overloading. In Python, "+" does not
mean plus at all. It means whatever the programmer wanted it to mean. An
infix line of code that includes "obj1 + obj2" is supposed to investigate
how to do it. I am not sure if some built-in objects may be different, but
it does a sequence of operations till it finds what it needs and does it.

I believe it looks a bit like this. The LHS object, obj1, is examined to see
if it has defined a __add__() method. If found, it is called and either
produces a result or signals it cannot handle obj2 for some reason. If that
method is not found, or fails, then it looks to see if the RHS, obj2, has a
__radd__() method defined. That can be given obj1 and return an answer or
signal failure. 

If obj1 is 5 and obj2 is "pm" then we are using the built-in predefined
classes that currently have no interest in concatenating or adding unlike
types like this. If you could add or change these dunder methods (and note
you may also need to deal with __iadd__() to handle the case where x=5 and
you write "x += "pm" albeit that could weirdly change the type of x without
a linter having a clue.

I suggest the latter argument may be a good enough reason that Python did
not implement this. There are many good reasons. Does anyone like a language
that lets you type 2 + "three" and quietly makes that be 5? Sure, it can be
made to work on a subset of number in say English, but will it work in other
languages. It can be hard enough now to write code in UNICODE (I have seen
some) that tries to determine if a code point represents a number in some
language or representation and treats it as a numeral. I have seen the
numeric bullets such as a dark circle containing a white nine be treated as
if the user had put in a nine, for example.

As was mentioned, some languages have different operators for addition
versus concatenation and in that context, it may be intuitive that using the
wrong object type is an implicit call to conversion. Python uses "+" for
both purposes depending on context and potentially for many more purposes
the programmer can devise. 

Consider the asterisk operator as a companion concept. It gladly accepts a
string and a number in either order and does something somewhat intuitive
with them by treating multiplication as a sort of repeated addition:

>>> 5 * "6"
'6'
>>> "5" * 6
'55'
>>> 3 * "Hello? "
'Hello? Hello? Hello?

But it will not handle float.

>>> "Hello" * 2.5
TypeError: can't multiply sequence by non-int of type 'float'

If you want to either truncate a float to an into or round it or take a
ceiling, though, it will not guess for you and you must do something
explicit like this:

>>> "Hello" * round(2.5)
'HelloHello'
>>> "Hello" * round(2.6)
'HelloHelloHello'
>>> "Hello" * int(2.6)
'HelloHello'

There is a parallel argument here in arguing it should accept a float and
truncate it. But since you can easily cast a float to an int, in any of many
ways, why have the program choose when it quite likely reflects an error in
the code. And, no, I do not suggest 2.5 be interpreted as putting in an
approximate percentage so that .8 * "Hello" should result in "Hell" ...




-Original Message-
From: Python-list  On
Behalf Of Cameron Simpson
Sent: Wed