Re: Checking if email is valid

2023-11-01 Thread Mats Wichmann via Python-list

On 11/1/23 05:35, Simon Connah via Python-list wrote:

OK. I've been doing some reading and that you should avoid regex to check email 
addresses. So what I was thinking was something like this:


To be a little more specific, Avoid Rolling Your Own RegEx.  It's very 
tricky, and you will get it subtly wrong.


All depending, as others have said, on what level of "validation" you're 
after.


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


Re: pip/pip3 confusion and keeping up to date

2023-11-02 Thread Mats Wichmann via Python-list

On 11/2/23 04:58, Chris Green via Python-list wrote:

I have a couple of systems which used to have python2 as well as
python3 but as Ubuntu and Debian verions have moved on they have
finally eliminated all dependencies on python2.

So they now have only python3 and there is no python executable in
PATH.


FWIW, for this you install the little stub package python-is-python3. 
Especially if you want to keep a python2 installation around - "python" 
will still be python3 in this case.



So, going on from this, how do I do the equivalent of "apt update; apt
upgrade" for my globally installed pip packages


Odds are you don't want to. The internet is full of surprises about 
dependency problems when stuff is blindly updated; the set of Python 
packages in the apt repositories is carefully curated to avoid these 
problems - and this is part of the reason why sometimes certain such 
packages are irritatingly down-rev.





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


Re: Too Broad of an exception

2023-10-26 Thread Mats Wichmann via Python-list

On 10/26/23 03:04, Rene Kita via Python-list wrote:

Rene Kita  wrote:

rsutton  wrote:

Hi all,
I am fairly new to python (ie < 2 years).  I have a question about
pylint.  I am running on windows 10/11, python 3.10.11.

[...]

 if p.returncode >= 8:
 raise Exception(f'Invalid result: {p.returncode}')

It actually runs fine.  But pylint is not having it.  I get:

win_get_put_tb_filters.py:61:12: W0719: Raising too general exception:
Exception (broad-exception-raised)


pylint is just a linter, ignore it if the code works and you like it the
way it is.

pylint complains because you use Exception. Use e.g. RuntimeException to
silence it.



Ingrid says it's a RuntimeError, not RuntimeException.


Meanwhile, the purpose of this complaint from pylint (and notice it's a 
"warning", not an "error", so take that for what it's worth), is that 
you usually want to convey some information when you raise an exception. 
Of course, you can put that into the message you pass to the class 
instance you raise, but the type of exception is informational too. 
Raising just "Exception" is equivalent to saying "my car is broken", 
without specifying that the starter turns but won't "catch", or starts 
but the transmission won't engage, or the battery is dead, or  so 
it's *advising* (not forcing) you to be more informative.


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


Re: Checking if email is valid

2023-11-05 Thread Mats Wichmann via Python-list

On 11/5/23 10:34, Grant Edwards via Python-list wrote:


Indeed. There is a tiny but brightly burning kernel of hate in my
heart for web sites (and their developers) that refuse to accept
credit card numbers entered with spaces _as_they_are_shown_on_the_card_!

I've concluded that using PHP causes debilitating and irreversible
brain damage.


I think it's the attitude that speed of deployment is more important 
than any other factor, rather than just PHP :-)  Plus a bunch of that 
stuff is also coded in the front end (aka Javascript).


Phone numbers.
Credit card numbers.
Names (in my case - my wife has a hypenated surname which is almost as 
deadly as non-alpha characters in a name which was already mentioned in 
this diverging thread)


and addresses.  living rurally we have two addresses: a post office 
rural route box for USPS and a "street address" for anyone else.  The 
former looks like "{locationID} Box {number}".  The single word "Box" 
often triggers "we don't deliver to P.O. Boxes" - it's not a PO Box, and 
it's the only address USPS will deliver to, so get over yourself.  Or 
triggers fraud detection alerts, because "billing address" != "shipping 
address".


it's astonishing how bad so many websites are at what should be a 
fundamental function: taking in user-supplied data in order to do 
something valuable with it.



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


Re: Checking if email is valid

2023-11-06 Thread Mats Wichmann via Python-list

On 11/6/23 01:57, Simon Connah via Python-list wrote:

The thing I truly hate is when you have two telephone number fields. One for landline and one for mobile. I mean who in hell has a landline these days? 


People who live in places with spotty, or no, mobile coverage. We do exist.
--
https://mail.python.org/mailman/listinfo/python-list


Re: Checking if email is valid

2023-11-06 Thread Mats Wichmann via Python-list

On 11/6/23 08:23, Jon Ribbens via Python-list wrote:

On 2023-11-06, Mats Wichmann  wrote:

On 11/6/23 01:57, Simon Connah via Python-list wrote:

The thing I truly hate is when you have two telephone number fields.
One for landline and one for mobile. I mean who in hell has a
landline these days?


People who live in places with spotty, or no, mobile coverage. We do
exist.


Catering for people in minority situations is, of course, important.

Catering for people in the majority situation is probably important too.


A good experience would do both, in a comfortable way for either.

Continuing with the example, if you have a single phone number field, or 
let a mobile number be entered in a field marked for landline, you will 
probably assume you can text to that number.  I see this all the time on 
signups that are attempting to provide some sort of 2FA - I enter the 
landline number and the website tries to text a verification code to it 
(rather have an authenticator app for 2FA anyway, but that's a different 
argument)


Suggests maybe labeling should be something like:

* Number you want to be called on
* Number for texted security messages, if different

Never seen that, though :-)


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


Re: pip/pip3 confusion and keeping up to date

2023-11-06 Thread Mats Wichmann via Python-list

On 11/6/23 14:28, Karsten Hilbert via Python-list wrote:


I had just hoped someone here might have a handy pointer for
how to deal with modules having to be installed from pip for
use with an apt-installed python-based application.


That just shouldn't happen - such packages are supposed to be 
dependency-complete within the packaging universe in question.


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


Re: PEP668 / pipx and "--editable" installs

2023-09-18 Thread Mats Wichmann via Python-list

On 9/18/23 02:16, Peter J. Holzer via Python-list wrote:

On 2023-09-15 14:15:23 +, c.buhtz--- via Python-list wrote:

I tried to install it via "pipx install -e .[develop]". It's pyproject.toml
has a bug: A missing dependency "dateutil". But "dateutil" is not available
from PyPi for Python 3.11 (the default in Debian 12). But thanks to great
Debian they have a "python3-dateutil" package. I installed it.


Sidenote:
PyPI does have several packages with "dateutil" in their name. From the
version number (2.8.2) I guess that "python-dateutil" is the one
packaged in Debian 12.

This can be installed via pip:



It *is* the case that package name is not always equal to importable 
name. That certainly occurs in the universe of Python packages on PyPI; 
it's if anything much more likely on Linux distributions which have to 
share the package name namespace with a lot more than just Python 
packages (just for starters, what seems like billions of Perl packages), 
so you're even more likely to see names like python-foo or python3-foo 
when the thing you import is foo.  That has nothing to do virtualenvs, 
of course.


The use of a virtualenv for a project actually makes it more likely that 
you discover unstated dependencies, which is generally a good thing.



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


Re: PEP668 / pipx and "--editable" installs

2023-09-18 Thread Mats Wichmann via Python-list

On 9/18/23 12:56, c.buhtz--- via Python-list wrote:

On 2023-09-18 10:16 "Peter J. Holzer via Python-list"
 wrote:

On 2023-09-15 14:15:23 +, c.buhtz--- via Python-list wrote:

I tried to install it via "pipx install -e .[develop]". It's
pyproject.toml has a bug: A missing dependency "dateutil". But
"dateutil" is not available from PyPi for Python 3.11 (the default
in Debian 12). But thanks to great Debian they have a
"python3-dateutil" package. I installed it.


This can be installed via pip:


I'm aware of this. But this is not the question.

I would like to know and understand why my via "pipx" installed package
"hyperorg" is not able to see the systems packages installed via "apt
install python3-dateutils"?

Is this the usual behavior? Is this correct?


Yes.  By default, the virtualenv contains just what you've installed. 
It's designed to give you tight control over what's installed, so you 
can track dependencies, avoid accidental inclusions, etc.  As usual, you 
don't have to accept the default. For example, for the venv module:


usage: venv [-h] [--system-site-packages] [--symlinks | --copies] [--clear]
[--upgrade] [--without-pip] [--prompt PROMPT] [--upgrade-deps]
ENV_DIR [ENV_DIR ...]

Creates virtual Python environments in one or more target directories.

positional arguments:
  ENV_DIR   A directory to create the environment in.

options:
  -h, --helpshow this help message and exit
  --system-site-packages
Give the virtual environment access to the system
site-packages dir.
...


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


Re: type annotation vs working code

2023-09-30 Thread Mats Wichmann via Python-list

On 9/30/23 13:00, Karsten Hilbert via Python-list wrote:

A type annotation isn't supposed to change what code does,
or so I thought:

#
class Borg:
_instances:dict = {}

def __new__(cls, *args, **kargs):
# look up subclass instance cache
if Borg._instances.get(cls) is None:
Borg._instances[cls] = object.__new__(cls)
return Borg._instances[cls]


class WorkingSingleton(Borg):

def __init__(self):
print(self.__class__.__name__, ':')
try:
self.already_initialized
print('already initialized')
return

except AttributeError:
print('initializing')

self.already_initialized = True
self.special_value = 42


class FailingSingleton(Borg):

def __init__(self):
print(self.__class__.__name__, ':')
try:
self.already_initialized:bool
print('already initialized')
return

except AttributeError:
print('initializing')

self.already_initialized = True
self.special_value = 42

s = WorkingSingleton()
print(s.special_value)

s = FailingSingleton()
print(s.special_value)

#

Notice how Working* and Failing differ in the type annotation
of self.already_initialized only.


What happens here is in the second case, the line is just recorded as a 
variable annotation, and is not evaluated as a reference, as you're 
expecting to happen, so it just goes right to the print call without 
raising the exception.  You could change your initializer like this:


def __init__(self):
print(self.__class__.__name__, ':')
self.already_initialized: bool
try:
self.already_initialized
print('already initialized')
return

The syntax description is here:

https://peps.python.org/pep-0526/#global-and-local-variable-annotations


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


Re: Unable to uninstall 3.10.9

2023-09-27 Thread Mats Wichmann via Python-list

On 9/25/23 12:10, Pau Vilchez via Python-list wrote:

Hello Python Team,



I am somehow unable to completely remove Python 3.10.9 (64 Bit) from my
computer. I have tried deleting the Appdata folder then repairing and then
uninstalling but it still persists in the remove/add program function in
windows 10. I am just trying to reinstall it because I didn’t add it to the
path correctly, any help is greatly appreciated.


Rerunning the installer and telling it uninstall should normally work 
(if you can't get to that from the Programs applet, then you can start 
from the installer itself).


You can also fix the path addition from the Modify screen in the 
installer, you don't need to uninstall for that.


If it's really stuck, the Windows installer subsystem could have gotten 
confused, usually this tool works for folks:


https://support.microsoft.com/en-us/topic/fix-problems-that-block-programs-from-being-installed-or-removed-cca7d1b6-65a9-3d98-426b-e9f927e1eb4d


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


Re: upgrade of pip on my python 2.7 version

2023-09-27 Thread Mats Wichmann via Python-list

On 9/27/23 14:02, Zuri Shaddai Kuchipudi via Python-list wrote:


Why it's trying to select an incompatible version when you ask to
upgrade is not something I'd like to speculate on, for me personally
that's a surprise. Maybe something else you did before?

Also make sure you're using a pip that matches your Python. It's usually
safer if you invoke it as:

python -m pip install --upgrade pip

(or whatever the precise name of your Python 2 interpreter actually is)

the code that i want to run and all the libraries are written for python 2 but 
i have seen a video where the person showed the 2to3 pip method in which it 
rewrites the code in python 3 and shows all the necessary changes.


Upgrading to Python 3 is the best answer... except when it isn't.  If 
you want to convert a small project it's usually not too hard; and using 
a conversion tool can work well.


If you have libraries "not under your control" expect a lot more work.

You can upgrade pip to the latest available version for Python 2.7 - 
will take some research, I don't know what that version might be.


Or you could try this:

https://bootstrap.pypa.io/pip/2.7/get-pip.py
If you were using a Linux distro, you probably don't want to mess with 
the "system pip" which is usually set up to understand details of how 
that distro's Python is packaged.  It looks like you're on Windows by 
the paths in your original message, so that should be okay.


Or... you could just ignore the message suggesting you upgrade pip, and 
proceed, hoping things will stay working as they are.

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


Re: upgrade of pip on my python 2.7 version

2023-09-27 Thread Mats Wichmann via Python-list

On 9/27/23 05:17, Zuri Shaddai Kuchipudi via Python-list wrote:

hello everyone this the error that im getting while trying to install and 
upgrade pip on what is the solution for it?

C:\repository\pst-utils-pc-davinci-simulator>pip install
You are using pip version 7.0.1, however version 23.2.1 is available.
You should consider upgrading via the 'pip install --upgrade pip' command.
You must give at least one requirement to install (see "pip help install")

C:\repository\pst-utils-pc-davinci-simulator>pip install --upgrade pip
You are using pip version 7.0.1, however version 23.2.1 is available.
You should consider upgrading via the 'pip install --upgrade pip' command.
Collecting pip
   Using cached 
https://files.pythonhosted.org/packages/ba/19/e63fb4e0d20e48bd2167bb7e857abc0e21679e24805ba921a224df8977c0/pip-23.2.1.tar.gz
 Complete output from command python setup.py egg_info:
 Traceback (most recent call last):
   File "", line 20, in 
   File 
"c:\users\kuchipz\appdata\local\temp\pip-build-gc4ekm\pip\setup.py", line 7
 def read(rel_path: str) -> str:
  ^
 SyntaxError: invalid syntax


PyPI *should* be returning a compatible version of pip to upgrade to. 
pip itself has long since dropped support for 2.7, and the version 
you're trying to force is pretty clear:


pip 23.2.1

Meta
License: MIT License (MIT)
Author: The pip developers
Requires: Python >=3.7
...
Classifiers
Development Status
5 - Production/Stable
Intended Audience
Developers
License
OSI Approved :: MIT License
Programming Language
Python
Python :: 3
Python :: 3 :: Only
...

So "don't do that".

Why it's trying to select an incompatible version when you ask to 
upgrade is not something I'd like to speculate on, for me personally 
that's a surprise.  Maybe something else you did before?


Also make sure you're using a pip that matches your Python. It's usually 
safer if you invoke it as:


python -m pip install --upgrade pip

(or whatever the precise name of your Python 2 interpreter actually is)

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


Re: path to python in venv

2023-09-27 Thread Mats Wichmann via Python-list

On 9/27/23 13:46, Larry Martell via Python-list wrote:

On Wed, Sep 27, 2023 at 12:42 PM Jon Ribbens via Python-list
 wrote:


On 2023-09-27, Larry Martell  wrote:

I was under the impression that in a venv the python used would be in
the venv's bin dir. But in my venvs I see this in the bin dirs:

lrwxrwxrwx 1 larrymartell larrymartell7 Sep 27 11:21 python -> python3
lrwxrwxrwx 1 larrymartell larrymartell   16 Sep 27 11:21 python3 ->
/usr/bin/python3

...

Not sure what this really means, nor how to get python to be in my venv.


WHy do you want python to be "in your venv"?


Isn't that the entire point of a venv? To have a completely self
contained env? So if someone messes with the system python it will not
break code running in the venv.


It can do that, it just turns out the defaults are to not make a 
dedicated Python instance, and to not give access to the system site 
packages.  The venv and virtualenv modules, at least, will let you 
override either of those defaults via command-line options at creation time.


Once a year I have virtualenvs break when the new Python version appears 
in Fedora, which is irritating, but I take the attitude that virtualenvs 
are disposable and (try to) not let it bother me that I forgot to deal 
with that ahead of time.   It helps if you make sure that a virtualenv 
has a record of its dependencies - perhaps a requirements.txt file in 
the project it's being used to build, so it's easy to recreate them.



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


Re: Unable to completely remove Python 3.10.9 (64 bit) from Computer

2023-10-05 Thread Mats Wichmann via Python-list

On 10/4/23 13:08, Roland Müller via Python-list wrote:


On 25.9.2023 19.58, Pau Vilchez via Python-list wrote:

    Hello Python Team,


    I am somehow unable to completely remove Python 3.10.9 (64 Bit) 
from my
    computer. I have tried deleting the Appdata folder then repairing 
and then
    uninstalling but it still persists in the remove/add program 
function in
    windows 10. I am just trying to reinstall it because I didn’t add 
it to

    the path correctly, any help is greatly appreciated.

This is a Windows issue and not actually Python -specific. It may happen 
to every program you install.


If something is installed by the normal way using the W10 installer it 
should be removable too. If not there should be some error.


Python seems somewhat prone to this on Windows, I recently had a case 
where the original version of two upgraded Pythons were still stuck 
sitting in the Programs (which I didn't notice originally), so it looked 
like 3.11.1 and 3.11.4 were *both* installed, as well as two 3.10 
versions - this was an otherwise well-behaving system, so it was quite 
mystifying.


You can run uninstall directly from the installer file (download it 
again if you need to). This may work better than selecting "modify" from 
the Programs applet - a "stuck" installation may still be missing some 
piece of information even if you tried to repair it.


If things are *really* stuck Microsoft provide a tool which I've used 
with success on really messed up installation info.


https://support.microsoft.com/en-us/topic/fix-problems-that-block-programs-from-being-installed-or-removed-cca7d1b6-65a9-3d98-426b-e9f927e1eb4d


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


Re: Running a subprocess in a venv

2023-10-21 Thread Mats Wichmann via Python-list

On 10/21/23 07:01, Larry Martell via Python-list wrote:

I have a python script, and from that I want to run another script in
a subprocess in a venv. What is the best way to do that? I could write
a file that activates the venv then runs the script, then run that
file, but that seems messy. Is there a better way?


You don't need to "activate" a virtualenv. The activation script does 
some helpful things along the way (setup and cleanup) but none of them 
are required.  The most important thing it does is basically:


VIRTUAL_ENV='path-where-you-put-the-virtualenv'
export VIRTUAL_ENV
_OLD_VIRTUAL_PATH="$PATH"
PATH="$VIRTUAL_ENV/bin:$PATH"
export PATH

and that's really only so that commands that belong to that virtualenv 
(python, pip, and things where you installed a package in the venv wich 
creates an "executable" in bin/) are in a directory first in your search 
path. As long as you deal with necessary paths yourself, you're fine 
without activating. So as mentioned elsewhere, just use the path to the 
virtualenv's Python and you're good to go.



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


Re: Compiling python on windows with vs

2023-06-13 Thread Mats Wichmann via Python-list

On 6/13/23 12:12, Thomas Schweikle via Python-list wrote:



Am Di., 13.Juni.2023 um 19:20:38 schrieb Jim Schwartz:

What version of visual studio are you using?


Visual Studio 2022, aka 17.6.2.


What version of python?


python 3.10.11 or 3.11.4

I’ve had success with using the cython package in python and cl from 
visual studio, but I haven’t tried visual studio alone.


Same problem at the same place: directory "../modules/..." not found, 
Renaming it from "Modules" to "modules" it is found, but then fails to 
find "Modules".


Looks like it awaits, compiling in Windows an filesystem only case 
aware, not case sensitive -- I'm assuming this a bug now. Building 
within cygwin (or MSYS, Ubuntu) this works as expected. But there it 
does not search for "modules" once and "Modules" at an other place.


I just did this build the other day for the first time even from a git 
checkout (so VS22, and not a versioned release but top of main branch), 
and there was no such problem - did you follow the instructions at 
https://devguide.python.org/getting-started/setup-building/index.html?



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


Re: Multiple inheritance and a broken super() chain

2023-07-03 Thread Mats Wichmann via Python-list

On 7/3/23 12:13, Mats Wichmann via Python-list wrote:

To natter on a bit, and possibly muddy the waters even further...


Now, as I see it, from the super()'s point of view, there are two
inheritance chains, one starting at Left and the other at Right. But
*Right.__init__()* is called twice.
No: each class has just a single inheritance chain, built up when the 
class object is constructed, to avoid going insane. Yes, the chain for 
Left and for Right are different, but you're not instantiating *either* 
of those classes when you make a Bottom, so they don't matter here. 
You're just filling out a Bottom: it looks for init, finds it, and so 
would stop hunting - but then the super() call there sends it to the 
next class object in the chain to look for the method you told it to 
(also init), where it would stop since it found it, except you sent it 
on with another super(), and so on.  Python is a bit... different :) 
(compared to other languages with class definitions)


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


Re: Multiple inheritance and a broken super() chain

2023-07-03 Thread Mats Wichmann via Python-list

On 7/3/23 12:01, Richard Damon via Python-list wrote:

On 7/3/23 1:38 PM, Peter Slížik via Python-list wrote:

Hello.

The legacy code I'm working with uses a classic diamond inheritance. 
Let me

call the classes *Top*, *Left*, *Right*, and *Bottom*.
This is a trivial textbook example. The classes were written in the
pre-super() era, so all of them initialized their parents and Bottom
initialized both Left and Right in this order.

The result was expected: *Top* was initialized twice:

Top.__init__() Left.__init__() Top.__init__() Right.__init__()
Bottom.__init__()

Now I replaced all parent init calls with *super()*. After this, Top was
initialized only once.

Top.__init__() Right.__init__() Left.__init__() Bottom.__init__()

But at this point, I freaked out. The code is complex and I don't have 
the
time to examine its inner workings. And before, everything worked 
correctly
even though Top was initialized twice. So I decided to break the 
superclass

chain and use super() only in classes inheriting from a single parent. My
intent was to keep the original behavior but use super() where 
possible to

make the code more readable.

class Top:
def __init__(self):
print("Top.__init__()")

class Left(Top):
def __init__(self):
super().__init__()
print("Left.__init__()")

class Right(Top):
def __init__(self):
super().__init__()
print("Right.__init__()")

class Bottom(Left, Right):
def __init__(self):
Left.__init__(self) # Here I'm calling both parents manually
Right.__init__(self)
print("Bottom.__init__()")

b = Bottom()


The result has surprised me:

Top.__init__() Right.__init__() Left.__init__() Top.__init__()
Right.__init__() Bottom.__init__()

Now, as I see it, from the super()'s point of view, there are two
inheritance chains, one starting at Left and the other at Right. But
*Right.__init__()* is called twice. What's going on here?

Thanks,
Peter


Because the MRO from Bottom is [Bottom, Left, Right, Top] so super() in 
Left is Right. It doesn't go to Top as the MRO knows that Right should 
go to Top, so Left needs to go to Right to init everything, and then

Bottom messes things up by calling Right again.


And you can see this a little better in your toy example by using begin 
*and* end prints in your initializers.


Also, you might find that because of the MRO, super() in your Bottom 
class would actually give you what you want.


And if not sure, print out Bottom.__mro__



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


Re: Setup-tools

2023-07-16 Thread Mats Wichmann via Python-list

On 7/15/23 12:56, MRAB via Python-list wrote:

On 2023-07-15 07:12, YOUSEF EZZAT via Python-list wrote:

Hey!. i face a problem when i get setup packages by pip
when i code this : "pip install numpy" in my command line it gives me 
error

"ModuleNotFoundError: No module named 'distutils'"

please, i need help for solving this problem.
i have python 3.12.0b4


What do you normally do when it can't find a module? Install it via pip!

pip install distutils

By the way, do you really need Python 3.12? It's still in beta, so 
unless you're specifically checking whether it works, ready for its 
final release, you'd be better off with Python 3.11.


To add to this:

For modules which have *binary* compiled wheels (of which numpy is one), 
they are quite likely to be version-specific, and for many projects, are 
not made available for pre-release Pythons. You can check numpy here:


https://pypi.org/project/numpy/#files

(note: pre-release versions targeting pre-release Pythons *may* be 
elsewhere too, you might check with the numpy project).


What pip does if it doesn't find an appropriate wheel version matching 
your Python version is try to build it from the source distribution - 
this is why it thinks it needs distutils.  If you're on Windows, this 
will almost certainly fail, although you can often find blogs written by 
people who have gone through the same adventure who describe how they 
got there in the end.


If numpy is the thing that's important to your work, the advice would be 
to stick to a released Python with a matching released numpy.  If you 
specifically need to test that something is going to work with 3.12, 
then by all means go ahead, but be prepared to do some legwork.




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


Re: Assistance Request - Issue with Installing 'pip' despite Python 3.10 Installation

2023-06-07 Thread Mats Wichmann via Python-list

On 6/7/23 10:08, MRAB via Python-list wrote:

On 2023-06-07 15:54, Florian Guilbault via Python-list wrote:

Dear Python Technical Team,

I hope this email finds you well. I am reaching out to you today to seek
assistance with an issue I am facing regarding the installation of 'pip'
despite my numerous attempts to resolve the problem.

Recently, I performed installation, uninstallation, and even repair
operations on Python 3.10 on my computer. However, I have noticed that
'pip' has never been installed successfully. When I check via the command
prompt, I receive the following error: "'pip' is not recognized as an
internal or external command, operable program, or batch file."

I have tried several approaches to resolve this issue. I have verified 
that

the PATH environment variable is correctly configured to include the path
to the Python Scripts directory. 


I'm assuming you checked - say, with Explorer - that pip.exe really is 
where you think it is?
Anyway,  if you ask a Windows shell (cmd) to locate it, and it doesn't, 
then your PATH is not set up correctly after all.


where pip

should give you back a path that ends witn ...\Scripts\pip.exe

That said, the suggestions already given are on point.  Running pip as a 
module (rather than as a standalone command) assures that it's 
associated with the Python you want it associated with.  In today's 
world, a lot of developer systems end up with multiple Python 
installations (*), and you don't want to use a pip that is bound to the 
wrong one, or the next email will be "I installed foo module but my 
Python fails to import it".


(*) You can have different Python versions for compat checking, you can 
have project-specific virtualenvs, you can have Pythons that come 
bundled with a subsystem like Conda, etc.



On Windows, it's recommended to use the Python Launcher and the pip module:

py -m pip install whatever



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


Re: Imports and dot-notation

2023-08-10 Thread Mats Wichmann via Python-list

On 8/9/23 17:28, dn via Python-list wrote:

Side note: Using "...import identifier, ..." does not save storage-space 
over "import module" (the whole module is imported regardless, IIRC), 
however it does form an "interface" and thus recommend leaning into the 
"Interface Segregation Principle", or as our InfoSec brethren would say 
'the principle of least privilege'. Accordingly, prefer "from ... import 
... as ...".




Attribute lookup has *some* cost.  That is, finding "c" in the local 
namespace is going to be a little quicker than "b.c", where Python finds 
"b" in the local namespace and then finds its "c" attribute; that's then 
a little quicker than "a.b.c", etc.


See all relevant commentary about premature optimisation, spending time 
optimising the wrong things, etc.  but there *are* cases where it 
matters (c.f. a tight loop that will be run many many times)

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


Re: Using __new__

2024-02-18 Thread Mats Wichmann via Python-list

On 2/17/24 19:24, dn via Python-list wrote:

On 18/02/24 13:21, Jonathan Gossage wrote:



- perhaps someone knows a better/proper way to do this?

Suggested research: custom classes, ABCs, and meta-classes...


Cure the old "what do you want to accomplish" question.  If it's to 
channel access to a resource to a single place, many folks seem to 
advocate just putting that code in a module, and not trying to use a 
class for that - Python already treats modules as a form of singleton 
(if you squint a bit). It's not Java, after all, everything doesn't 
_have_ to be a class.


I'd also second the idea of looking at metaclasses for an 
implementation. Most simpler class-based singleton approaches turn out 
not to be thread-safe... you can get closer to solving that with a 
metaclass with a lock taken in the dunder-call method.



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


Re: IDLE editor suggestion.

2023-12-12 Thread Mats Wichmann via Python-list

On 12/12/23 13:50, Thomas Passin via Python-list wrote:

On 2023-12-12 08:22, Steve GS via Python-list wrote:
 > Maybe this already exists but
 > I have never seen it in any
 > editor that I have used.
 >
 > It would be nice to have a
 > pull-down text box that lists
 > all of the searches I have
 > used during this session. It
 > would make editing a lot
 > easier if I could select the
 > previous searches rather than
 > having to enter it every time.
 >
 > If this is inappropriate to
 > post this here, please tell me
 > where to go.
 > Life should be so
 > complicated.
 >
EditPad has this.

So do Notepad++, EditPlus (not free but low cost, Windows only, and very 
good), and I'm sure many others that are much simpler than Visual Studio 
Code, for example.



Every now and then I pop up and suggest people look at Eric.  Odd name 
for an editor? Well, it continues the long pun history in the Python 
world (Eric Idle... get it?).  It has search history, among many other 
things, I think once it was considered to be sort of IDLE++, but it's 
grown to a lot more than that.   Not saying Eric is better-than-XYZ-IDE, 
but it is a cool project...



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


Re: Python 3.12.1, Windows 11: shebang line #!/usr/bin/env python3 doesn't work any more

2024-01-02 Thread Mats Wichmann via Python-list

On 1/1/24 12:53, Thomas Passin via Python-list wrote:

On Windows 10, a shebang line gets ignored in favor of Python 3.9.9 (if 
invoked by the script name alone) or Python 3.12.1 (if invoked by the 
"py" launcher).


fwiw, you can also create an ini file to define to the launcher py which 
version should be the default, if no version is specified.




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


Re: Type hints - am I doing it right?

2023-12-13 Thread Mats Wichmann via Python-list

On 12/13/23 00:19, Frank Millman via Python-list wrote:

I have to add 'import configparser' at the top of each of these modules 
in order to type hint the method.


This seems verbose. If it is the correct way of doing it I can live with 
it, but I wondered if there was an easier way.


Think of import as meaning "make this available in my current (module) 
namespace".


The actual import machinery only runs the first time, that is, if it's 
not already present in the sys.modules dict.

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


Re: Python 3.12.1, Windows 11: shebang line #!/usr/bin/env python3 doesn't work any more

2024-01-01 Thread Mats Wichmann via Python-list

On 1/1/24 04:02, Sibylle Koczian via Python-list wrote:

Am 30.12.2023 um 04:04 schrieb Mike Dewhirst via Python-list:


I had assumed the OP had installed Python from the Microsoft shop and 
that's where py.exe must have come from.




In fact I didn't say in my post that I always get Python from 
python.org. When I started to use the language there was no Python from 
any Microsoft shop (I'm not sure there was a Microsoft shop, it was in 
the last millenium, Python 1.5 or 1.6). So I tend to forget that 
possible download source.


But in all this thread I didn't see a single explanation for my current 
situation: one and the same shebang line works on Windows 10 / Python 
3.11 and doesn't work on Windows 11 / Python 3.12. I suspect Windows, 
because a change in the way Python 3.12 uses shebang lines should be 
visible in the documentation.


The shebang support in the Python Launcher is documented here:

https://docs.python.org/3/using/windows.html#shebang-lines

That says the line you list originally:

> My shebang line is usually "#!/usr/bin/env python3"

means look for python3 in PATH.  Do you have one? If you don't have one, 
you'll get one you don't want: the stupid Microsoft shim that, which if 
run interactively, encourages you to install from the Microsoft store. 
You should be able to disable this.


File suffix associations are a different thing - they give me no end of 
headaches on Windows. They start out bound to the shim, and should 
rebind to the launcher when you install, but then things can steal it. 
If you install Visual Studio Code with Python extensions, then it takes 
over the running of .py files - if you click in the explorer, you'll get 
it open in the editor, not run.  I've argued about this, to no avail 
(plays havoc with my testsuite, which in some places tries to execute 
Python scripts as a cli command).


And then I've got this:

C:\Users\mats\SOMEWHERE>py -0
 -V:3.13  Python 3.13 (64-bit)
 -V:3.12 *Python 3.12 (64-bit)
 -V:3.11  Python 3.11 (64-bit)
 -V:3.10  Python 3.10 (64-bit)
 -V:3.9   Python 3.9 (64-bit)
 -V:3.8   Python 3.8 (64-bit)
 -V:3.7   Python 3.7 (64-bit)
 -V:3.6   Python 3.6 (64-bit)

# Okay, it knows about lots of Python versions, and shows a default of 3.12

C:\Users\mats\SOMEWHERE>py
Python 3.12.1 (tags/v3.12.1:2305ca5, Dec  7 2023, 22:03:25) [MSC v.1937 
64 bit (AMD64)] on win32

Type "help", "copyright", "credits" or "license" for more information.
>>> ^Z

# Great, that works just as expected

C:\Users\mats\SOMEWHERE>py test.py
Python was not found; run without arguments to install from the 
Microsoft Store, or disable this shortcut from Settings > Manage App 
Execution Aliases.


# wait, what? if "py" worked, why doesn't "py test.py"?


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


Re: Python 3.12.1, Windows 11: shebang line #!/usr/bin/env python3 doesn't work any more

2024-01-01 Thread Mats Wichmann via Python-list

On 1/1/24 07:11, Thomas Passin via Python-list wrote:

Here's how to find out what program Windows thinks it should use to run 
a ".py" file.  In a console:


C:\Users\tom>assoc .py
.py=Python.File

C:\Users\tom>ftype Python.file
Python.file="C:\Windows\py.exe" "%L" %*


That's not enough. There is now (has been for a while) a layered system, 
and this gives you just one layer, there may be other associations that 
win out.


Per somebody who actually knows:

> The only way to determine the association without reimplmenting the 
shell's search is to simply ask the shell via AssocQueryString. Possibly 
PowerShell can provide this information. – Eryk Sun



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


Re: mypy question

2023-12-29 Thread Mats Wichmann via Python-list

On 12/29/23 05:15, Karsten Hilbert via Python-list wrote:

Hi all,

I am not sure why mypy thinks this

gmPG2.py:554: error: Argument "queries" to "run_rw_queries" has incompatible type 
"List[Dict[str, str]]"; expected
"List[Dict[str, Union[str, List[Any], Dict[str, Any"  [arg-type]
 rows, idx = run_rw_queries(link_obj = conn, queries = 
queries, return_data = True)
   
^~~

should be flagged. The intent is for "queries" to be

a list
of dicts
with keys of str
and values of
str OR
list of anything OR
dict with
keys of str
and values of anything

I'd have thunk list[dict[str,str]] matches that ?


Dict[str, str] means the key type and value type should both be strings, 
but in your retelling above you indicate lots of possible value types... 
actually the mypy guess seems to be a pretty good recreation of your 
psuedo-code description.

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


Re: mypy question

2023-12-29 Thread Mats Wichmann via Python-list

On 12/29/23 08:02, Karsten Hilbert via Python-list wrote:


Dict[str, str] means the key type and value type should both be strings,


Indeed, I know that much, list[dict[str, str]] is what is getting
passed in in this particular invocation of run_rw_queries().

For what it's worth here's the signature of that function:

def run_rw_queries (
link_obj:_TLnkObj=None,
queries:list[dict[str, str | list | dict[str, Any]]]=None,
end_tx:bool=False,
return_data:bool=None,
get_col_idx:bool=False,
verbose:bool=False
) -> tuple[list[dbapi.extras.DictRow], dict[str, int] | None]:

Given that I would have thought that passing in
list[dict[str, str]] for "queries" ought to be type safe.
Mypy indicates otherwise which I am not grokking as to why.


ah... didn't grok what you were asking, sorry - ignore my attempt then. 
So you are passing something that has been typed more narrowly than the 
function parameter. Can you use a TypeGuard here?

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


Re: Are there any easy-to-use Visual Studio C# WinForms-like GUI designers in the Python world for Tk?

2023-12-29 Thread Mats Wichmann via Python-list

On 12/28/23 18:05, Félix An via Python-list wrote:
I'm used to C# WinForms, which has an easy-to-use drag-and-drop GUI 
designer in Visual Studio. Is there anything similar for Tk? How about 
Qt? What do you recommend as the easiest way to create GUI programs in 
Python, similar to the ease of use of C# WinForms?


Qt has a long-standing Designer tool.

I was pretty sure there was nothing for tkinter, but it seems at least 
someone tried:


https://pypi.org/project/tkdesigner/

and someone has tried a web-based one (looks like it may help to read 
Chinese for that one)


https://visualtk.com/


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


Re: Extract lines from file, add to new files

2024-01-11 Thread Mats Wichmann via Python-list

On 1/11/24 11:27, MRAB via Python-list wrote:

On 2024-01-11 18:08, Rich Shepard via Python-list wrote:

It's been several years since I've needed to write a python script so I'm
asking for advice to get me started with a brief script to separate names
and email addresses in one file into two separate files: 
salutation.txt and

emails.txt.

An example of the input file:

Calvin
cal...@example.com

Hobbs
ho...@some.com

Nancy
na...@herown.com

Sluggo
slu...@another.com

Having extracted salutations and addresses I'll write a bash script using
sed and mailx to associate a message file with each name and email 
address.


I'm unsure where to start given my lack of recent experience.


 From the look of it:

1. If the line is empty, ignore it.

2. If the line contains "@", it's an email address.

3. Otherwise, it's a name.



4. Don't assume it's going to be "plain text" if the email info is 
harvested from external sources (like incoming emails) - you'll end up 
stumbling over a 誰かのユーザー from somewhere.  Process as bytes, or be really 
careful about which encodings you allow - which for email "names" is 
something you can't actually control.


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


Re: Python 3.12.1, Windows 11: shebang line #!/usr/bin/env python3 doesn't work any more

2024-01-15 Thread Mats Wichmann via Python-list

On 1/15/24 09:44, Sibylle Koczian via Python-list wrote:


First and foremost I want to understand why I'm seeing this:

- Python scripts with "/usr/bin/env python3" as shebang line work as 
expected on a computer with Windows 10 and Python 3.11.5. They have 
worked for years on this machine, using either the latest Python or one 
version before (depending on availability of some packages). There is a 
virtual machine with ArchLinux on the same machine and some of the 
scripts are copies from that.


- I've got a second computer with Windows 11 and I installed Python 
3.12.1 on it. After copying some scripts from my first computer I found 
that I couldn't start them: not by entering the script name in a 
console, not using py.exe, not double clicking in the explorer. Entering 
\python  probably worked - I think 
I tried that too, but I'm not really sure, because that's really not 
practical.


In the Python documentation for versions 3.11 and 3.12 I found no 
differences regarding py.exe and shebang lines.


Then I removed the "/env" from the shebang lines and could start the 
scripts from the second computer. That certainly is a solution, but why???


It's because of Windows itself.  The default nowadays is that irritating 
little stub that prompts you to go install Python from the WIndows 
store.  When you use the "env" form, it looks for python (or python3 in 
your case) in the PATH *first* and you'll get a hit.   Mine looks like:


C:\Users\mats\AppData\Local\Microsoft\WindwsApps\python.exe and python3.exe

you can check what it's doing for you by using the "where" command in a 
windows shell.


On your older Windows 10 machine you either never had that stub - I 
don't know when it was added, maybe someone from Microsoft listening 
here knows - or it's been superseded by changes to the PATH, or 
something.  On my fairly new Win 11 box the base of that path is early 
in the user portion of PATH, so that must be a default.


py.exe without the "/usr/bin/env" magic doesn't put PATH searching 
first, according to that snip from the docs that's been posted here 
several times., so you shouldn't fall down that particular rathole.


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


Re: Python 3.12.1, Windows 11: shebang line #!/usr/bin/env python3 doesn't work any more

2024-01-15 Thread Mats Wichmann via Python-list

On 1/15/24 09:44, Sibylle Koczian via Python-list wrote:

In the Python documentation for versions 3.11 and 3.12 I found no 
differences regarding py.exe and shebang lines.


Then I removed the "/env" from the shebang lines and could start the 
scripts from the second computer. That certainly is a solution, but why???


Sibylle


also, it looks like you can disable the PATH-searching behavior of the 
/usr/bin/env virtual path:


> The environment variable PYLAUNCHER_NO_SEARCH_PATH may be set (to any 
value) to skip this search of PATH.


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


Re: Python 3.12.1, Windows 11: shebang line #!/usr/bin/env python3 doesn't work any more

2024-01-15 Thread Mats Wichmann via Python-list

On 1/15/24 12:01, Thomas Passin via Python-list wrote:

On 1/15/2024 1:26 PM, Mats Wichmann via Python-list wrote:

On 1/15/24 09:44, Sibylle Koczian via Python-list wrote:


First and foremost I want to understand why I'm seeing this:

- Python scripts with "/usr/bin/env python3" as shebang line work as 
expected on a computer with Windows 10 and Python 3.11.5. They have 
worked for years on this machine, using either the latest Python or 
one version before (depending on availability of some packages). 
There is a virtual machine with ArchLinux on the same machine and 
some of the scripts are copies from that.


- I've got a second computer with Windows 11 and I installed Python 
3.12.1 on it. After copying some scripts from my first computer I 
found that I couldn't start them: not by entering the script name in 
a console, not using py.exe, not double clicking in the explorer. 
Entering \python  probably 
worked - I think I tried that too, but I'm not really sure, because 
that's really not practical.


In the Python documentation for versions 3.11 and 3.12 I found no 
differences regarding py.exe and shebang lines.


Then I removed the "/env" from the shebang lines and could start the 
scripts from the second computer. That certainly is a solution, but 
why???


It's because of Windows itself.  The default nowadays is that 
irritating little stub that prompts you to go install Python from the 
WIndows store.  When you use the "env" form, it looks for python (or 
python3 in your case) in the PATH *first* and you'll get a hit.   Mine 
looks like:


C:\Users\mats\AppData\Local\Microsoft\WindwsApps\python.exe and 
python3.exe


you can check what it's doing for you by using the "where" command in 
a windows shell.


On your older Windows 10 machine you either never had that stub - I 
don't know when it was added, maybe someone from Microsoft listening 
here knows - or it's been superseded by changes to the PATH, or 
something.  On my fairly new Win 11 box the base of that path is early 
in the user portion of PATH, so that must be a default.


py.exe without the "/usr/bin/env" magic doesn't put PATH searching 
first, according to that snip from the docs that's been posted here 
several times., so you shouldn't fall down that particular rathole.


Python from the App Store is not the same as Python from python.org:


yes. this question is about the python.org distribution. but, Windows 
natively has something called python.exe and python3.exe which is 
interfering here, IF the python.org install isn't directed to put itself 
into the path, AND if the "#!/usr/bin/env python3" form is used, causing 
a search in PATH, which is the setup Sibylle has described, unless I've 
misunderstood details.




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


Re: Python 3.12.1, Windows 11: shebang line #!/usr/bin/env python3 doesn't work any more

2024-01-17 Thread Mats Wichmann via Python-list

On 1/16/24 10:00, Sibylle Koczian via Python-list wrote:

Am 15.01.2024 um 23:55 schrieb Mats Wichmann via Python-list:

On 1/15/24 12:01, Thomas Passin via Python-list wrote:

On 1/15/2024 1:26 PM, Mats Wichmann via Python-list wrote:
Python from the App Store is not the same as Python from python.org:


yes. this question is about the python.org distribution. but, Windows 
natively has something called python.exe and python3.exe which is 
interfering here, IF the python.org install isn't directed to put 
itself into the path, AND if the "#!/usr/bin/env python3" form is 
used, causing a search in PATH, which is the setup Sibylle has 
described, unless I've misunderstood details.




No, you didn't misunderstand any detail. It's exactly right. My Windows 
10 box doesn't find anything for "where python", "where python3",


Be interesting to know if your WIndows 10 has those files in place, and 
it's just a missing path entry (a good thing, perhaps) that's causing it 
not to be found there.


while the new Windows 11 machine finds the Microsoft stub. "Irritating" is a 
very friendly attribute for that thing. Why must it be called 
"python.exe" and not something else like the installation files from 
python.org?


it will be replaced by the real "python.exe" from the Microsoft Store 
install, if you go ahead and install that - I guess that's why that name 
was chosen.


I'll stop using "/env" - hopefully that won't create problems with the 
scripts I use in the Linux VM. But in that case I'll know what's up.


Thank you very much!
Sibylle




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


Re: PyTorch

2024-01-17 Thread Mats Wichmann via Python-list

On 1/17/24 09:48, Alan Zaharia via Python-list wrote:

Hello Python

I Need help. it could not be found for PyTorch. It said in the Command Prompt 
ERROR: Could not find a version that satisfies the requirement torch (from 
versions: none)
ERROR: No matching distribution found for torch,  Can you help me?


Use Python 3.11.


Or follow here:

https://github.com/pytorch/pytorch/issues/110436

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


Re: Silly/crazy problem with sqlite

2023-11-25 Thread Mats Wichmann via Python-list

On 11/24/23 14:10, Chris Green via Python-list wrote:

Chris Green  wrote:

This is driving me crazy, I'm running this code:-


OK, I've found what's wrong:-


 cr.execute(sql, ('%' + "2023-11" + '%'))


should be:-

 cr.execute(sql, ('%' +  x + '%',) )


I have to say this seems very non-pythonesque to me, the 'obvious'
default simply doesn't work right, and I really can't think of a case
where the missing comma would make any sense at all.


as noted, the comma makes it a tuple.

this might be a case where rewriting as an f-string makes it just a 
little more readable, since the syntax will make it look like there's a 
single string followed by a comma - the addition just makes it look less 
clear to my eyes:


cr.execute(sql, (f'%2023-11%', ))

cr.execute(sql, (f'%{x}%', ))

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


Re: How/where to store calibration values - written by program A, read by program B

2023-12-05 Thread Mats Wichmann via Python-list

On 12/5/23 07:37, Chris Green via Python-list wrote:

Is there a neat, pythonic way to store values which are 'sometimes'
changed?

My particular case at the moment is calibration values for ADC inputs
which are set by running a calibration program and used by lots of
programs which display the values or do calculations with them.

 From the program readability point of view it would be good to have a
Python module with the values in it but using a Python program to
write/update a Python module sounds a bit odd somehow.

I could simply write the values to a file (or a database) and I
suspect that this may be the best answer but it does make retrieving
the values different from getting all other (nearly) constant values.

Are there any Python modules aimed specifically at this sort of
requirement?


A search term to look for is "data persistence"

there is lots of support at various levels - you can do simpler things 
with plain text (or binary), json data, or csv data, or configparser, or 
use pickles; if there's not a lot of values a dbapi database may, as 
already mentioned, be overkill.


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


Re: argparse argument post-processing

2023-11-27 Thread Mats Wichmann via Python-list

On 11/27/23 04:29, Dom Grigonis via Python-list wrote:

Hi all,

I have a situation, maybe someone can give some insight.

Say I want to have input which is comma separated array (e.g. 
paths='path1,path2,path3') and convert it to the desired output - list:
import argparse
parser = argparse.ArgumentParser()
parser.add_argument('paths', type=lambda x: list(filter(str.strip, 
x.split(','
So far so good. But this is just an example of what sort of solution I am after.


Maybe use "action" rather than "type" here? the conversion of a csv 
argument into words seems more like an action.



Now the second case. I want input to be space separated array - bash array. And 
I want space-separated string returned. My current approach is:
import argparse
parser = argparse.ArgumentParser()
parser.add_argument('paths', nargs='+')
args = parser.parse_args()
paths = ' '.join(args.paths)
But what I am looking for is a way to do this, which is intrinsic to `argparse` 
module. Reason being I have a fair amount of such cases and I don’t want to do 
post-processing, where post-post-processing happens (after 
`parser.parse_args()`).

I have tried overloading `parse_args` with post-processor arguments, and that 
seemed fine, but it stopped working when I had sub-parsers, which are defined 
in different modules and do not call `parse_args` themselves.


Depending on what *else* you need to handle it may or not may work here 
to just collect these from the remainders, and then use an action to 
join them, like:


import argparse 




class JoinAction(argparse.Action): 

def __call__(self, parser, namespace, values, option_string=None): 

setattr(namespace, self.dest, ' '.join(values)) 




parser = argparse.ArgumentParser() 

parser.add_argument('paths', nargs=argparse.REMAINDER, 
action=JoinAction)
args = parser.parse_args() 



print(f"{args.paths!r}") 








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


Re: argparse argument post-processing

2023-11-27 Thread Mats Wichmann via Python-list

On 11/27/23 13:21, Dom Grigonis wrote:

Thank you, exactly what I was looking for!

One more question following this. Is there a way to have a customisable action? 
I.e. What if I want to join with space in one case and with coma in another. Is 
there a way to reuse the same action class?


I've worked more with optparse (the project I work on that uses it has 
reasons why it's not feasible to convert to argparse); in optparse you 
use a callback function, rather than an action class, and the change to 
a callable class is somewhat significant :-; so I'm not really an expert.


The question is how you determine which you want to do - then there's no 
problem for the action class's call method to implement it. I presume 
you can write an initializer class that takes an extra argument, collect 
that and stuff it into an instance variable, then use super to call the 
base Action class's initializer with the rest of the args


super().__init__(option_strings=option_strings, *args, **kwargs)

Hopefully someone else has done this kind of thing because now I'm just 
guessing!



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


Re: Assistance Needed: Corrupted Python Installation Uninstallation Issue

2024-01-29 Thread Mats Wichmann via Python-list

On 1/29/24 05:19, Syed Hamood via Python-list wrote:

Dear Python.org Support Team,

I hope this email finds you well. I am writing to seek assistance with an
issue I'm encountering while attempting to uninstall a corrupted Python
installation on my system.

Details of my system:

- Operating System: Windows 10
- Python Version: 3.11.3(64-bit)
- Installation Method: installer from Python.org

Description of the issue: [Provide a brief description of the problem
you're facing, any error messages received, or specific steps you've taken
so far.]

I have already tried the following:

- Deleting python. removing corrupted files from command prompt with
administrative privileges.

However, despite my efforts, I have been unable to successfully uninstall
the corrupted Python installation.


The more stuff you remove by hand the harder it is for the Windows 
installer to act to do an uninstall.


This tool usually helps if things are badly messed up:

https://support.microsoft.com/en-us/topic/fix-problems-that-block-programs-from-being-installed-or-removed-cca7d1b6-65a9-3d98-426b-e9f927e1eb4d

Haven't used it for a while, but after it tries basic overall repairs to 
the installation subsystem (which is probably okay), there are prompts 
you can follow to point to a specific program that doesn't want to 
uninstall.



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


Re: Aw: Re: Extract lines from file, add to new files

2024-01-30 Thread Mats Wichmann via Python-list

On 1/30/24 14:46, AVI GROSS via Python-list wrote:

Rich,

You may want to broaden your perspective a bit when people make suggestions.

Karsten did not spell out a full design and should not need to.

But consider this as a scenario.

You want to send (almost) the same message to one or more recipients.

So call a program, perhaps some variant on a shell script, that does some
prep work such as maybe creating a temporary or working directory/folder.
Had one copy of your message ready in a file somewhere, Have a way to get a
list of recipients intended and the file or files containing enough info to
link email addresses to human names and anything else such as their
preferred pronoun  or address.


I'd say based on the bits of the problem description I *have* absorbed, 
which almost certainly isn't all of them, there's a fairly basic 
capability, not terribly often used in my experience, that might be of 
some use:


https://docs.python.org/3/library/string.html#template-strings


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


Re: Extract lines from file, add to new files

2024-02-03 Thread Mats Wichmann via Python-list

On 2/3/24 10:58, Thomas Passin via Python-list wrote:
In my view this whole thread became murky and complicated because the OP 
did not write down the requirements for the program.  Requirements are 
needed to communicate with other people.  An individual may not need to 
actually write down the requirements - depending on their complexity - 
but they always exist even if only vaguely in a person's mind.  The 
requirements may include what tools or languages the person wants to use 
and why.


If you are asking for help, you need to communicate the requirements to 
the people you are asking for help from.


The OP may have thought the original post(s) contained enough of the 
requirements but as we know by now, they didn't.


The person asking for help may not realize they don't know enough to 
write down all the requirements; an effort to do so may bring that lack 
to visibility.


Mailing lists like these have a drawback that it's hard to impossible 
for someone not involved in a thread to learn anything general from it. 
We can write over and over again to please state clearly what you want 
to do and where the sticking points are, but newcomers post new 
questions without ever reading these pleas.  Then good-hearted people 
who want to be helpful end up spending a lot of time trying to guess 
what is actually being asked for, and maybe never find out with enough 
clarity.  Others take a guess and then spend time working up a solution 
that may or may not be on target.


So please! before posting a request for help, write down the 
requirements as best you can figure them out, and then make sure that 
they are expressed such that the readers can understand.


Indeed.  I've occasionally practised the following technique (in some 
form) over the years without knowing it had grown a name, and wikipedia 
page to go with it.  It may be handy to use to help come up with a 
clearer explanation before sending off a post to a mailing list or other 
static medium, because of the inevitable delays in going back and forth. 
Interactive formus like the Python Discord have a bit of an advantage in 
that you can try to tease out the intent more quickly.  But as you 
say... a newcomer won't know this.


https://en.wikipedia.org/wiki/Rubber_duck_debugging

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


Re: xor operator

2023-11-13 Thread Mats Wichmann via Python-list

On 11/13/23 16:24, Dom Grigonis via Python-list wrote:

I am not arguing that it is a generalised xor.

I don’t want anything, I am just gauging if it is specialised or if there is a 
need for it. So just thought could suggest it as I have encountered such need 
several times already.

It is fairly clear by now that it is not a common one given it took some time 
to even convey what I mean. Bad naming didn’t help ofc, but if it was something 
that is needed I think it would have clicked much faster.


There are things that If You Need Them You Know, and If You Do Not You 
Do Not Understand - and you seem to have found one.  The problem is that 
forums like this are not a statistically great sampling mechanism - a 
few dozen people, perhaps, chime in on many topics; there are millions 
of people using Python. Still, the folks here like to think they're at 
least somewhat representative :)


Hardware and software people may have somewhat different views of xor, 
so *maybe* the topic title added a bit to the muddle.  To me (one of 
those millions), any/all falsy, any/all truthy have some interest, and 
Python does provide those. Once you get into How Many True question - 
whether that's the odd-is-true, even-is-false model, or the 
bail-after-X-truthy-values model, it's not terribly interesting to me: 
once it gets more complex than an all/any decision, I need to check for 
particular combinations specifically. Two-of-six means nothing to me 
until I know which combination of two it is.



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


Re: help: pandas and 2d table

2024-04-13 Thread Mats Wichmann via Python-list

On 4/13/24 07:00, jak via Python-list wrote:

Stefan Ram ha scritto:

jak  wrote or quoted:

Would you show me the path, please?


   I was not able to read xls here, so I used csv instead; Warning:
   the script will overwrite file "file_20240412201813_tmp_DML.csv"!

import pandas as pd

with open( 'file_20240412201813_tmp_DML.csv', 'w' )as out:
 print( '''obj,foo1,foo2,foo3,foo4,foo5,foo6
foo1,aa,ab,zz,ad,ae,af
foo2,ba,bb,bc,bd,zz,bf
foo3,ca,zz,cc,cd,ce,zz
foo4,da,db,dc,dd,de,df
foo5,ea,eb,ec,zz,ee,ef
foo6,fa,fb,fc,fd,fe,ff''', file=out )

df = pd.read_csv( 'file_20240412201813_tmp_DML.csv' )

result = {}

for rownum, row in df.iterrows():
 iterator = row.items()
 _, rowname = next( iterator )
 for colname, value in iterator:
 if value not in result: result[ value ]= []
 result[ value ].append( ( rowname, colname ))

print( result )



In reality what I wanted to achieve was this:

     what = 'zz'
     result = {what: []}

     for rownum, row in df.iterrows():
     iterator = row.items()
     _, rowname = next(iterator)
     for colname, value in iterator:
     if value == what:
     result[what] += [(rowname, colname)]
     print(result)

In any case, thank you again for pointing me in the right direction. I
had lost myself looking for a pandas method that would do this in a
single shot or almost.




doesn't Pandas have a "where" method that can do this kind of thing? Or 
doesn't it match what you are looking for?  Pretty sure numpy does, but 
that's a lot to bring in if you don't need the rest of numpy.



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


Re: Issues with uninstalling python versions on windows server

2024-05-04 Thread Mats Wichmann via Python-list

On 5/3/24 05:55, Tripura Seersha via Python-list wrote:

Hi Team,

I am working on an automation related to uninstalling and installing python 
versions on different windows servers.

I have observed that uninstallation is working only with the account/login 
using which the python version is installed. But for automation, we are not 
aware which account is being used for installation on different machines.


If you want to automate things properly, you need to control 
installation as well as uninstallation - if things are just installed 
via some random user account it's hard to see how you can expect later 
steps without that knowledge to work out.


There's a fair bit of control available; if you haven't already, take a 
look here:


https://docs.python.org/3/using/windows.html#installing-without-ui

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


Re: Issues with uninstalling python versions on windows server

2024-05-10 Thread Mats Wichmann via Python-list

On 5/10/24 03:39, Tripura Seersha via Python-list wrote:

Hi Barry,

Automation is using the system account using which the installation is failing 
with exit code 3. This account has the administrative privileges.

Please help me with this issue.

Thanks,
Seersha


You probably have a better chance of finding the attention of people who 
know about the details either on the Python Discuss board 
(discuss.python.org), or by filing an issue - after first checking 
someone else isn't wrestling with the same problem you are - there are a 
number of uninstall-related issues open 
(https://github.com/python/cpython/issues)


In particular, I see that this part of your issue:

> I have observed that uninstallation is working only with the 
account/login using which the python version is installed


seems to be a known problem, where the user who initiated the install 
has the uninstall registered to their account - see 
https://github.com/python/cpython/issues/69353

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


Re: Variable scope inside and outside functions - global statement being overridden by assignation unless preceded by reference

2024-03-06 Thread Mats Wichmann via Python-list

On 3/6/24 05:55, Jacob Kruger via Python-list wrote:
Ok, simpler version - all the code in a simpler test file, and working 
with two separate variables to explain exactly what am talking about:


If you import the contents of that file into the python interpreter, 
dt_expiry will start off as "1970-01-01 00:00", and, if you execute 
do_it function, it will print out the new value assigned to the 
dt_expiry variable inside that function, but if you then again check the 
value of the dt_expiry variable afterwards, it's reverted to the 1970... 
value?



If I take out the line that removes values from l_test # l_test.clear() 
# before appending new value to it, then it will also not retain it's 
new/additional child items after the function exits, and will just 
revert back to [1, 2, 3] each and every time.



In other words, with some of the variable/object types, if you use a 
function that manipulates the contents of a variable, before then 
re-assigning it a new value, it seems like it might then actually 
update/manipulate the global variable, but, either just calling purely 
content retrieval functions against said objects, or assigning them new 
values from scratch seems to then ignore the global scope specified in 
the first line inside the function?



Hope this makes more sense


No, it doesn't. Your code is working as one would expect. For example, 
adding prints for the l_test variable, and removing the .clear() which 
you claim makes it not work, shows me:


before: l_test=[1, 2, 3], id(l_test)=140153285385856
leaving do_it: l_test=[1, 2, 3, 1, 2, 3, 99], id(l_test)=140153285385856
after: l_test=[1, 2, 3, 1, 2, 3, 99], id(l_test)=140153285385856

It's the same list object, as you can see by the id values. And the list 
is updating as expected.


And... you don't need the global statement for l_test. As it's mutable, 
you can mutate it in the function; the global only acts on assignment. 
Using "global" for that may make your intent more clear to readers 
though, although static checkers will grumble at you.


You must be doing something additional that you're not telling us about.


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


Re: If a dictionary key has a Python list as its value!

2024-03-07 Thread Mats Wichmann via Python-list

On 3/7/24 07:11, Varuna Seneviratna via Python-list wrote:

If a dictionary key has a Python list as its value, you can read the values
one by one in the list using a for-loop like in the following.

d = {k: [1,2,3]}



for v in d[k]:
  print(v)



No tutorial describes this, why?
What is the Python explanation for this behaviour?


Sorry... why is this a surprise? If an object is iterable, you can 
iterate over it.


>>> d = {'key': [1, 2, 3]}
>>> type(d['key'])

>>> val = d['key']
>>> type(val)

>>> for v in val:
... print(v)
...
...
1
2
3
>>>



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


Re: Configuring an object via a dictionary

2024-03-15 Thread Mats Wichmann via Python-list

On 3/15/24 03:30, Loris Bennett via Python-list wrote:

Hi,

I am initialising an object via the following:



 self.source_name = config['source_name']


config.get('source_name', default_if_not_defined)  is a common technique...




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


Re: Can u help me?

2024-03-05 Thread Mats Wichmann via Python-list

On 3/5/24 18:44, Ethan Furman via Python-list wrote:

On 3/5/24 16:49, MRAB via Python-list wrote:
 > On 2024-03-06 00:24, Ethan Furman via Python-list wrote:
 >> On 3/5/24 16:06, Chano Fucks via Python-list wrote:
 >>
 >>> [image: image.png]
 >>
 >> The image is of MS-Windows with the python installation window of 
"Repair Successful".  Hopefully somebody better at

 >> explaining that problem can take it from here...
 >>
 > If the repair was successful, what's the problem?

I imagine the issue is trying get Python to run (as I recall, the python 
icon on the MS-Windows desktop is the installer, not Python itself).


that's often it, yes - you keep getting the installer when you think you 
should get a snazzy Python window. Of course, you don't - Python is a 
command-line/terminal program, not a windows app.  Now if you tried to 
launch IDLE instead, you'd get at least a window.


But we're just guessing here. Perhaps Chano will come back with an 
updated question with some details.

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


Re: the name ``wheel''

2024-03-22 Thread Mats Wichmann via Python-list

On 3/22/24 11:45, Barry via Python-list wrote:




On 22 Mar 2024, at 15:25, Gilmeh Serda via Python-list  
wrote:


Many if not most Linux distributions do not include pip by default.


Really? It came with Manjaro.


Debian and Ubuntu require you to install pip as a separate package.
Also puts venv in its own package.

Fedora leaves all the batteries intact and rhel I assume.


pip is still a separate package in the .rpm world. which makes sense on 
a couple of levels:


* pip releases on its own cycle, you wouldn't want to have to *force* a 
new release of python + python-libs + python-devel + maybe others, if 
you happened want to rev pip forward independently.


* in a distro-packaged world, that's the primary place you get your 
Python packages from, and pip isn't seen as being as necessary, and 
potentially even as destructive. How many times have you seen an article 
that suggests you "sudo pip install randompackage"? Many distro setups 
now disallow installing like that. If you know what you're doing, and 
particularly if you're happy to control a specific environment by 
setting up a virtualenv, then fine, you'll still have access to 
everything you need.


anyway, I seem to recall the original message (which I've since deleted) 
was asking about Windows anyway.  There it's quite unusual to end up 
without pip, but not so unusual to end up without the *command* named 
pip - search path things, and all that. Usually if you "py -m pip 
--version" you'll see it's actually installed, just not accessible using 
the current search path.




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


Re: xkcd.com/353 ( Flying with Python )

2024-03-31 Thread Mats Wichmann via Python-list

On 3/30/24 10:31, MRAB via Python-list wrote:

On 2024-03-30 11:25, Skip Montanaro via Python-list wrote:


> https://xkcd.com/1306/
>   what does  SIGIL   mean?

I think its' a Perl term, referring to the $/@/# symbols in front of
identifiers.


I wouldn't consider '@' to be a sigil any more than I would a unary minus.


Nonetheless, Perl folk do use that term, specifically.

"One thing that distinguishes Perl from other languages is its use of 
sigils; the funny looking symbols placed in front of variable names. "


$   Scalar  $foo
@   Array   @foo
%   Hash%foo
&   Subroutine  
*   Typeglob*foo


>Sigils have many benefits, not least of which is that variables 
can be interpolated into strings with no additional syntax. Perl scripts 
are also easy to read (for people who have bothered to learn Perl!) 
because the nouns stand out from verbs. And new verbs can be added to 
the language without breaking old scripts.


>Programming Perl, Chapter 1, 4th Edition

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


Re: ModuleNotFoundError: No module named 'Paramiko'

2024-04-09 Thread Mats Wichmann via Python-list

On 4/7/24 19:31, Wenyong Wei via Python-list wrote:


Dear Sir/Madam,

Recently I encounter a problem that I can't import paramiko in my computer. My 
PC running on window 10 64 bits. I have investigate this issue via internet, 
there are a lot of solutions for this issue, after trying most of the steps, I 
still can't run this module, the major steps I have try are:


   1.
Install python ver 3.7.1 or 3.11.8 by itself or customer installation (changing 
the installation folder) and check add python to the path.
   2.
pip install paramiko, if ver 3.7.1 installed, need to upgrade the pip version.
   3.
Checking the environment path, there are two path related to the python, one 
for python.exe, the other for \Lib\site-packages\paramiko

can you please provide advice on this issue?


Going to be more explicit than the other answers:

===
If an attempted import gives you ModuleNotFound, that *always* means the 
package is not installed... not at all, or just not in the paths that 
copy of Python is looking in.

===

The problem arises in part because most package installation 
instructions take the simplest approach and just tell you to (for example)


pip install paramiko

So it's installed. But where did it go? You can check where it went:

pip show paramiko

That path ("location") needs to be one where your Python interpreter is 
looking.


If all goes well, "pip" and "python" are perfectly matched, but in the 
current world, there are often several Python interpreters installed 
(projects may require a specific version, an IDE may grab its own 
version, something may create and setup a virtualenv, alternate worlds 
like Conda may set up a Python, the list goes on), and for any given 
installation on Windows, python.exe and the pip excutable pip.exe go in 
different directories anyway, and the Windows PATH doesn't always 
include both, and you easily get mismatches.


As others have said, the way to avoid mismatches is to use pip As A 
Module, specifically a module of the Python you want to use.  So if 
you're using the Python Launcher, that looks like:


py -m pip install paramiko

Hope this helps.

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


Re: Running issues

2024-04-06 Thread Mats Wichmann via Python-list

On 4/5/24 15:32, shannon makasale via Python-list wrote:

Hi there,
My name is Shannon. I installed Python 3.12 on my laptop a couple months ago, 
but realised my school requires me to use 3.11.1.


they can suggest 3.11 and there might be a good reason for that, but you 
should not worry about something as specific as "3.11.1" - use the 
latest release in the 3.11 series.



I uninstalled 3.12 and installed 3.11.1.

Unfortunately, I am unable to run python now. It keeps asking to be modified, 
repaired or uninstalled.

Do you have any suggestions on how to fix this?


I think it's been covered in previous replies, but to be even more explicit:

*Don't* re-run the Python Installer.  Windows will sort of "remember" it 
and may present it to you when you try to launch, and for some reason 
the core team appears unwilling to name it something less ambiguous, 
like python_setup, despite that having been requested several times over 
the years.  You would probably do well to just remove  that file (for 
the case you've described, python-3.11.1-amd64.exe).


Python itself is a command-line tool. You can launch python from inside 
a command shell (Windows Terminal is actually a good choice, even though 
it's not installed by default), usually by typing "py" (unless you 
somehow declined to install the Python launcher), or you can navigate to 
it through the start menu.  You will, however, probably want to use some 
sort of editor to work inside or it gets quite tedious.  You can use the 
included IDLE also via the start menu, or install one of the many free 
choices available.  Your school's curriculum may well guide you here, if 
you want to be able to follow along exactly with classroom presentation, 
screenshots, etc.



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


Re: Flubbed it in the second interation through the string: range error... HOW?

2024-05-29 Thread Mats Wichmann via Python-list

On 5/29/24 08:02, Grant Edwards via Python-list wrote:

On 2024-05-29, Chris Angelico via Python-list  wrote:


print(f"if block {name[index]=} {index=}")


Holy cow!  How did I not know about the f-string {=} thing?



It's more recent than f-strings in general, so it's not that hard to miss.
--
https://mail.python.org/mailman/listinfo/python-list


Re: Terminal Emulator (Posting On Python-List Prohibited)

2024-05-18 Thread Mats Wichmann via Python-list

On 5/18/24 10:48, Grant Edwards via Python-list wrote:

On 2024-05-18, Peter J. Holzer via Python-list  wrote:

On 2024-05-16 19:46:07 +0100, Gordinator via Python-list wrote:


To be fair, the problem is the fact that they use Windows (but I
guess Linux users have to deal with venvs, so we're even.


I don't think Linux users have to deal with venvs any more than
Windows users. Maybe even less because many distributions come with
a decent set of Python packages.


I've been using Python on Linux almost daily for 25 years,


same here, but:

 and I've

yet to use a venv...


Distros have do offer a good selection of packaged Python bits, yes, but 
only for the version of Python that's "native" to that distro release. 
If you need to test other versions of Python, you're mostly on your own. 
 Just as an example, for a particular project  I had one test machine 
running Fedora 38 until just a couple weeks ago, with Python 3.11 as 
"native" with a full suite of packages, but I needed to test 3.12 and 
then the 3.13 pre-releases, as well as occasionally sanity-check the 
"oldest supported Python for this project", which turned out to be 3.6. 
I could build all those Pythons myself and install them to a location I 
can "python3.xx -m pip install" to, but Fedora is nice enough to package 
up a whole bunch of past and future Python versions, so why?  And Fedora 
really discourages doing installs via pip to a system-packaged Python. 
So venvs make managing all that pretty convenient. Dunno why everybody's 
so down on venvs...




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


Re: Serializing pydantic enums

2024-05-29 Thread Mats Wichmann via Python-list

On 5/29/24 13:27, Larry Martell via Python-list wrote:

On Tue, May 28, 2024 at 11:46 AM Left Right via Python-list
 wrote:


Most Python objects aren't serializable into JSON. Pydantic isn't
special in this sense.

What can you do about this? -- Well, if this is a one-of situation,
then, maybe just do it by hand?

If this is a recurring problem: json.dumps() takes a cls argument that
will be used to do the serialization. Extend json.JSONEncoder and
implement the encode() method for the encoder class you are passing. I
believe that the official docs have some information about this too.


Yeah, I know I can do this, but I seem to recall reading that pydantic
handled serialization.  Guess not.


Pydantic devotes some of its documentation to serialization.

https://docs.pydantic.dev/latest/concepts/serialization/

As noted elsewhere, some Python objects are easy to serialize, some you 
need to provide some help. Consider pickling: if you write a class that 
isn't obviously pickleable, the getstate dunder method can be defined to 
help out.  For Pydantic, there's a couple of ways... aliases in 
particular seem designed to help: there's a serialization_alias argument 
to the Field function.

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


Re: From JoyceUlysses.txt -- words occurring exactly once

2024-06-01 Thread Mats Wichmann via Python-list

On 5/31/24 11:59, Dieter Maurer via Python-list wrote:

hmmm, I "sent" this but there was some problem and it remained unsent. 
Just in case it hasn't All Been Said Already, here's the retry:



HenHanna wrote at 2024-5-30 13:03 -0700:


Given a text file of a novel (JoyceUlysses.txt) ...

could someone give me a pretty fast (and simple) Python program that'd
give me a list of all words occurring exactly once?


Your task can be split into several subtasks:
  * parse the text into words

This depends on your notion of "word".
In the simplest case, a word is any maximal sequence of non-whitespace
characters. In this case, you can use `split` for this task


This piece is by far "the hard part", because of the ambiguity. For 
example, if I just say non-whitespace, then I get as distinct words 
followed by punctuation. What about hyphenation - of which there's both 
the compound word forms and the ones at the end of lines if the source 
text has been formatted that way.  Are all-lowercase words different 
than the same word starting with a capital?  What about non-initial 
capitals, as happens a fair bit in modern usage with acronyms, 
trademarks (perhaps not in Ulysses? :-) ), etc. What about accented letters?


If you want what's at least a quick starting point to play with, you 
could use a very simple regex - a fair amount of thought has gone into 
what a "word character" is (\w), so it deals with excluding both 
punctuation and whitespace.


import re
from collections import Counter

with open("JoyceUlysses/txt", "r") as f:
wordcount = Counter(re.findall(r'\w+', f.read().lower()))

Now you have a Counter object counting all the "words" with their 
occurrence counts (by this definition) in the document. You can fish 
through that to answer the questions asked (find entries with a count of 
1, 2, 3, etc.)


Some people Go Big and use something that actually tries to recognize 
the language, and opposed to making assumptions from ranges of 
characters.  nltk is a choice there.  But at this point it's not really 
"simple" any longer (though nltk experts might end up disagreeing with 
that).



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